2012-02-28 05:24:41 -06:00
|
|
|
# Authors:
|
|
|
|
# Alexander Bokovoy <abokovoy@redhat.com>
|
|
|
|
#
|
|
|
|
# Copyright (C) 2011 Red Hat
|
|
|
|
# see file 'COPYING' for use and warranty information
|
|
|
|
#
|
|
|
|
# Portions (C) Andrew Tridgell, Andrew Bartlett
|
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
|
|
|
# Make sure we only run this module at the server where samba4-python
|
|
|
|
# package is installed to avoid issues with unavailable modules
|
|
|
|
|
2015-12-16 12:04:20 -06:00
|
|
|
import re
|
|
|
|
import time
|
|
|
|
|
2015-12-16 09:06:03 -06:00
|
|
|
from ipalib import api, _
|
2012-02-28 05:24:41 -06:00
|
|
|
from ipalib import errors
|
|
|
|
from ipapython import ipautil
|
2015-12-16 12:04:20 -06:00
|
|
|
from ipapython.ipa_log_manager import root_logger
|
2012-10-31 14:52:12 -05:00
|
|
|
from ipapython.dn import DN
|
2012-05-15 12:10:28 -05:00
|
|
|
from ipaserver.install import installutils
|
2012-11-15 04:21:16 -06:00
|
|
|
from ipalib.util import normalize_name
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2015-12-16 09:06:03 -06:00
|
|
|
import os, struct
|
2012-02-28 05:24:41 -06:00
|
|
|
from samba import param
|
|
|
|
from samba import credentials
|
2012-09-13 12:01:55 -05:00
|
|
|
from samba.dcerpc import security, lsa, drsblobs, nbt, netlogon
|
2013-09-11 13:34:55 -05:00
|
|
|
from samba.ndr import ndr_pack, ndr_print
|
2012-02-28 05:24:41 -06:00
|
|
|
from samba import net
|
|
|
|
import samba
|
|
|
|
import random
|
2015-07-21 08:18:40 -05:00
|
|
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
|
|
|
|
from cryptography.hazmat.backends import default_backend
|
2012-09-25 09:23:33 -05:00
|
|
|
try:
|
|
|
|
from ldap.controls import RequestControl as LDAPControl #pylint: disable=F0401
|
|
|
|
except ImportError:
|
|
|
|
from ldap.controls import LDAPControl as LDAPControl #pylint: disable=F0401
|
|
|
|
import ldap as _ldap
|
2013-01-31 05:59:35 -06:00
|
|
|
from ipapython.ipaldap import IPAdmin
|
2012-10-31 14:52:12 -05:00
|
|
|
from ipalib.session import krbccache_dir, krbccache_prefix
|
|
|
|
from dns import resolver, rdatatype
|
|
|
|
from dns.exception import DNSException
|
2013-07-19 09:04:14 -05:00
|
|
|
import pysss_nss_idmap
|
|
|
|
import pysss
|
2015-09-11 06:43:28 -05:00
|
|
|
import six
|
2014-05-29 07:47:17 -05:00
|
|
|
from ipaplatform.paths import paths
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2014-09-02 07:47:29 -05:00
|
|
|
from ldap.filter import escape_filter_chars
|
2014-11-24 07:07:49 -06:00
|
|
|
from time import sleep
|
2014-09-02 07:47:29 -05:00
|
|
|
|
2015-09-11 06:43:28 -05:00
|
|
|
if six.PY3:
|
|
|
|
unicode = str
|
2015-10-08 08:39:14 -05:00
|
|
|
long = int
|
2015-09-11 06:43:28 -05:00
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
__doc__ = _("""
|
|
|
|
Classes to manage trust joins using DCE-RPC calls
|
|
|
|
|
|
|
|
The code in this module relies heavily on samba4-python package
|
|
|
|
and Samba4 python bindings.
|
|
|
|
""")
|
|
|
|
|
2015-06-05 07:57:02 -05:00
|
|
|
# Both constants can be used as masks against trust direction
|
|
|
|
# because bi-directional has two lower bits set.
|
|
|
|
TRUST_ONEWAY = 1
|
|
|
|
TRUST_BIDIRECTIONAL = 3
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2013-02-07 07:59:00 -06:00
|
|
|
def is_sid_valid(sid):
|
|
|
|
try:
|
|
|
|
security.dom_sid(sid)
|
|
|
|
except TypeError:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2012-08-13 08:35:19 -05:00
|
|
|
access_denied_error = errors.ACIError(info=_('CIFS server denied your credentials'))
|
2012-08-01 02:14:09 -05:00
|
|
|
dcerpc_error_codes = {
|
2012-08-13 08:35:19 -05:00
|
|
|
-1073741823:
|
|
|
|
errors.RemoteRetrieveError(reason=_('communication with CIFS server was unsuccessful')),
|
2012-08-01 02:14:09 -05:00
|
|
|
-1073741790: access_denied_error,
|
|
|
|
-1073741715: access_denied_error,
|
|
|
|
-1073741614: access_denied_error,
|
2012-08-13 08:35:19 -05:00
|
|
|
-1073741603:
|
|
|
|
errors.ValidationError(name=_('AD domain controller'), error=_('unsupported functional level')),
|
2013-11-12 03:36:22 -06:00
|
|
|
-1073741811: # NT_STATUS_INVALID_PARAMETER
|
|
|
|
errors.RemoteRetrieveError(
|
|
|
|
reason=_('AD domain controller complains about communication sequence. It may mean unsynchronized time on both sides, for example')),
|
2015-05-08 07:09:13 -05:00
|
|
|
-1073741776: # NT_STATUS_INVALID_PARAMETER_MIX, we simply will skip the binding
|
|
|
|
access_denied_error,
|
|
|
|
-1073741772: # NT_STATUS_OBJECT_NAME_NOT_FOUND
|
|
|
|
errors.RemoteRetrieveError(reason=_('CIFS server configuration does not allow access to \\\\pipe\\lsarpc')),
|
2012-08-01 02:14:09 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
dcerpc_error_messages = {
|
2012-08-13 08:35:19 -05:00
|
|
|
"NT_STATUS_OBJECT_NAME_NOT_FOUND":
|
|
|
|
errors.NotFound(reason=_('Cannot find specified domain or server name')),
|
2014-11-24 07:07:49 -06:00
|
|
|
"WERR_NO_LOGON_SERVERS":
|
|
|
|
errors.RemoteRetrieveError(reason=_('AD DC was unable to reach any IPA domain controller. Most likely it is a DNS or firewall issue')),
|
2012-08-13 08:35:19 -05:00
|
|
|
"NT_STATUS_INVALID_PARAMETER_MIX":
|
|
|
|
errors.RequirementError(name=_('At least the domain or IP address should be specified')),
|
2012-08-01 02:14:09 -05:00
|
|
|
}
|
|
|
|
|
2015-07-22 07:00:37 -05:00
|
|
|
pysss_type_key_translation_dict = {
|
|
|
|
pysss_nss_idmap.ID_USER: 'user',
|
|
|
|
pysss_nss_idmap.ID_GROUP: 'group',
|
|
|
|
# Used for users with magic private groups
|
|
|
|
pysss_nss_idmap.ID_BOTH: 'both',
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2012-08-01 02:14:09 -05:00
|
|
|
def assess_dcerpc_exception(num=None,message=None):
|
|
|
|
"""
|
|
|
|
Takes error returned by Samba bindings and converts it into
|
|
|
|
an IPA error class.
|
|
|
|
"""
|
|
|
|
if num and num in dcerpc_error_codes:
|
|
|
|
return dcerpc_error_codes[num]
|
|
|
|
if message and message in dcerpc_error_messages:
|
|
|
|
return dcerpc_error_messages[message]
|
2012-08-13 08:35:19 -05:00
|
|
|
reason = _('''CIFS server communication error: code "%(num)s",
|
|
|
|
message "%(message)s" (both may be "None")''') % dict(num=num, message=message)
|
|
|
|
return errors.RemoteRetrieveError(reason=reason)
|
2012-08-01 02:14:09 -05:00
|
|
|
|
2015-07-21 08:18:40 -05:00
|
|
|
|
|
|
|
def arcfour_encrypt(key, data):
|
|
|
|
algorithm = algorithms.ARC4(key)
|
|
|
|
cipher = Cipher(algorithm, mode=None, backend=default_backend())
|
|
|
|
encryptor = cipher.encryptor()
|
|
|
|
return encryptor.update(data)
|
|
|
|
|
|
|
|
|
2012-09-25 09:23:33 -05:00
|
|
|
class ExtendedDNControl(LDAPControl):
|
|
|
|
# This class attempts to implement LDAP control that would work
|
|
|
|
# with both python-ldap 2.4.x and 2.3.x, thus there is mix of properties
|
|
|
|
# from both worlds and encodeControlValue has default parameter
|
2012-02-28 05:24:41 -06:00
|
|
|
def __init__(self):
|
2012-09-25 09:23:33 -05:00
|
|
|
self.controlValue = 1
|
2012-02-28 05:24:41 -06:00
|
|
|
self.controlType = "1.2.840.113556.1.4.529"
|
|
|
|
self.criticality = False
|
|
|
|
self.integerValue = 1
|
|
|
|
|
2012-09-25 09:23:33 -05:00
|
|
|
def encodeControlValue(self, value=None):
|
2012-02-28 05:24:41 -06:00
|
|
|
return '0\x03\x02\x01\x01'
|
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2012-06-20 08:08:33 -05:00
|
|
|
class DomainValidator(object):
|
|
|
|
ATTR_FLATNAME = 'ipantflatname'
|
|
|
|
ATTR_SID = 'ipantsecurityidentifier'
|
|
|
|
ATTR_TRUSTED_SID = 'ipanttrusteddomainsid'
|
2012-10-31 14:52:12 -05:00
|
|
|
ATTR_TRUST_PARTNER = 'ipanttrustpartner'
|
|
|
|
ATTR_TRUST_AUTHOUT = 'ipanttrustauthoutgoing'
|
2012-06-20 08:08:33 -05:00
|
|
|
|
|
|
|
def __init__(self, api):
|
|
|
|
self.api = api
|
|
|
|
self.ldap = self.api.Backend.ldap2
|
|
|
|
self.domain = None
|
|
|
|
self.flatname = None
|
|
|
|
self.dn = None
|
|
|
|
self.sid = None
|
|
|
|
self._domains = None
|
2012-10-31 14:52:12 -05:00
|
|
|
self._info = dict()
|
|
|
|
self._creds = None
|
2015-07-06 09:46:24 -05:00
|
|
|
self._admin_creds = None
|
2012-10-31 14:52:12 -05:00
|
|
|
self._parm = None
|
2012-06-20 08:08:33 -05:00
|
|
|
|
|
|
|
def is_configured(self):
|
|
|
|
cn_trust_local = DN(('cn', self.api.env.domain), self.api.env.container_cifsdomains, self.api.env.basedn)
|
|
|
|
try:
|
2013-10-31 11:54:21 -05:00
|
|
|
entry_attrs = self.ldap.get_entry(cn_trust_local, [self.ATTR_FLATNAME, self.ATTR_SID])
|
2012-06-20 08:08:33 -05:00
|
|
|
self.flatname = entry_attrs[self.ATTR_FLATNAME][0]
|
|
|
|
self.sid = entry_attrs[self.ATTR_SID][0]
|
2013-10-31 11:54:21 -05:00
|
|
|
self.dn = entry_attrs.dn
|
2012-06-20 08:08:33 -05:00
|
|
|
self.domain = self.api.env.domain
|
2015-07-30 09:49:29 -05:00
|
|
|
except errors.NotFound as e:
|
2012-06-20 08:08:33 -05:00
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def get_trusted_domains(self):
|
2013-07-25 06:54:39 -05:00
|
|
|
"""
|
|
|
|
Returns case-insensitive dict of trusted domain tuples
|
|
|
|
(flatname, sid, trust_auth_outgoing), keyed by domain name.
|
|
|
|
"""
|
|
|
|
cn_trust = DN(('cn', 'ad'), self.api.env.container_trusts,
|
|
|
|
self.api.env.basedn)
|
|
|
|
|
2012-06-20 08:08:33 -05:00
|
|
|
try:
|
|
|
|
search_kw = {'objectClass': 'ipaNTTrustedDomain'}
|
|
|
|
filter = self.ldap.make_filter(search_kw, rules=self.ldap.MATCH_ALL)
|
2013-07-25 06:54:39 -05:00
|
|
|
(entries, truncated) = self.ldap.find_entries(
|
|
|
|
filter=filter,
|
|
|
|
base_dn=cn_trust,
|
|
|
|
attrs_list=[self.ATTR_TRUSTED_SID,
|
|
|
|
self.ATTR_FLATNAME,
|
2013-09-27 05:36:59 -05:00
|
|
|
self.ATTR_TRUST_PARTNER]
|
2013-07-25 06:54:39 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
# We need to use case-insensitive dictionary since we use
|
|
|
|
# domain names as keys and those are generally case-insensitive
|
|
|
|
result = ipautil.CIDict()
|
2012-06-20 08:08:33 -05:00
|
|
|
|
2013-10-31 11:54:21 -05:00
|
|
|
for entry in entries:
|
2013-01-24 04:51:58 -06:00
|
|
|
try:
|
|
|
|
trust_partner = entry[self.ATTR_TRUST_PARTNER][0]
|
|
|
|
flatname_normalized = entry[self.ATTR_FLATNAME][0].lower()
|
|
|
|
trusted_sid = entry[self.ATTR_TRUSTED_SID][0]
|
2015-07-30 09:49:29 -05:00
|
|
|
except KeyError as e:
|
2013-01-24 04:51:58 -06:00
|
|
|
# Some piece of trusted domain info in LDAP is missing
|
|
|
|
# Skip the domain, but leave log entry for investigation
|
2013-07-25 06:54:39 -05:00
|
|
|
api.log.warn("Trusted domain '%s' entry misses an "
|
2013-10-31 11:54:21 -05:00
|
|
|
"attribute: %s", entry.dn, e)
|
2013-01-24 04:51:58 -06:00
|
|
|
continue
|
2013-07-25 06:54:39 -05:00
|
|
|
|
2013-01-24 04:51:58 -06:00
|
|
|
result[trust_partner] = (flatname_normalized,
|
2013-09-27 05:36:59 -05:00
|
|
|
security.dom_sid(trusted_sid))
|
2012-09-25 09:25:42 -05:00
|
|
|
return result
|
2015-07-30 09:49:29 -05:00
|
|
|
except errors.NotFound as e:
|
2012-06-20 08:08:33 -05:00
|
|
|
return []
|
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
def set_trusted_domains(self):
|
|
|
|
# At this point we have SID_NT_AUTHORITY family SID and really need to
|
|
|
|
# check it against prefixes of domain SIDs we trust to
|
|
|
|
if not self._domains:
|
|
|
|
self._domains = self.get_trusted_domains()
|
|
|
|
if len(self._domains) == 0:
|
|
|
|
# Our domain is configured but no trusted domains are configured
|
|
|
|
# This means we can't check the correctness of a trusted
|
|
|
|
# domain SIDs
|
|
|
|
raise errors.ValidationError(name='sid',
|
|
|
|
error=_('no trusted domain is configured'))
|
|
|
|
|
2013-03-06 05:17:28 -06:00
|
|
|
def get_domain_by_sid(self, sid, exact_match=False):
|
2012-06-20 08:08:33 -05:00
|
|
|
if not self.domain:
|
|
|
|
# our domain is not configured or self.is_configured() never run
|
|
|
|
# reject SIDs as we can't check correctness of them
|
2013-01-18 10:28:39 -06:00
|
|
|
raise errors.ValidationError(name='sid',
|
|
|
|
error=_('domain is not configured'))
|
2013-03-06 05:17:28 -06:00
|
|
|
|
2012-06-20 08:08:33 -05:00
|
|
|
# Parse sid string to see if it is really in a SID format
|
|
|
|
try:
|
|
|
|
test_sid = security.dom_sid(sid)
|
2013-03-06 05:17:28 -06:00
|
|
|
except TypeError:
|
2013-01-18 10:28:39 -06:00
|
|
|
raise errors.ValidationError(name='sid',
|
|
|
|
error=_('SID is not valid'))
|
2013-03-06 05:17:28 -06:00
|
|
|
|
2012-06-20 08:08:33 -05:00
|
|
|
# At this point we have SID_NT_AUTHORITY family SID and really need to
|
|
|
|
# check it against prefixes of domain SIDs we trust to
|
2013-07-17 08:55:36 -05:00
|
|
|
self.set_trusted_domains()
|
2013-03-06 05:17:28 -06:00
|
|
|
|
|
|
|
# We have non-zero list of trusted domains and have to go through
|
|
|
|
# them one by one and check their sids as prefixes / exact match
|
|
|
|
# depending on the value of exact_match flag
|
|
|
|
if exact_match:
|
|
|
|
# check exact match of sids
|
|
|
|
for domain in self._domains:
|
|
|
|
if sid == str(self._domains[domain][1]):
|
|
|
|
return domain
|
|
|
|
|
|
|
|
raise errors.NotFound(reason=_("SID does not match exactly"
|
|
|
|
"with any trusted domain's SID"))
|
|
|
|
else:
|
|
|
|
# check as prefixes
|
|
|
|
test_sid_subauths = test_sid.sub_auths
|
|
|
|
for domain in self._domains:
|
|
|
|
domsid = self._domains[domain][1]
|
|
|
|
sub_auths = domsid.sub_auths
|
|
|
|
num_auths = min(test_sid.num_auths, domsid.num_auths)
|
|
|
|
if test_sid_subauths[:num_auths] == sub_auths[:num_auths]:
|
|
|
|
return domain
|
|
|
|
raise errors.NotFound(reason=_('SID does not match any '
|
|
|
|
'trusted domain'))
|
2013-01-18 10:28:39 -06:00
|
|
|
|
|
|
|
def is_trusted_sid_valid(self, sid):
|
|
|
|
try:
|
|
|
|
self.get_domain_by_sid(sid)
|
|
|
|
except (errors.ValidationError, errors.NotFound):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
2012-06-20 08:08:33 -05:00
|
|
|
|
2013-03-06 05:17:28 -06:00
|
|
|
def is_trusted_domain_sid_valid(self, sid):
|
|
|
|
try:
|
|
|
|
self.get_domain_by_sid(sid, exact_match=True)
|
|
|
|
except (errors.ValidationError, errors.NotFound):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
|
2013-02-04 07:33:53 -06:00
|
|
|
def get_sid_from_domain_name(self, name):
|
|
|
|
"""Returns binary representation of SID for the trusted domain name
|
|
|
|
or None if name is not in the list of trusted domains."""
|
|
|
|
|
|
|
|
domains = self.get_trusted_domains()
|
|
|
|
if name in domains:
|
|
|
|
return domains[name][1]
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
2013-01-18 10:28:39 -06:00
|
|
|
def get_trusted_domain_objects(self, domain=None, flatname=None, filter="",
|
|
|
|
attrs=None, scope=_ldap.SCOPE_SUBTREE, basedn=None):
|
|
|
|
"""
|
|
|
|
Search for LDAP objects in a trusted domain specified either by `domain'
|
|
|
|
or `flatname'. The actual LDAP search is specified by `filter', `attrs',
|
|
|
|
`scope' and `basedn'. When `basedn' is empty, database root DN is used.
|
|
|
|
"""
|
|
|
|
assert domain is not None or flatname is not None
|
2012-10-31 14:52:12 -05:00
|
|
|
"""Returns SID for the trusted domain object (user or group only)"""
|
|
|
|
if not self.domain:
|
|
|
|
# our domain is not configured or self.is_configured() never run
|
2013-01-18 10:28:39 -06:00
|
|
|
raise errors.ValidationError(name=_('Trust setup'),
|
|
|
|
error=_('Our domain is not configured'))
|
2012-10-31 14:52:12 -05:00
|
|
|
if not self._domains:
|
|
|
|
self._domains = self.get_trusted_domains()
|
|
|
|
if len(self._domains) == 0:
|
|
|
|
# Our domain is configured but no trusted domains are configured
|
2013-01-18 10:28:39 -06:00
|
|
|
raise errors.ValidationError(name=_('Trust setup'),
|
|
|
|
error=_('No trusted domain is not configured'))
|
2012-10-31 14:52:12 -05:00
|
|
|
|
2013-01-18 10:28:39 -06:00
|
|
|
entries = None
|
|
|
|
if domain is not None:
|
|
|
|
if domain not in self._domains:
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('domain is not trusted'))
|
2012-10-31 14:52:12 -05:00
|
|
|
# Now we have a name to check against our list of trusted domains
|
2013-07-17 08:55:36 -05:00
|
|
|
entries = self.search_in_dc(domain, filter, attrs, scope, basedn)
|
2013-01-18 10:28:39 -06:00
|
|
|
elif flatname is not None:
|
2012-10-31 14:52:12 -05:00
|
|
|
# Flatname was specified, traverse through the list of trusted
|
|
|
|
# domains first to find the proper one
|
2013-01-18 10:28:39 -06:00
|
|
|
found_flatname = False
|
2012-10-31 14:52:12 -05:00
|
|
|
for domain in self._domains:
|
2013-01-18 10:28:39 -06:00
|
|
|
if self._domains[domain][0] == flatname:
|
|
|
|
found_flatname = True
|
2013-07-17 08:55:36 -05:00
|
|
|
entries = self.search_in_dc(domain, filter, attrs, scope, basedn)
|
2013-01-18 10:28:39 -06:00
|
|
|
if entries:
|
2012-10-31 14:52:12 -05:00
|
|
|
break
|
2013-01-18 10:28:39 -06:00
|
|
|
if not found_flatname:
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('no trusted domain matched the specified flat name'))
|
|
|
|
if not entries:
|
|
|
|
raise errors.NotFound(reason=_('trusted domain object not found'))
|
|
|
|
|
|
|
|
return entries
|
|
|
|
|
2015-04-29 01:16:13 -05:00
|
|
|
def get_trusted_domain_object_sid(self, object_name, fallback_to_ldap=True):
|
2013-07-19 09:04:14 -05:00
|
|
|
result = pysss_nss_idmap.getsidbyname(object_name)
|
|
|
|
if object_name in result and (pysss_nss_idmap.SID_KEY in result[object_name]):
|
|
|
|
object_sid = result[object_name][pysss_nss_idmap.SID_KEY]
|
|
|
|
return object_sid
|
|
|
|
|
2015-04-29 01:16:13 -05:00
|
|
|
# If fallback to AD DC LDAP is not allowed, bail out
|
|
|
|
if not fallback_to_ldap:
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('SSSD was unable to resolve the object to a valid SID'))
|
|
|
|
|
2013-07-19 09:04:14 -05:00
|
|
|
# Else, we are going to contact AD DC LDAP
|
2013-01-18 10:28:39 -06:00
|
|
|
components = normalize_name(object_name)
|
|
|
|
if not ('domain' in components or 'flatname' in components):
|
|
|
|
# No domain or realm specified, ambiguous search
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('Ambiguous search, user domain was not specified'))
|
|
|
|
|
|
|
|
attrs = ['objectSid']
|
|
|
|
filter = '(&(sAMAccountName=%(name)s)(|(objectClass=user)(objectClass=group)))' \
|
|
|
|
% dict(name=components['name'])
|
|
|
|
scope = _ldap.SCOPE_SUBTREE
|
|
|
|
entries = self.get_trusted_domain_objects(components.get('domain'),
|
|
|
|
components.get('flatname'), filter, attrs, scope)
|
|
|
|
|
|
|
|
if len(entries) > 1:
|
|
|
|
# Treat non-unique entries as invalid
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('Trusted domain did not return a unique object'))
|
2013-10-31 11:54:21 -05:00
|
|
|
sid = self.__sid_to_str(entries[0]['objectSid'][0])
|
2013-01-18 10:28:39 -06:00
|
|
|
try:
|
|
|
|
test_sid = security.dom_sid(sid)
|
|
|
|
return unicode(test_sid)
|
2015-07-30 09:49:29 -05:00
|
|
|
except TypeError as e:
|
2013-01-18 10:28:39 -06:00
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('Trusted domain did not return a valid SID for the object'))
|
2012-10-31 14:52:12 -05:00
|
|
|
|
2015-07-22 07:00:37 -05:00
|
|
|
def get_trusted_domain_object_type(self, name_or_sid):
|
|
|
|
"""
|
|
|
|
Return the type of the object corresponding to the given name in
|
|
|
|
the trusted domain, which is either 'user', 'group' or 'both'.
|
|
|
|
The 'both' types is used for users with magic private groups.
|
|
|
|
"""
|
|
|
|
|
|
|
|
object_type = None
|
|
|
|
|
|
|
|
if is_sid_valid(name_or_sid):
|
|
|
|
result = pysss_nss_idmap.getnamebysid(name_or_sid)
|
|
|
|
else:
|
|
|
|
result = pysss_nss_idmap.getsidbyname(name_or_sid)
|
|
|
|
|
|
|
|
if name_or_sid in result:
|
|
|
|
object_type = result[name_or_sid].get(pysss_nss_idmap.TYPE_KEY)
|
|
|
|
|
|
|
|
# Do the translation to hide pysss_nss_idmap constants
|
|
|
|
# from higher-level code
|
|
|
|
return pysss_type_key_translation_dict.get(object_type)
|
|
|
|
|
2014-09-02 07:47:29 -05:00
|
|
|
def get_trusted_domain_object_from_sid(self, sid):
|
2015-04-29 01:16:00 -05:00
|
|
|
root_logger.debug("Converting SID to object name: %s" % sid)
|
2014-09-02 07:47:29 -05:00
|
|
|
|
|
|
|
# Check if the given SID is valid
|
|
|
|
if not self.is_trusted_sid_valid(sid):
|
|
|
|
raise errors.ValidationError(name='sid', error='SID is not valid')
|
|
|
|
|
|
|
|
# Use pysss_nss_idmap to obtain the name
|
|
|
|
result = pysss_nss_idmap.getnamebysid(sid).get(sid)
|
|
|
|
|
|
|
|
valid_types = (pysss_nss_idmap.ID_USER,
|
|
|
|
pysss_nss_idmap.ID_GROUP,
|
|
|
|
pysss_nss_idmap.ID_BOTH)
|
|
|
|
|
|
|
|
if result:
|
|
|
|
if result.get(pysss_nss_idmap.TYPE_KEY) in valid_types:
|
|
|
|
return result.get(pysss_nss_idmap.NAME_KEY)
|
|
|
|
|
|
|
|
# If unsuccessful, search AD DC LDAP
|
2015-04-29 01:16:00 -05:00
|
|
|
root_logger.debug("Searching AD DC LDAP")
|
2014-09-02 07:47:29 -05:00
|
|
|
|
|
|
|
escaped_sid = escape_filter_chars(
|
|
|
|
security.dom_sid(sid).__ndr_pack__(),
|
|
|
|
2 # 2 means every character needs to be escaped
|
|
|
|
)
|
|
|
|
|
|
|
|
attrs = ['sAMAccountName']
|
|
|
|
filter = (r'(&(objectSid=%(sid)s)(|(objectClass=user)(objectClass=group)))'
|
|
|
|
% dict(sid=escaped_sid)) # sid in binary
|
|
|
|
domain = self.get_domain_by_sid(sid)
|
|
|
|
|
|
|
|
entries = self.get_trusted_domain_objects(domain=domain,
|
|
|
|
filter=filter,
|
|
|
|
attrs=attrs)
|
|
|
|
|
|
|
|
if len(entries) > 1:
|
|
|
|
# Treat non-unique entries as invalid
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error=_('Trusted domain did not return a unique object'))
|
|
|
|
|
|
|
|
object_name = (
|
|
|
|
"%s@%s" % (entries[0].single_value['sAMAccountName'].lower(),
|
|
|
|
domain.lower())
|
|
|
|
)
|
|
|
|
|
|
|
|
return unicode(object_name)
|
|
|
|
|
2013-07-19 09:04:14 -05:00
|
|
|
def __get_trusted_domain_user_and_groups(self, object_name):
|
2013-01-18 10:38:15 -06:00
|
|
|
"""
|
|
|
|
Returns a tuple with user SID and a list of SIDs of all groups he is
|
|
|
|
a member of.
|
|
|
|
|
|
|
|
LIMITATIONS:
|
|
|
|
- only Trusted Admins group members can use this function as it
|
|
|
|
uses secret for IPA-Trusted domain link
|
|
|
|
- List of group SIDs does not contain group memberships outside
|
|
|
|
of the trusted domain
|
|
|
|
"""
|
|
|
|
components = normalize_name(object_name)
|
|
|
|
domain = components.get('domain')
|
|
|
|
flatname = components.get('flatname')
|
|
|
|
name = components.get('name')
|
|
|
|
|
|
|
|
is_valid_sid = is_sid_valid(object_name)
|
|
|
|
if is_valid_sid:
|
|
|
|
# Find a trusted domain for the SID
|
|
|
|
domain = self.get_domain_by_sid(object_name)
|
|
|
|
# Now search a trusted domain for a user with this SID
|
|
|
|
attrs = ['cn']
|
|
|
|
filter = '(&(objectClass=user)(objectSid=%(sid)s))' \
|
|
|
|
% dict(sid=object_name)
|
|
|
|
try:
|
|
|
|
entries = self.get_trusted_domain_objects(domain=domain, filter=filter,
|
|
|
|
attrs=attrs, scope=_ldap.SCOPE_SUBTREE)
|
|
|
|
except errors.NotFound:
|
|
|
|
raise errors.NotFound(reason=_('trusted domain user not found'))
|
2013-10-31 11:54:21 -05:00
|
|
|
user_dn = entries[0].dn
|
2013-01-18 10:38:15 -06:00
|
|
|
elif domain or flatname:
|
|
|
|
attrs = ['cn']
|
|
|
|
filter = '(&(sAMAccountName=%(name)s)(objectClass=user))' \
|
|
|
|
% dict(name=name)
|
|
|
|
try:
|
|
|
|
entries = self.get_trusted_domain_objects(domain,
|
|
|
|
flatname, filter, attrs, _ldap.SCOPE_SUBTREE)
|
|
|
|
except errors.NotFound:
|
|
|
|
raise errors.NotFound(reason=_('trusted domain user not found'))
|
2013-10-31 11:54:21 -05:00
|
|
|
user_dn = entries[0].dn
|
2013-01-18 10:38:15 -06:00
|
|
|
else:
|
|
|
|
# No domain or realm specified, ambiguous search
|
|
|
|
raise errors.ValidationError(name=_('trusted domain object'),
|
|
|
|
error= _('Ambiguous search, user domain was not specified'))
|
|
|
|
|
|
|
|
# Get SIDs of user object and it's groups
|
|
|
|
# tokenGroups attribute must be read with a scope BASE for a known user
|
|
|
|
# distinguished name to avoid search error
|
|
|
|
attrs = ['objectSID', 'tokenGroups']
|
|
|
|
filter = "(objectClass=user)"
|
|
|
|
entries = self.get_trusted_domain_objects(domain,
|
|
|
|
flatname, filter, attrs, _ldap.SCOPE_BASE, user_dn)
|
2013-10-31 11:54:21 -05:00
|
|
|
object_sid = self.__sid_to_str(entries[0]['objectSid'][0])
|
|
|
|
group_sids = [self.__sid_to_str(sid) for sid in entries[0]['tokenGroups']]
|
2013-01-18 10:38:15 -06:00
|
|
|
return (object_sid, group_sids)
|
|
|
|
|
2013-07-19 09:04:14 -05:00
|
|
|
def get_trusted_domain_user_and_groups(self, object_name):
|
|
|
|
"""
|
|
|
|
Returns a tuple with user SID and a list of SIDs of all groups he is
|
|
|
|
a member of.
|
|
|
|
|
|
|
|
First attempts to perform SID lookup via SSSD and in case of failure
|
|
|
|
resorts back to checking trusted domain's AD DC LDAP directly.
|
|
|
|
|
|
|
|
LIMITATIONS:
|
|
|
|
- only Trusted Admins group members can use this function as it
|
|
|
|
uses secret for IPA-Trusted domain link if SSSD lookup failed
|
|
|
|
- List of group SIDs does not contain group memberships outside
|
|
|
|
of the trusted domain
|
|
|
|
"""
|
|
|
|
group_sids = None
|
|
|
|
group_list = None
|
|
|
|
object_sid = None
|
|
|
|
is_valid_sid = is_sid_valid(object_name)
|
|
|
|
if is_valid_sid:
|
|
|
|
object_sid = object_name
|
|
|
|
result = pysss_nss_idmap.getnamebysid(object_name)
|
|
|
|
if object_name in result and (pysss_nss_idmap.NAME_KEY in result[object_name]):
|
|
|
|
group_list = pysss.getgrouplist(result[object_name][pysss_nss_idmap.NAME_KEY])
|
|
|
|
else:
|
|
|
|
result = pysss_nss_idmap.getsidbyname(object_name)
|
|
|
|
if object_name in result and (pysss_nss_idmap.SID_KEY in result[object_name]):
|
|
|
|
object_sid = result[object_name][pysss_nss_idmap.SID_KEY]
|
|
|
|
group_list = pysss.getgrouplist(object_name)
|
|
|
|
|
|
|
|
if not group_list:
|
|
|
|
return self.__get_trusted_domain_user_and_groups(object_name)
|
|
|
|
|
|
|
|
group_sids = pysss_nss_idmap.getsidbyname(group_list)
|
|
|
|
return (object_sid, [el[1][pysss_nss_idmap.SID_KEY] for el in group_sids.items()])
|
|
|
|
|
2012-10-31 14:52:12 -05:00
|
|
|
def __sid_to_str(self, sid):
|
|
|
|
"""
|
|
|
|
Converts binary SID to string representation
|
|
|
|
Returns unicode string
|
|
|
|
"""
|
|
|
|
sid_rev_num = ord(sid[0])
|
|
|
|
number_sub_id = ord(sid[1])
|
|
|
|
ia = struct.unpack('!Q','\x00\x00'+sid[2:8])[0]
|
|
|
|
subs = [
|
|
|
|
struct.unpack('<I',sid[8+4*i:12+4*i])[0]
|
|
|
|
for i in range(number_sub_id)
|
|
|
|
]
|
|
|
|
return u'S-%d-%d-%s' % ( sid_rev_num, ia, '-'.join([str(s) for s in subs]),)
|
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
def kinit_as_http(self, domain):
|
|
|
|
"""
|
|
|
|
Initializes ccache with http service credentials.
|
|
|
|
|
|
|
|
Applies session code defaults for ccache directory and naming prefix.
|
|
|
|
Session code uses krbccache_prefix+<pid>, we use
|
|
|
|
krbccache_prefix+<TD>+<domain netbios name> so there is no clash.
|
|
|
|
|
|
|
|
Returns tuple (ccache path, principal) where (None, None) signifes an
|
|
|
|
error on ccache initialization
|
|
|
|
"""
|
|
|
|
|
|
|
|
domain_suffix = domain.replace('.', '-')
|
|
|
|
|
|
|
|
ccache_name = "%sTD%s" % (krbccache_prefix, domain_suffix)
|
|
|
|
ccache_path = os.path.join(krbccache_dir, ccache_name)
|
|
|
|
|
|
|
|
realm = api.env.realm
|
|
|
|
hostname = api.env.host
|
|
|
|
principal = 'HTTP/%s@%s' % (hostname, realm)
|
2014-05-29 07:47:17 -05:00
|
|
|
keytab = paths.IPA_KEYTAB
|
2013-07-17 08:55:36 -05:00
|
|
|
|
|
|
|
# Destroy the contents of the ccache
|
|
|
|
root_logger.debug('Destroying the contents of the separate ccache')
|
|
|
|
|
2015-11-25 10:17:18 -06:00
|
|
|
ipautil.run(
|
2014-05-29 07:47:17 -05:00
|
|
|
[paths.KDESTROY, '-A', '-c', ccache_path],
|
2013-07-17 08:55:36 -05:00
|
|
|
env={'KRB5CCNAME': ccache_path},
|
|
|
|
raiseonerr=False)
|
|
|
|
|
|
|
|
# Destroy the contents of the ccache
|
|
|
|
root_logger.debug('Running kinit from ipa.keytab to obtain HTTP '
|
|
|
|
'service principal with MS-PAC attached.')
|
|
|
|
|
2015-11-25 10:17:18 -06:00
|
|
|
result = ipautil.run(
|
2014-05-29 07:47:17 -05:00
|
|
|
[paths.KINIT, '-kt', keytab, principal],
|
2013-07-17 08:55:36 -05:00
|
|
|
env={'KRB5CCNAME': ccache_path},
|
|
|
|
raiseonerr=False)
|
|
|
|
|
2015-11-25 10:17:18 -06:00
|
|
|
if result.returncode == 0:
|
2013-07-17 08:55:36 -05:00
|
|
|
return (ccache_path, principal)
|
|
|
|
else:
|
|
|
|
return (None, None)
|
|
|
|
|
2015-07-06 09:46:24 -05:00
|
|
|
def kinit_as_administrator(self, domain):
|
|
|
|
"""
|
|
|
|
Initializes ccache with http service credentials.
|
|
|
|
|
|
|
|
Applies session code defaults for ccache directory and naming prefix.
|
|
|
|
Session code uses krbccache_prefix+<pid>, we use
|
|
|
|
krbccache_prefix+<TD>+<domain netbios name> so there is no clash.
|
|
|
|
|
|
|
|
Returns tuple (ccache path, principal) where (None, None) signifes an
|
|
|
|
error on ccache initialization
|
|
|
|
"""
|
|
|
|
|
|
|
|
if self._admin_creds == None:
|
|
|
|
return (None, None)
|
|
|
|
|
|
|
|
domain_suffix = domain.replace('.', '-')
|
|
|
|
|
|
|
|
ccache_name = "%sTDA%s" % (krbccache_prefix, domain_suffix)
|
|
|
|
ccache_path = os.path.join(krbccache_dir, ccache_name)
|
|
|
|
|
|
|
|
(principal, password) = self._admin_creds.split('%', 1)
|
|
|
|
|
|
|
|
# Destroy the contents of the ccache
|
|
|
|
root_logger.debug('Destroying the contents of the separate ccache')
|
|
|
|
|
2015-11-25 10:17:18 -06:00
|
|
|
ipautil.run(
|
2015-07-06 09:46:24 -05:00
|
|
|
[paths.KDESTROY, '-A', '-c', ccache_path],
|
|
|
|
env={'KRB5CCNAME': ccache_path},
|
|
|
|
raiseonerr=False)
|
|
|
|
|
|
|
|
# Destroy the contents of the ccache
|
|
|
|
root_logger.debug('Running kinit with credentials of AD administrator')
|
|
|
|
|
2015-11-25 10:17:18 -06:00
|
|
|
result = ipautil.run(
|
2015-07-06 09:46:24 -05:00
|
|
|
[paths.KINIT, principal],
|
|
|
|
env={'KRB5CCNAME': ccache_path},
|
|
|
|
stdin=password,
|
|
|
|
raiseonerr=False)
|
|
|
|
|
2015-11-25 10:17:18 -06:00
|
|
|
if result.returncode == 0:
|
2015-07-06 09:46:24 -05:00
|
|
|
return (ccache_path, principal)
|
|
|
|
else:
|
|
|
|
return (None, None)
|
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
def search_in_dc(self, domain, filter, attrs, scope, basedn=None,
|
2013-09-27 05:36:59 -05:00
|
|
|
quiet=False):
|
2012-10-31 14:52:12 -05:00
|
|
|
"""
|
2013-07-17 08:55:36 -05:00
|
|
|
Perform LDAP search in a trusted domain `domain' Domain Controller.
|
|
|
|
Returns resulting entries or None.
|
2012-10-31 14:52:12 -05:00
|
|
|
"""
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2013-01-18 10:28:39 -06:00
|
|
|
entries = None
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2012-10-31 14:52:12 -05:00
|
|
|
info = self.__retrieve_trusted_domain_gc_list(domain)
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2012-10-31 14:52:12 -05:00
|
|
|
if not info:
|
2013-07-17 08:55:36 -05:00
|
|
|
raise errors.ValidationError(
|
|
|
|
name=_('Trust setup'),
|
2013-01-18 10:28:39 -06:00
|
|
|
error=_('Cannot retrieve trusted domain GC list'))
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2012-10-31 14:52:12 -05:00
|
|
|
for (host, port) in info['gc']:
|
2013-07-17 08:55:36 -05:00
|
|
|
entries = self.__search_in_dc(info, host, port, filter, attrs,
|
|
|
|
scope, basedn=basedn,
|
|
|
|
quiet=quiet)
|
2013-01-18 10:28:39 -06:00
|
|
|
if entries:
|
2012-10-31 14:52:12 -05:00
|
|
|
break
|
|
|
|
|
2013-01-18 10:28:39 -06:00
|
|
|
return entries
|
2012-10-31 14:52:12 -05:00
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
def __search_in_dc(self, info, host, port, filter, attrs, scope,
|
2013-09-27 05:36:59 -05:00
|
|
|
basedn=None, quiet=False):
|
2012-10-31 14:52:12 -05:00
|
|
|
"""
|
2013-01-18 10:28:39 -06:00
|
|
|
Actual search in AD LDAP server, using SASL GSSAPI authentication
|
2013-07-17 08:55:36 -05:00
|
|
|
Returns LDAP result or None.
|
2012-10-31 14:52:12 -05:00
|
|
|
"""
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2015-07-22 07:29:35 -05:00
|
|
|
ccache_name = None
|
|
|
|
|
2015-07-06 09:46:24 -05:00
|
|
|
if self._admin_creds:
|
|
|
|
(ccache_name, principal) = self.kinit_as_administrator(info['dns_domain'])
|
2013-07-17 08:55:36 -05:00
|
|
|
|
|
|
|
if ccache_name:
|
2015-06-04 06:59:22 -05:00
|
|
|
with ipautil.private_ccache(path=ccache_name):
|
2013-07-17 08:55:36 -05:00
|
|
|
entries = None
|
|
|
|
|
|
|
|
try:
|
|
|
|
conn = IPAdmin(host=host,
|
|
|
|
port=389, # query the AD DC
|
|
|
|
no_schema=True,
|
|
|
|
decode_attrs=False,
|
|
|
|
sasl_nocanon=True)
|
|
|
|
# sasl_nocanon used to avoid hard requirement for PTR
|
|
|
|
# records pointing back to the same host name
|
|
|
|
|
|
|
|
conn.do_sasl_gssapi_bind()
|
|
|
|
|
|
|
|
if basedn is None:
|
|
|
|
# Use domain root base DN
|
|
|
|
basedn = ipautil.realm_to_suffix(info['dns_domain'])
|
|
|
|
|
|
|
|
entries = conn.get_entries(basedn, scope, filter, attrs)
|
2015-07-30 09:49:29 -05:00
|
|
|
except Exception as e:
|
2013-07-17 08:55:36 -05:00
|
|
|
msg = "Search on AD DC {host}:{port} failed with: {err}"\
|
|
|
|
.format(host=host, port=str(port), err=str(e))
|
|
|
|
if quiet:
|
|
|
|
root_logger.debug(msg)
|
|
|
|
else:
|
|
|
|
root_logger.warning(msg)
|
|
|
|
finally:
|
|
|
|
return entries
|
2012-10-31 14:52:12 -05:00
|
|
|
|
|
|
|
def __retrieve_trusted_domain_gc_list(self, domain):
|
|
|
|
"""
|
|
|
|
Retrieves domain information and preferred GC list
|
|
|
|
Returns dictionary with following keys
|
|
|
|
name -- NetBIOS name of the trusted domain
|
|
|
|
dns_domain -- DNS name of the trusted domain
|
|
|
|
gc -- array of tuples (server, port) for Global Catalog
|
|
|
|
"""
|
|
|
|
if domain in self._info:
|
|
|
|
return self._info[domain]
|
|
|
|
|
|
|
|
if not self._creds:
|
|
|
|
self._parm = param.LoadParm()
|
|
|
|
self._parm.load(os.path.join(ipautil.SHARE_DIR,"smb.conf.empty"))
|
|
|
|
self._parm.set('netbios name', self.flatname)
|
|
|
|
self._creds = credentials.Credentials()
|
|
|
|
self._creds.set_kerberos_state(credentials.MUST_USE_KERBEROS)
|
|
|
|
self._creds.guess(self._parm)
|
|
|
|
self._creds.set_workstation(self.flatname)
|
|
|
|
|
|
|
|
netrc = net.Net(creds=self._creds, lp=self._parm)
|
|
|
|
finddc_error = None
|
|
|
|
result = None
|
|
|
|
try:
|
|
|
|
result = netrc.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC | nbt.NBT_SERVER_CLOSEST)
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2014-08-19 08:19:45 -05:00
|
|
|
try:
|
|
|
|
# If search of closest GC failed, attempt to find any one
|
|
|
|
result = netrc.finddc(domain=domain, flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_GC)
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2014-08-19 08:19:45 -05:00
|
|
|
finddc_error = e
|
2012-10-31 14:52:12 -05:00
|
|
|
|
2013-07-17 08:55:36 -05:00
|
|
|
if not self._domains:
|
|
|
|
self._domains = self.get_trusted_domains()
|
|
|
|
|
2012-10-31 14:52:12 -05:00
|
|
|
info = dict()
|
|
|
|
servers = []
|
2013-07-17 08:55:36 -05:00
|
|
|
|
2012-10-31 14:52:12 -05:00
|
|
|
if result:
|
|
|
|
info['name'] = unicode(result.domain_name)
|
|
|
|
info['dns_domain'] = unicode(result.dns_domain)
|
|
|
|
servers = [(unicode(result.pdc_dns_name), 3268)]
|
|
|
|
else:
|
|
|
|
info['name'] = self._domains[domain]
|
|
|
|
info['dns_domain'] = domain
|
|
|
|
# Retrieve GC servers list
|
|
|
|
gc_name = '_gc._tcp.%s.' % info['dns_domain']
|
|
|
|
|
|
|
|
try:
|
|
|
|
answers = resolver.query(gc_name, rdatatype.SRV)
|
2015-07-30 09:49:29 -05:00
|
|
|
except DNSException as e:
|
2012-10-31 14:52:12 -05:00
|
|
|
answers = []
|
|
|
|
|
|
|
|
for answer in answers:
|
|
|
|
server = str(answer.target).rstrip(".")
|
|
|
|
servers.append((server, answer.port))
|
|
|
|
|
|
|
|
info['gc'] = servers
|
|
|
|
|
|
|
|
# Both methods should not fail at the same time
|
|
|
|
if finddc_error and len(info['gc']) == 0:
|
|
|
|
raise assess_dcerpc_exception(message=str(finddc_error))
|
|
|
|
|
|
|
|
self._info[domain] = info
|
|
|
|
return info
|
|
|
|
|
2013-09-11 13:34:55 -05:00
|
|
|
def string_to_array(what):
|
|
|
|
blob = [0] * len(what)
|
|
|
|
|
|
|
|
for i in range(len(what)):
|
|
|
|
blob[i] = ord(what[i])
|
|
|
|
return blob
|
2012-10-31 14:52:12 -05:00
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
class TrustDomainInstance(object):
|
|
|
|
|
|
|
|
def __init__(self, hostname, creds=None):
|
|
|
|
self.parm = param.LoadParm()
|
|
|
|
self.parm.load(os.path.join(ipautil.SHARE_DIR,"smb.conf.empty"))
|
|
|
|
if len(hostname) > 0:
|
|
|
|
self.parm.set('netbios name', hostname)
|
|
|
|
self.creds = creds
|
|
|
|
self.hostname = hostname
|
|
|
|
self.info = {}
|
|
|
|
self._pipe = None
|
|
|
|
self._policy_handle = None
|
|
|
|
self.read_only = False
|
2013-09-11 13:34:55 -05:00
|
|
|
self.ftinfo_records = None
|
2014-11-24 07:07:49 -06:00
|
|
|
self.validation_attempts = 0
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
def __gen_lsa_connection(self, binding):
|
|
|
|
if self.creds is None:
|
2012-08-13 08:35:19 -05:00
|
|
|
raise errors.RequirementError(name=_('CIFS credentials object'))
|
2012-02-28 05:24:41 -06:00
|
|
|
try:
|
|
|
|
result = lsa.lsarpc(binding, self.parm, self.creds)
|
|
|
|
return result
|
2015-07-14 03:50:34 -05:00
|
|
|
except RuntimeError as e:
|
|
|
|
num, message = e.args
|
2012-08-01 02:14:09 -05:00
|
|
|
raise assess_dcerpc_exception(num=num, message=message)
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2013-11-27 04:17:43 -06:00
|
|
|
def init_lsa_pipe(self, remote_host):
|
2012-02-28 05:24:41 -06:00
|
|
|
"""
|
|
|
|
Try to initialize connection to the LSA pipe at remote host.
|
|
|
|
This method tries consequently all possible transport options
|
|
|
|
and selects one that works. See __gen_lsa_bindings() for details.
|
|
|
|
|
|
|
|
The actual result may depend on details of existing credentials.
|
|
|
|
For example, using signing causes NO_SESSION_KEY with Win2K8 and
|
|
|
|
using kerberos against Samba with signing does not work.
|
|
|
|
"""
|
|
|
|
# short-cut: if LSA pipe is initialized, skip completely
|
|
|
|
if self._pipe:
|
|
|
|
return
|
|
|
|
|
2012-08-01 02:14:09 -05:00
|
|
|
attempts = 0
|
2015-05-08 07:09:13 -05:00
|
|
|
session_attempts = 0
|
2012-02-28 05:24:41 -06:00
|
|
|
bindings = self.__gen_lsa_bindings(remote_host)
|
|
|
|
for binding in bindings:
|
2012-08-01 02:14:09 -05:00
|
|
|
try:
|
|
|
|
self._pipe = self.__gen_lsa_connection(binding)
|
2015-05-08 07:09:13 -05:00
|
|
|
if self._pipe and self._pipe.session_key:
|
2012-08-01 02:14:09 -05:00
|
|
|
break
|
2015-07-30 09:49:29 -05:00
|
|
|
except errors.ACIError as e:
|
2012-08-01 02:14:09 -05:00
|
|
|
attempts = attempts + 1
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2015-05-08 07:09:13 -05:00
|
|
|
# When session key is not available, we just skip this binding
|
|
|
|
session_attempts = session_attempts + 1
|
2012-08-01 02:14:09 -05:00
|
|
|
|
2015-05-08 07:09:13 -05:00
|
|
|
if self._pipe is None and (attempts + session_attempts) == len(bindings):
|
2012-08-13 08:35:19 -05:00
|
|
|
raise errors.ACIError(
|
|
|
|
info=_('CIFS server %(host)s denied your credentials') % dict(host=remote_host))
|
2012-08-01 02:14:09 -05:00
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
if self._pipe is None:
|
2012-08-13 08:35:19 -05:00
|
|
|
raise errors.RemoteRetrieveError(
|
|
|
|
reason=_('Cannot establish LSA connection to %(host)s. Is CIFS server running?') % dict(host=remote_host))
|
2012-09-13 12:01:55 -05:00
|
|
|
self.binding = binding
|
2015-05-08 07:09:13 -05:00
|
|
|
self.session_key = self._pipe.session_key
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
def __gen_lsa_bindings(self, remote_host):
|
|
|
|
"""
|
|
|
|
There are multiple transports to issue LSA calls. However, depending on a
|
|
|
|
system in use they may be blocked by local operating system policies.
|
2013-11-27 04:17:43 -06:00
|
|
|
Generate all we can use. init_lsa_pipe() will try them one by one until
|
2012-02-28 05:24:41 -06:00
|
|
|
there is one working.
|
|
|
|
|
2015-05-08 07:09:13 -05:00
|
|
|
We try NCACN_NP before NCACN_IP_TCP and use SMB2 before SMB1 or defaults.
|
2012-02-28 05:24:41 -06:00
|
|
|
"""
|
|
|
|
transports = (u'ncacn_np', u'ncacn_ip_tcp')
|
2015-08-05 13:33:45 -05:00
|
|
|
options = ( u'smb2,print', u'print')
|
2015-08-07 11:03:48 -05:00
|
|
|
return [u'%s:%s[%s]' % (t, remote_host, o) for t in transports for o in options]
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2014-08-19 08:21:21 -05:00
|
|
|
def retrieve_anonymously(self, remote_host, discover_srv=False, search_pdc=False):
|
2012-02-28 05:24:41 -06:00
|
|
|
"""
|
|
|
|
When retrieving DC information anonymously, we can't get SID of the domain
|
|
|
|
"""
|
|
|
|
netrc = net.Net(creds=self.creds, lp=self.parm)
|
2014-08-19 08:21:21 -05:00
|
|
|
flags = nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS | nbt.NBT_SERVER_WRITABLE
|
|
|
|
if search_pdc:
|
|
|
|
flags = flags | nbt.NBT_SERVER_PDC
|
2012-08-01 02:14:09 -05:00
|
|
|
try:
|
|
|
|
if discover_srv:
|
2014-08-19 08:21:21 -05:00
|
|
|
result = netrc.finddc(domain=remote_host, flags=flags)
|
2012-08-01 02:14:09 -05:00
|
|
|
else:
|
2014-08-19 08:21:21 -05:00
|
|
|
result = netrc.finddc(address=remote_host, flags=flags)
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2012-08-01 02:14:09 -05:00
|
|
|
raise assess_dcerpc_exception(message=str(e))
|
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
if not result:
|
|
|
|
return False
|
|
|
|
self.info['name'] = unicode(result.domain_name)
|
|
|
|
self.info['dns_domain'] = unicode(result.dns_domain)
|
|
|
|
self.info['dns_forest'] = unicode(result.forest)
|
|
|
|
self.info['guid'] = unicode(result.domain_uuid)
|
2012-09-13 12:01:55 -05:00
|
|
|
self.info['dc'] = unicode(result.pdc_dns_name)
|
2014-08-19 08:21:21 -05:00
|
|
|
self.info['is_pdc'] = (result.server_type & nbt.NBT_SERVER_PDC) != 0
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
# Netlogon response doesn't contain SID of the domain.
|
|
|
|
# We need to do rootDSE search with LDAP_SERVER_EXTENDED_DN_OID control to reveal the SID
|
2012-03-21 07:51:50 -05:00
|
|
|
ldap_uri = 'ldap://%s' % (result.pdc_dns_name)
|
2012-02-28 05:24:41 -06:00
|
|
|
conn = _ldap.initialize(ldap_uri)
|
|
|
|
conn.set_option(_ldap.OPT_SERVER_CONTROLS, [ExtendedDNControl()])
|
2013-08-06 03:41:58 -05:00
|
|
|
search_result = None
|
2012-02-28 05:24:41 -06:00
|
|
|
try:
|
|
|
|
(objtype, res) = conn.search_s('', _ldap.SCOPE_BASE)[0]
|
2013-08-06 03:41:58 -05:00
|
|
|
search_result = res['defaultNamingContext'][0]
|
2012-02-28 05:24:41 -06:00
|
|
|
self.info['dns_hostname'] = res['dnsHostName'][0]
|
2015-07-30 09:49:29 -05:00
|
|
|
except _ldap.LDAPError as e:
|
2012-08-13 08:35:19 -05:00
|
|
|
root_logger.error(
|
|
|
|
"LDAP error when connecting to %(host)s: %(error)s" %
|
|
|
|
dict(host=unicode(result.pdc_name), error=str(e)))
|
2015-07-30 09:49:29 -05:00
|
|
|
except KeyError as e:
|
2013-08-06 05:15:22 -05:00
|
|
|
root_logger.error("KeyError: {err}, LDAP entry from {host} "
|
|
|
|
"returned malformed. Your DNS might be "
|
|
|
|
"misconfigured."
|
|
|
|
.format(host=unicode(result.pdc_name),
|
|
|
|
err=unicode(e)))
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2013-08-06 03:41:58 -05:00
|
|
|
if search_result:
|
2013-08-06 05:15:22 -05:00
|
|
|
self.info['sid'] = self.parse_naming_context(search_result)
|
2012-02-28 05:24:41 -06:00
|
|
|
return True
|
|
|
|
|
|
|
|
def parse_naming_context(self, context):
|
|
|
|
naming_ref = re.compile('.*<SID=(S-.*)>.*')
|
2014-03-12 10:51:43 -05:00
|
|
|
return unicode(naming_ref.match(context).group(1))
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
def retrieve(self, remote_host):
|
2013-11-27 04:17:43 -06:00
|
|
|
self.init_lsa_pipe(remote_host)
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
objectAttribute = lsa.ObjectAttribute()
|
|
|
|
objectAttribute.sec_qos = lsa.QosInfo()
|
2012-08-01 02:14:09 -05:00
|
|
|
try:
|
|
|
|
self._policy_handle = self._pipe.OpenPolicy2(u"", objectAttribute, security.SEC_FLAG_MAXIMUM_ALLOWED)
|
|
|
|
result = self._pipe.QueryInfoPolicy2(self._policy_handle, lsa.LSA_POLICY_INFO_DNS)
|
2015-07-14 03:50:34 -05:00
|
|
|
except RuntimeError as e:
|
|
|
|
num, message = e.args
|
2012-08-01 02:14:09 -05:00
|
|
|
raise assess_dcerpc_exception(num=num, message=message)
|
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
self.info['name'] = unicode(result.name.string)
|
|
|
|
self.info['dns_domain'] = unicode(result.dns_domain.string)
|
|
|
|
self.info['dns_forest'] = unicode(result.dns_forest.string)
|
|
|
|
self.info['guid'] = unicode(result.domain_guid)
|
|
|
|
self.info['sid'] = unicode(result.sid)
|
2012-09-13 12:01:55 -05:00
|
|
|
self.info['dc'] = remote_host
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2014-08-19 08:21:21 -05:00
|
|
|
try:
|
|
|
|
result = self._pipe.QueryInfoPolicy2(self._policy_handle, lsa.LSA_POLICY_INFO_ROLE)
|
2015-07-14 03:50:34 -05:00
|
|
|
except RuntimeError as e:
|
|
|
|
num, message = e.args
|
2014-08-19 08:21:21 -05:00
|
|
|
raise assess_dcerpc_exception(num=num, message=message)
|
|
|
|
|
|
|
|
self.info['is_pdc'] = (result.role == lsa.LSA_ROLE_PRIMARY)
|
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
def generate_auth(self, trustdom_secret):
|
|
|
|
password_blob = string_to_array(trustdom_secret.encode('utf-16-le'))
|
|
|
|
|
|
|
|
clear_value = drsblobs.AuthInfoClear()
|
|
|
|
clear_value.size = len(password_blob)
|
|
|
|
clear_value.password = password_blob
|
|
|
|
|
|
|
|
clear_authentication_information = drsblobs.AuthenticationInformation()
|
|
|
|
clear_authentication_information.LastUpdateTime = samba.unix2nttime(int(time.time()))
|
|
|
|
clear_authentication_information.AuthType = lsa.TRUST_AUTH_TYPE_CLEAR
|
|
|
|
clear_authentication_information.AuthInfo = clear_value
|
|
|
|
|
|
|
|
authentication_information_array = drsblobs.AuthenticationInformationArray()
|
|
|
|
authentication_information_array.count = 1
|
|
|
|
authentication_information_array.array = [clear_authentication_information]
|
|
|
|
|
|
|
|
outgoing = drsblobs.trustAuthInOutBlob()
|
|
|
|
outgoing.count = 1
|
|
|
|
outgoing.current = authentication_information_array
|
|
|
|
|
|
|
|
confounder = [3]*512
|
|
|
|
for i in range(512):
|
|
|
|
confounder[i] = random.randint(0, 255)
|
|
|
|
|
|
|
|
trustpass = drsblobs.trustDomainPasswords()
|
|
|
|
trustpass.confounder = confounder
|
|
|
|
|
|
|
|
trustpass.outgoing = outgoing
|
|
|
|
trustpass.incoming = outgoing
|
|
|
|
|
|
|
|
trustpass_blob = ndr_pack(trustpass)
|
|
|
|
|
|
|
|
encrypted_trustpass = arcfour_encrypt(self._pipe.session_key, trustpass_blob)
|
|
|
|
|
|
|
|
auth_blob = lsa.DATA_BUF2()
|
|
|
|
auth_blob.size = len(encrypted_trustpass)
|
|
|
|
auth_blob.data = string_to_array(encrypted_trustpass)
|
|
|
|
|
|
|
|
auth_info = lsa.TrustDomainInfoAuthInfoInternal()
|
|
|
|
auth_info.auth_blob = auth_blob
|
|
|
|
self.auth_info = auth_info
|
|
|
|
|
|
|
|
|
2013-09-11 13:34:55 -05:00
|
|
|
def generate_ftinfo(self, another_domain):
|
|
|
|
"""
|
|
|
|
Generates TrustDomainInfoFullInfo2Internal structure
|
|
|
|
This structure allows to pass information about all domains associated
|
|
|
|
with the another domain's realm.
|
|
|
|
|
|
|
|
Only top level name and top level name exclusions are handled here.
|
|
|
|
"""
|
|
|
|
if not another_domain.ftinfo_records:
|
|
|
|
return
|
|
|
|
|
|
|
|
ftinfo_records = []
|
|
|
|
info = lsa.ForestTrustInformation()
|
|
|
|
|
|
|
|
for rec in another_domain.ftinfo_records:
|
|
|
|
record = lsa.ForestTrustRecord()
|
|
|
|
record.flags = 0
|
|
|
|
record.time = rec['rec_time']
|
|
|
|
record.type = rec['rec_type']
|
|
|
|
record.forest_trust_data.string = rec['rec_name']
|
|
|
|
ftinfo_records.append(record)
|
|
|
|
|
|
|
|
info.count = len(ftinfo_records)
|
|
|
|
info.entries = ftinfo_records
|
|
|
|
return info
|
|
|
|
|
|
|
|
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']
|
|
|
|
collision_info = self._pipe.lsaRSetForestTrustInformation(self._policy_handle,
|
|
|
|
ldname,
|
|
|
|
lsa.LSA_FOREST_TRUST_DOMAIN_INFO,
|
|
|
|
ftinfo, 0)
|
|
|
|
if collision_info:
|
|
|
|
root_logger.error("When setting forest trust information, got collision info back:\n%s" % (ndr_print(collision_info)))
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2013-09-11 13:34:55 -05:00
|
|
|
# We can ignore the error here -- setting up name suffix routes may fail
|
|
|
|
pass
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2015-06-05 07:57:02 -05:00
|
|
|
def establish_trust(self, another_domain, trustdom_secret, trust_type='bidirectional'):
|
2012-02-28 05:24:41 -06:00
|
|
|
"""
|
|
|
|
Establishes trust between our and another domain
|
|
|
|
Input: another_domain -- instance of TrustDomainInstance, initialized with #retrieve call
|
|
|
|
trustdom_secret -- shared secred used for the trust
|
|
|
|
"""
|
2013-09-11 13:34:55 -05:00
|
|
|
if self.info['name'] == another_domain.info['name']:
|
|
|
|
# Check that NetBIOS names do not clash
|
|
|
|
raise errors.ValidationError(name=u'AD Trust Setup',
|
|
|
|
error=_('the IPA server and the remote domain cannot share the same '
|
|
|
|
'NetBIOS name: %s') % self.info['name'])
|
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
self.generate_auth(trustdom_secret)
|
|
|
|
|
|
|
|
info = lsa.TrustDomainInfoInfoEx()
|
|
|
|
info.domain_name.string = another_domain.info['dns_domain']
|
|
|
|
info.netbios_name.string = another_domain.info['name']
|
|
|
|
info.sid = security.dom_sid(another_domain.info['sid'])
|
2015-06-05 07:57:02 -05:00
|
|
|
info.trust_direction = lsa.LSA_TRUST_DIRECTION_INBOUND
|
|
|
|
if trust_type == TRUST_BIDIRECTIONAL:
|
|
|
|
info.trust_direction |= lsa.LSA_TRUST_DIRECTION_OUTBOUND
|
2012-02-28 05:24:41 -06:00
|
|
|
info.trust_type = lsa.LSA_TRUST_TYPE_UPLEVEL
|
2014-08-19 08:22:54 -05:00
|
|
|
info.trust_attributes = 0
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
try:
|
|
|
|
dname = lsa.String()
|
|
|
|
dname.string = another_domain.info['dns_domain']
|
|
|
|
res = self._pipe.QueryTrustedDomainInfoByName(self._policy_handle, dname, lsa.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO)
|
|
|
|
self._pipe.DeleteTrustedDomain(self._policy_handle, res.info_ex.sid)
|
2015-07-14 03:50:34 -05:00
|
|
|
except RuntimeError as e:
|
|
|
|
num, message = e.args
|
2014-02-26 09:43:34 -06:00
|
|
|
# Ignore anything but access denied (NT_STATUS_ACCESS_DENIED)
|
|
|
|
if num == -1073741790:
|
|
|
|
raise access_denied_error
|
|
|
|
|
2012-08-01 02:14:09 -05:00
|
|
|
try:
|
2012-09-26 17:34:57 -05:00
|
|
|
trustdom_handle = self._pipe.CreateTrustedDomainEx2(self._policy_handle, info, self.auth_info, security.SEC_STD_DELETE)
|
2015-07-14 03:50:34 -05:00
|
|
|
except RuntimeError as e:
|
|
|
|
num, message = e.args
|
2012-08-01 02:14:09 -05:00
|
|
|
raise assess_dcerpc_exception(num=num, message=message)
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2013-09-11 13:34:55 -05:00
|
|
|
# We should use proper trustdom handle in order to modify the
|
|
|
|
# trust settings. Samba insists this has to be done with LSA
|
|
|
|
# OpenTrustedDomain* calls, it is not enough to have a handle
|
|
|
|
# returned by the CreateTrustedDomainEx2 call.
|
|
|
|
trustdom_handle = self._pipe.OpenTrustedDomainByName(self._policy_handle, dname, security.SEC_FLAG_MAXIMUM_ALLOWED)
|
2012-09-26 17:34:57 -05:00
|
|
|
try:
|
|
|
|
infoclass = lsa.TrustDomainInfoSupportedEncTypes()
|
|
|
|
infoclass.enc_types = security.KERB_ENCTYPE_RC4_HMAC_MD5
|
|
|
|
infoclass.enc_types |= security.KERB_ENCTYPE_AES128_CTS_HMAC_SHA1_96
|
|
|
|
infoclass.enc_types |= security.KERB_ENCTYPE_AES256_CTS_HMAC_SHA1_96
|
|
|
|
self._pipe.SetInformationTrustedDomain(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_SUPPORTED_ENCRYPTION_TYPES, infoclass)
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2013-09-05 00:13:53 -05:00
|
|
|
# We can ignore the error here -- changing enctypes is for
|
|
|
|
# improved security but the trust will work with default values as
|
|
|
|
# well. In particular, the call may fail against Windows 2003
|
|
|
|
# server as that one doesn't support AES encryption types
|
2012-09-26 17:34:57 -05:00
|
|
|
pass
|
|
|
|
|
2014-08-19 08:22:54 -05:00
|
|
|
try:
|
2015-06-05 07:57:02 -05:00
|
|
|
info = self._pipe.QueryTrustedDomainInfo(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX)
|
|
|
|
info.trust_attributes |= lsa.LSA_TRUST_ATTRIBUTE_FOREST_TRANSITIVE
|
2014-08-19 08:22:54 -05:00
|
|
|
self._pipe.SetInformationTrustedDomain(trustdom_handle, lsa.LSA_TRUSTED_DOMAIN_INFO_INFO_EX, info)
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2014-08-19 08:22:54 -05:00
|
|
|
root_logger.error('unable to set trust to transitive: %s' % (str(e)))
|
|
|
|
pass
|
|
|
|
if self.info['is_pdc']:
|
|
|
|
self.update_ftinfo(another_domain)
|
|
|
|
|
2012-09-13 12:01:55 -05:00
|
|
|
def verify_trust(self, another_domain):
|
2015-06-05 07:57:02 -05:00
|
|
|
def retrieve_netlogon_info_2(logon_server, domain, function_code, data):
|
2012-09-13 12:01:55 -05:00
|
|
|
try:
|
|
|
|
netr_pipe = netlogon.netlogon(domain.binding, domain.parm, domain.creds)
|
2015-06-05 07:57:02 -05:00
|
|
|
result = netr_pipe.netr_LogonControl2Ex(logon_server=logon_server,
|
2012-09-13 12:01:55 -05:00
|
|
|
function_code=function_code,
|
|
|
|
level=2,
|
|
|
|
data=data
|
|
|
|
)
|
|
|
|
return result
|
2015-07-14 03:50:34 -05:00
|
|
|
except RuntimeError as e:
|
|
|
|
num, message = e.args
|
2012-09-13 12:01:55 -05:00
|
|
|
raise assess_dcerpc_exception(num=num, message=message)
|
|
|
|
|
2015-06-05 07:57:02 -05:00
|
|
|
result = retrieve_netlogon_info_2(None, self,
|
2012-09-13 12:01:55 -05:00
|
|
|
netlogon.NETLOGON_CONTROL_TC_VERIFY,
|
|
|
|
another_domain.info['dns_domain'])
|
2015-07-15 08:38:50 -05:00
|
|
|
|
|
|
|
if result and result.flags and netlogon.NETLOGON_VERIFY_STATUS_RETURNED:
|
|
|
|
if result.pdc_connection_status[0] != 0 and result.tc_connection_status[0] != 0:
|
2014-11-24 07:07:49 -06:00
|
|
|
if result.pdc_connection_status[1] == "WERR_ACCESS_DENIED":
|
|
|
|
# Most likely AD DC hit another IPA replica which yet has no trust secret replicated
|
2015-07-15 08:38:50 -05:00
|
|
|
|
2014-11-24 07:07:49 -06:00
|
|
|
# Sleep and repeat again
|
|
|
|
self.validation_attempts += 1
|
|
|
|
if self.validation_attempts < 10:
|
|
|
|
sleep(5)
|
|
|
|
return self.verify_trust(another_domain)
|
2015-07-15 08:38:50 -05:00
|
|
|
|
|
|
|
# If we get here, we already failed 10 times
|
|
|
|
srv_record_templates = (
|
|
|
|
'_ldap._tcp.%s',
|
|
|
|
'_ldap._tcp.Default-First-Site-Name._sites.dc._msdcs.%s'
|
|
|
|
)
|
|
|
|
|
|
|
|
srv_records = ', '.join(
|
|
|
|
[srv_record % api.env.domain
|
|
|
|
for srv_record in srv_record_templates]
|
|
|
|
)
|
|
|
|
|
|
|
|
error_message = _(
|
|
|
|
'IPA master denied trust validation requests from AD '
|
|
|
|
'DC %(count)d times. Most likely AD DC contacted a '
|
|
|
|
'replica that has no trust information replicated '
|
|
|
|
'yet. Additionally, please check that AD DNS is able '
|
|
|
|
'to resolve %(records)s SRV records to the correct '
|
|
|
|
'IPA server.') % dict(count=self.validation_attempts,
|
|
|
|
records=srv_records)
|
|
|
|
|
|
|
|
raise errors.ACIError(info=error_message)
|
|
|
|
|
2014-11-24 07:07:49 -06:00
|
|
|
raise assess_dcerpc_exception(*result.pdc_connection_status)
|
2015-07-15 08:38:50 -05:00
|
|
|
|
2012-09-13 12:01:55 -05:00
|
|
|
return True
|
2015-07-15 08:38:50 -05:00
|
|
|
|
2012-09-13 12:01:55 -05:00
|
|
|
return False
|
|
|
|
|
2013-09-27 05:39:57 -05:00
|
|
|
|
2015-05-28 06:49:58 -05:00
|
|
|
def fetch_domains(api, mydomain, trustdomain, creds=None, server=None):
|
2013-09-18 10:04:19 -05:00
|
|
|
trust_flags = dict(
|
|
|
|
NETR_TRUST_FLAG_IN_FOREST = 0x00000001,
|
|
|
|
NETR_TRUST_FLAG_OUTBOUND = 0x00000002,
|
|
|
|
NETR_TRUST_FLAG_TREEROOT = 0x00000004,
|
|
|
|
NETR_TRUST_FLAG_PRIMARY = 0x00000008,
|
|
|
|
NETR_TRUST_FLAG_NATIVE = 0x00000010,
|
|
|
|
NETR_TRUST_FLAG_INBOUND = 0x00000020,
|
|
|
|
NETR_TRUST_FLAG_MIT_KRB5 = 0x00000080,
|
|
|
|
NETR_TRUST_FLAG_AES = 0x00000100)
|
|
|
|
|
|
|
|
trust_attributes = dict(
|
|
|
|
NETR_TRUST_ATTRIBUTE_NON_TRANSITIVE = 0x00000001,
|
|
|
|
NETR_TRUST_ATTRIBUTE_UPLEVEL_ONLY = 0x00000002,
|
|
|
|
NETR_TRUST_ATTRIBUTE_QUARANTINED_DOMAIN = 0x00000004,
|
|
|
|
NETR_TRUST_ATTRIBUTE_FOREST_TRANSITIVE = 0x00000008,
|
|
|
|
NETR_TRUST_ATTRIBUTE_CROSS_ORGANIZATION = 0x00000010,
|
|
|
|
NETR_TRUST_ATTRIBUTE_WITHIN_FOREST = 0x00000020,
|
|
|
|
NETR_TRUST_ATTRIBUTE_TREAT_AS_EXTERNAL = 0x00000040)
|
|
|
|
|
2013-09-27 05:39:57 -05:00
|
|
|
def communicate(td):
|
2013-11-27 04:17:43 -06:00
|
|
|
td.init_lsa_pipe(td.info['dc'])
|
2013-09-27 05:39:57 -05:00
|
|
|
netr_pipe = netlogon.netlogon(td.binding, td.parm, td.creds)
|
|
|
|
domains = netr_pipe.netr_DsrEnumerateDomainTrusts(td.binding, 1)
|
|
|
|
return domains
|
|
|
|
|
|
|
|
domains = None
|
2013-11-27 04:17:43 -06:00
|
|
|
domain_validator = DomainValidator(api)
|
|
|
|
configured = domain_validator.is_configured()
|
|
|
|
if not configured:
|
|
|
|
return None
|
|
|
|
|
2013-09-27 05:39:57 -05:00
|
|
|
td = TrustDomainInstance('')
|
|
|
|
td.parm.set('workgroup', mydomain)
|
2013-11-27 04:17:43 -06:00
|
|
|
cr = credentials.Credentials()
|
|
|
|
cr.set_kerberos_state(credentials.DONT_USE_KERBEROS)
|
|
|
|
cr.guess(td.parm)
|
|
|
|
cr.set_anonymous()
|
|
|
|
cr.set_workstation(domain_validator.flatname)
|
|
|
|
netrc = net.Net(creds=cr, lp=td.parm)
|
|
|
|
try:
|
2015-05-28 06:49:58 -05:00
|
|
|
if server:
|
|
|
|
result = netrc.finddc(address=server,
|
|
|
|
flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS)
|
|
|
|
else:
|
|
|
|
result = netrc.finddc(domain=trustdomain,
|
|
|
|
flags=nbt.NBT_SERVER_LDAP | nbt.NBT_SERVER_DS)
|
2015-07-30 09:49:29 -05:00
|
|
|
except RuntimeError as e:
|
2013-11-27 04:17:43 -06:00
|
|
|
raise assess_dcerpc_exception(message=str(e))
|
|
|
|
|
|
|
|
td.info['dc'] = unicode(result.pdc_dns_name)
|
2015-07-06 09:46:24 -05:00
|
|
|
if type(creds) is bool:
|
|
|
|
# Rely on existing Kerberos credentials in the environment
|
|
|
|
td.creds = credentials.Credentials()
|
|
|
|
td.creds.set_kerberos_state(credentials.MUST_USE_KERBEROS)
|
|
|
|
td.creds.guess(td.parm)
|
|
|
|
td.creds.set_workstation(domain_validator.flatname)
|
|
|
|
domains = communicate(td)
|
|
|
|
else:
|
2015-06-05 07:57:02 -05:00
|
|
|
# Attempt to authenticate as HTTP/ipa.master and use cross-forest trust
|
2015-07-06 09:46:24 -05:00
|
|
|
# or as passed-in user in case of a one-way trust
|
2013-09-27 05:39:57 -05:00
|
|
|
domval = DomainValidator(api)
|
2015-07-06 09:46:24 -05:00
|
|
|
ccache_name = None
|
|
|
|
principal = None
|
|
|
|
if creds:
|
|
|
|
domval._admin_creds = creds
|
|
|
|
(ccache_name, principal) = domval.kinit_as_administrator(trustdomain)
|
|
|
|
else:
|
|
|
|
(ccache_name, principal) = domval.kinit_as_http(trustdomain)
|
2013-11-27 04:17:43 -06:00
|
|
|
td.creds = credentials.Credentials()
|
2013-09-27 05:39:57 -05:00
|
|
|
td.creds.set_kerberos_state(credentials.MUST_USE_KERBEROS)
|
|
|
|
if ccache_name:
|
2015-06-04 06:59:22 -05:00
|
|
|
with ipautil.private_ccache(path=ccache_name):
|
2013-11-27 04:17:43 -06:00
|
|
|
td.creds.guess(td.parm)
|
|
|
|
td.creds.set_workstation(domain_validator.flatname)
|
2013-09-27 05:39:57 -05:00
|
|
|
domains = communicate(td)
|
|
|
|
|
|
|
|
if domains is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
result = []
|
|
|
|
for t in domains.array:
|
2014-08-19 08:23:58 -05:00
|
|
|
if (not (t.trust_flags & trust_flags['NETR_TRUST_FLAG_PRIMARY']) and
|
2013-09-27 05:39:57 -05:00
|
|
|
(t.trust_flags & trust_flags['NETR_TRUST_FLAG_IN_FOREST'])):
|
|
|
|
res = dict()
|
|
|
|
res['cn'] = unicode(t.dns_name)
|
|
|
|
res['ipantflatname'] = unicode(t.netbios_name)
|
|
|
|
res['ipanttrusteddomainsid'] = unicode(t.sid)
|
|
|
|
res['ipanttrustpartner'] = res['cn']
|
|
|
|
result.append(res)
|
|
|
|
return result
|
2013-09-18 10:04:19 -05:00
|
|
|
|
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
class TrustDomainJoins(object):
|
|
|
|
def __init__(self, api):
|
|
|
|
self.api = api
|
|
|
|
self.local_domain = None
|
|
|
|
self.remote_domain = None
|
|
|
|
|
2012-06-20 08:08:33 -05:00
|
|
|
domain_validator = DomainValidator(api)
|
|
|
|
self.configured = domain_validator.is_configured()
|
2012-02-28 05:24:41 -06:00
|
|
|
|
2012-06-20 08:08:33 -05:00
|
|
|
if self.configured:
|
|
|
|
self.local_flatname = domain_validator.flatname
|
|
|
|
self.local_dn = domain_validator.dn
|
|
|
|
self.__populate_local_domain()
|
2012-02-28 05:24:41 -06:00
|
|
|
|
|
|
|
def __populate_local_domain(self):
|
|
|
|
# Initialize local domain info using kerberos only
|
|
|
|
ld = TrustDomainInstance(self.local_flatname)
|
|
|
|
ld.creds = credentials.Credentials()
|
|
|
|
ld.creds.set_kerberos_state(credentials.MUST_USE_KERBEROS)
|
|
|
|
ld.creds.guess(ld.parm)
|
|
|
|
ld.creds.set_workstation(ld.hostname)
|
2012-05-15 12:10:28 -05:00
|
|
|
ld.retrieve(installutils.get_fqdn())
|
2012-02-28 05:24:41 -06:00
|
|
|
self.local_domain = ld
|
|
|
|
|
2013-05-31 05:01:23 -05:00
|
|
|
def populate_remote_domain(self, realm, realm_server=None, realm_admin=None, realm_passwd=None):
|
2012-02-28 05:24:41 -06:00
|
|
|
def get_instance(self):
|
|
|
|
# Fetch data from foreign domain using password only
|
|
|
|
rd = TrustDomainInstance('')
|
|
|
|
rd.parm.set('workgroup', self.local_domain.info['name'])
|
|
|
|
rd.creds = credentials.Credentials()
|
|
|
|
rd.creds.set_kerberos_state(credentials.DONT_USE_KERBEROS)
|
|
|
|
rd.creds.guess(rd.parm)
|
|
|
|
return rd
|
|
|
|
|
|
|
|
rd = get_instance(self)
|
|
|
|
rd.creds.set_anonymous()
|
|
|
|
rd.creds.set_workstation(self.local_domain.hostname)
|
|
|
|
if realm_server is None:
|
2014-08-19 08:21:21 -05:00
|
|
|
rd.retrieve_anonymously(realm, discover_srv=True, search_pdc=True)
|
2012-02-28 05:24:41 -06:00
|
|
|
else:
|
2014-08-19 08:21:21 -05:00
|
|
|
rd.retrieve_anonymously(realm_server, discover_srv=False, search_pdc=True)
|
2012-02-28 05:24:41 -06:00
|
|
|
rd.read_only = True
|
|
|
|
if realm_admin and realm_passwd:
|
|
|
|
if 'name' in rd.info:
|
2012-07-16 05:12:42 -05:00
|
|
|
names = realm_admin.split('\\')
|
|
|
|
if len(names) > 1:
|
|
|
|
# realm admin is in DOMAIN\user format
|
|
|
|
# strip DOMAIN part as we'll enforce the one discovered
|
|
|
|
realm_admin = names[-1]
|
2012-02-28 05:24:41 -06:00
|
|
|
auth_string = u"%s\%s%%%s" % (rd.info['name'], realm_admin, realm_passwd)
|
|
|
|
td = get_instance(self)
|
|
|
|
td.creds.parse_string(auth_string)
|
|
|
|
td.creds.set_workstation(self.local_domain.hostname)
|
|
|
|
if realm_server is None:
|
|
|
|
# we must have rd.info['dns_hostname'] then, part of anonymous discovery
|
|
|
|
td.retrieve(rd.info['dns_hostname'])
|
|
|
|
else:
|
|
|
|
td.retrieve(realm_server)
|
|
|
|
td.read_only = False
|
|
|
|
self.remote_domain = td
|
|
|
|
return
|
|
|
|
# Otherwise, use anonymously obtained data
|
|
|
|
self.remote_domain = rd
|
|
|
|
|
2013-09-11 13:34:55 -05:00
|
|
|
def get_realmdomains(self):
|
|
|
|
"""
|
|
|
|
Generate list of records for forest trust information about
|
|
|
|
our realm domains. Note that the list generated currently
|
|
|
|
includes only top level domains, no exclusion domains, and no TDO objects
|
2013-09-27 05:36:59 -05:00
|
|
|
as we handle the latter in a separate way
|
2013-09-11 13:34:55 -05:00
|
|
|
"""
|
|
|
|
if self.local_domain.read_only:
|
|
|
|
return
|
|
|
|
|
2015-07-17 06:25:32 -05:00
|
|
|
self.local_domain.ftinfo_records = []
|
2013-09-11 13:34:55 -05:00
|
|
|
|
|
|
|
realm_domains = self.api.Command.realmdomains_show()['result']
|
|
|
|
# Use realmdomains' modification timestamp to judge records last update time
|
2014-02-27 03:33:50 -06:00
|
|
|
entry = self.api.Backend.ldap2.get_entry(realm_domains['dn'], ['modifyTimestamp'])
|
2013-09-11 13:34:55 -05:00
|
|
|
# Convert the timestamp to Windows 64-bit timestamp format
|
2014-05-05 12:21:01 -05:00
|
|
|
trust_timestamp = long(time.mktime(entry['modifytimestamp'][0].timetuple())*1e7+116444736000000000)
|
2013-09-11 13:34:55 -05:00
|
|
|
|
|
|
|
for dom in realm_domains['associateddomain']:
|
|
|
|
ftinfo = dict()
|
|
|
|
ftinfo['rec_name'] = dom
|
|
|
|
ftinfo['rec_time'] = trust_timestamp
|
|
|
|
ftinfo['rec_type'] = lsa.LSA_FOREST_TRUST_TOP_LEVEL_NAME
|
|
|
|
self.local_domain.ftinfo_records.append(ftinfo)
|
|
|
|
|
2015-06-05 07:57:02 -05:00
|
|
|
def join_ad_full_credentials(self, realm, realm_server, realm_admin, realm_passwd, trust_type):
|
2012-06-20 08:08:33 -05:00
|
|
|
if not self.configured:
|
|
|
|
return None
|
|
|
|
|
2013-05-31 05:01:23 -05:00
|
|
|
if not(isinstance(self.remote_domain, TrustDomainInstance)):
|
|
|
|
self.populate_remote_domain(
|
|
|
|
realm,
|
|
|
|
realm_server,
|
|
|
|
realm_admin,
|
|
|
|
realm_passwd
|
|
|
|
)
|
|
|
|
|
2014-08-19 08:24:27 -05:00
|
|
|
if self.remote_domain.info['dns_domain'] != self.remote_domain.info['dns_forest']:
|
|
|
|
raise errors.NotAForestRootError(forest=self.remote_domain.info['dns_forest'], domain=self.remote_domain.info['dns_domain'])
|
|
|
|
|
2012-02-28 05:24:41 -06:00
|
|
|
if not self.remote_domain.read_only:
|
|
|
|
trustdom_pass = samba.generate_random_password(128, 128)
|
2013-09-11 13:34:55 -05:00
|
|
|
self.get_realmdomains()
|
2015-06-05 07:57:02 -05:00
|
|
|
self.remote_domain.establish_trust(self.local_domain, trustdom_pass, trust_type)
|
|
|
|
self.local_domain.establish_trust(self.remote_domain, trustdom_pass, trust_type)
|
|
|
|
# if trust is inbound, we don't need to verify it because AD DC will respond
|
|
|
|
# with WERR_NO_SUCH_DOMAIN -- in only does verification for outbound trusts.
|
|
|
|
result = True
|
|
|
|
if trust_type == TRUST_BIDIRECTIONAL:
|
|
|
|
result = self.remote_domain.verify_trust(self.local_domain)
|
2012-09-13 12:01:55 -05:00
|
|
|
return dict(local=self.local_domain, remote=self.remote_domain, verified=result)
|
2012-02-28 05:24:41 -06:00
|
|
|
return None
|
|
|
|
|
2015-06-05 07:57:02 -05:00
|
|
|
def join_ad_ipa_half(self, realm, realm_server, trustdom_passwd, trust_type):
|
2012-06-20 08:08:33 -05:00
|
|
|
if not self.configured:
|
|
|
|
return None
|
|
|
|
|
2013-05-31 05:01:23 -05:00
|
|
|
if not(isinstance(self.remote_domain, TrustDomainInstance)):
|
|
|
|
self.populate_remote_domain(realm, realm_server, realm_passwd=None)
|
|
|
|
|
2014-08-19 08:24:27 -05:00
|
|
|
if self.remote_domain.info['dns_domain'] != self.remote_domain.info['dns_forest']:
|
|
|
|
raise errors.NotAForestRootError(forest=self.remote_domain.info['dns_forest'], domain=self.remote_domain.info['dns_domain'])
|
|
|
|
|
2015-06-05 07:57:02 -05:00
|
|
|
self.local_domain.establish_trust(self.remote_domain, trustdom_passwd, trust_type)
|
2012-09-13 12:01:55 -05:00
|
|
|
return dict(local=self.local_domain, remote=self.remote_domain, verified=False)
|