2 # Copyright Andrew Tridgell 2010
3 # Copyright Andrew Bartlett 2010
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 """Joining a domain."""
21 from samba
.auth
import system_session
22 from samba
.samdb
import SamDB
23 from samba
import gensec
, Ldb
, drs_utils
24 import ldb
, samba
, sys
, uuid
25 from samba
.ndr
import ndr_pack
26 from samba
.dcerpc
import security
, drsuapi
, misc
, nbt
, lsa
, drsblobs
27 from samba
.dsdb
import DS_DOMAIN_FUNCTION_2003
28 from samba
.credentials
import Credentials
, DONT_USE_KERBEROS
29 from samba
.provision
import secretsdb_self_join
, provision
, provision_fill
, FILL_DRS
, FILL_SUBDOMAIN
30 from samba
.provision
.common
import setup_path
31 from samba
.schema
import Schema
32 from samba
import descriptor
33 from samba
.net
import Net
34 from samba
.provision
.sambadns
import setup_bind9_dns
35 from samba
import read_and_sub_file
36 from base64
import b64encode
42 # this makes debugging easier
43 talloc
.enable_null_tracking()
45 class DCJoinException(Exception):
47 def __init__(self
, msg
):
48 super(DCJoinException
, self
).__init
__("Can't join, error: %s" % msg
)
51 class dc_join(object):
52 """Perform a DC join."""
54 def __init__(ctx
, logger
=None, server
=None, creds
=None, lp
=None, site
=None,
55 netbios_name
=None, targetdir
=None, domain
=None,
56 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
57 promote_existing
=False):
62 ctx
.netbios_name
= netbios_name
63 ctx
.targetdir
= targetdir
64 ctx
.use_ntvfs
= use_ntvfs
66 ctx
.promote_existing
= promote_existing
67 ctx
.promote_from_dn
= None
72 ctx
.creds
.set_gensec_features(creds
.get_gensec_features() | gensec
.FEATURE_SEAL
)
73 ctx
.net
= Net(creds
=ctx
.creds
, lp
=ctx
.lp
)
75 if server
is not None:
78 ctx
.logger
.info("Finding a writeable DC for domain '%s'" % domain
)
79 ctx
.server
= ctx
.find_dc(domain
)
80 ctx
.logger
.info("Found DC %s" % ctx
.server
)
82 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
83 session_info
=system_session(),
84 credentials
=ctx
.creds
, lp
=ctx
.lp
)
87 ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
88 except ldb
.LdbError
, (enum
, estr
):
89 raise DCJoinException(estr
)
92 ctx
.myname
= netbios_name
93 ctx
.samname
= "%s$" % ctx
.myname
94 ctx
.base_dn
= str(ctx
.samdb
.get_default_basedn())
95 ctx
.root_dn
= str(ctx
.samdb
.get_root_basedn())
96 ctx
.schema_dn
= str(ctx
.samdb
.get_schema_basedn())
97 ctx
.config_dn
= str(ctx
.samdb
.get_config_basedn())
98 ctx
.domsid
= security
.dom_sid(ctx
.samdb
.get_domain_sid())
99 ctx
.forestsid
= ctx
.domsid
100 ctx
.domain_name
= ctx
.get_domain_name()
101 ctx
.forest_domain_name
= ctx
.get_forest_domain_name()
102 ctx
.invocation_id
= misc
.GUID(str(uuid
.uuid4()))
104 ctx
.dc_ntds_dn
= ctx
.samdb
.get_dsServiceName()
105 ctx
.dc_dnsHostName
= ctx
.get_dnsHostName()
106 ctx
.behavior_version
= ctx
.get_behavior_version()
108 if machinepass
is not None:
109 ctx
.acct_pass
= machinepass
111 ctx
.acct_pass
= samba
.generate_random_password(32, 40)
113 # work out the DNs of all the objects we will be adding
114 ctx
.server_dn
= "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx
.myname
, ctx
.site
, ctx
.config_dn
)
115 ctx
.ntds_dn
= "CN=NTDS Settings,%s" % ctx
.server_dn
116 topology_base
= "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx
.base_dn
117 if ctx
.dn_exists(topology_base
):
118 ctx
.topology_dn
= "CN=%s,%s" % (ctx
.myname
, topology_base
)
120 ctx
.topology_dn
= None
122 ctx
.dnsdomain
= ctx
.samdb
.domain_dns_name()
123 ctx
.dnsforest
= ctx
.samdb
.forest_dns_name()
124 ctx
.domaindns_zone
= 'DC=DomainDnsZones,%s' % ctx
.base_dn
125 ctx
.forestdns_zone
= 'DC=ForestDnsZones,%s' % ctx
.root_dn
127 res_domaindns
= ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
,
129 base
=ctx
.samdb
.get_partitions_dn(),
130 expression
="(&(objectClass=crossRef)(ncName=%s))" % ctx
.domaindns_zone
)
131 if dns_backend
is None:
132 ctx
.dns_backend
= "NONE"
134 if len(res_domaindns
) == 0:
135 ctx
.dns_backend
= "NONE"
136 print "NO DNS zone information found in source domain, not replicating DNS"
138 ctx
.dns_backend
= dns_backend
140 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
.lower(), ctx
.dnsdomain
)
142 ctx
.realm
= ctx
.dnsdomain
144 ctx
.acct_dn
= "CN=%s,OU=Domain Controllers,%s" % (ctx
.myname
, ctx
.base_dn
)
148 ctx
.SPNs
= [ "HOST/%s" % ctx
.myname
,
149 "HOST/%s" % ctx
.dnshostname
,
150 "GC/%s/%s" % (ctx
.dnshostname
, ctx
.dnsforest
) ]
152 # these elements are optional
153 ctx
.never_reveal_sid
= None
154 ctx
.reveal_sid
= None
155 ctx
.connection_dn
= None
160 ctx
.subdomain
= False
163 def del_noerror(ctx
, dn
, recursive
=False):
166 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
170 ctx
.del_noerror(r
.dn
, recursive
=True)
173 print "Deleted %s" % dn
177 def cleanup_old_join(ctx
):
178 """Remove any DNs from a previous join."""
180 # find the krbtgt link
181 print("checking sAMAccountName")
185 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
186 expression
='sAMAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
187 attrs
=["msDS-krbTgtLink"])
189 ctx
.del_noerror(res
[0].dn
, recursive
=True)
191 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
192 expression
='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb
.binary_encode("dns-%s" % ctx
.myname
), ldb
.binary_encode("dns/%s" % ctx
.dnshostname
)),
195 ctx
.del_noerror(res
[0].dn
, recursive
=True)
197 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
198 expression
='(sAMAccountName=%s)' % ldb
.binary_encode("dns-%s" % ctx
.myname
),
201 raise RuntimeError("Not removing account %s which looks like a Samba DNS service account but does not have servicePrincipalName=%s" % (ldb
.binary_encode("dns-%s" % ctx
.myname
), ldb
.binary_encode("dns/%s" % ctx
.dnshostname
)))
203 if ctx
.connection_dn
is not None:
204 ctx
.del_noerror(ctx
.connection_dn
)
205 if ctx
.krbtgt_dn
is not None:
206 ctx
.del_noerror(ctx
.krbtgt_dn
)
207 ctx
.del_noerror(ctx
.ntds_dn
)
208 ctx
.del_noerror(ctx
.server_dn
, recursive
=True)
210 ctx
.del_noerror(ctx
.topology_dn
)
212 ctx
.del_noerror(ctx
.partition_dn
)
214 ctx
.new_krbtgt_dn
= res
[0]["msDS-Krbtgtlink"][0]
215 ctx
.del_noerror(ctx
.new_krbtgt_dn
)
218 binding_options
= "sign"
219 lsaconn
= lsa
.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
222 objectAttr
= lsa
.ObjectAttribute()
223 objectAttr
.sec_qos
= lsa
.QosInfo()
225 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
226 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
229 name
.string
= ctx
.realm
230 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
232 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
235 name
.string
= ctx
.forest_domain_name
236 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
238 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
243 def promote_possible(ctx
):
244 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
246 # This shouldn't happen
247 raise Exception("Can not promote into a subdomain")
249 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
250 expression
='sAMAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
251 attrs
=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
253 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx
.samname
)
254 if "msDS-krbTgtLink" in res
[0] or "serverReferenceBL" in res
[0] or "rIDSetReferences" in res
[0]:
255 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx
.samname
)
256 if (int(res
[0]["userAccountControl"][0]) & (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT|samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT
) == 0):
257 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx
.samname
)
259 ctx
.promote_from_dn
= res
[0].dn
262 def find_dc(ctx
, domain
):
263 """find a writeable DC for the given domain"""
265 ctx
.cldap_ret
= ctx
.net
.finddc(domain
=domain
, flags
=nbt
.NBT_SERVER_LDAP | nbt
.NBT_SERVER_DS | nbt
.NBT_SERVER_WRITABLE
)
267 raise Exception("Failed to find a writeable DC for domain '%s'" % domain
)
268 if ctx
.cldap_ret
.client_site
is not None and ctx
.cldap_ret
.client_site
!= "":
269 ctx
.site
= ctx
.cldap_ret
.client_site
270 return ctx
.cldap_ret
.pdc_dns_name
273 def get_behavior_version(ctx
):
274 res
= ctx
.samdb
.search(base
=ctx
.base_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["msDS-Behavior-Version"])
275 if "msDS-Behavior-Version" in res
[0]:
276 return int(res
[0]["msDS-Behavior-Version"][0])
278 return samba
.dsdb
.DS_DOMAIN_FUNCTION_2000
280 def get_dnsHostName(ctx
):
281 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])
282 return res
[0]["dnsHostName"][0]
284 def get_domain_name(ctx
):
285 '''get netbios name of the domain from the partitions record'''
286 partitions_dn
= ctx
.samdb
.get_partitions_dn()
287 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
288 expression
='ncName=%s' % ctx
.samdb
.get_default_basedn())
289 return res
[0]["nETBIOSName"][0]
291 def get_forest_domain_name(ctx
):
292 '''get netbios name of the domain from the partitions record'''
293 partitions_dn
= ctx
.samdb
.get_partitions_dn()
294 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
295 expression
='ncName=%s' % ctx
.samdb
.get_root_basedn())
296 return res
[0]["nETBIOSName"][0]
298 def get_parent_partition_dn(ctx
):
299 '''get the parent domain partition DN from parent DNS name'''
300 res
= ctx
.samdb
.search(base
=ctx
.config_dn
, attrs
=[],
301 expression
='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
302 (ctx
.parent_dnsdomain
, ldb
.OID_COMPARATOR_AND
, samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
))
303 return str(res
[0].dn
)
305 def get_naming_master(ctx
):
306 '''get the parent domain partition DN from parent DNS name'''
307 res
= ctx
.samdb
.search(base
='CN=Partitions,%s' % ctx
.config_dn
, attrs
=['fSMORoleOwner'],
308 scope
=ldb
.SCOPE_BASE
, controls
=["extended_dn:1:1"])
309 if not 'fSMORoleOwner' in res
[0]:
310 raise DCJoinException("Can't find naming master on partition DN %s in %s" % (ctx
.partition_dn
, ctx
.samdb
.url
))
312 master_guid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
314 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res
[0]['fSMORoleOwner'][0])
316 master_host
= '%s._msdcs.%s' % (master_guid
, ctx
.dnsforest
)
320 '''get the SID of the connected user. Only works with w2k8 and later,
321 so only used for RODC join'''
322 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["tokenGroups"])
323 binsid
= res
[0]["tokenGroups"][0]
324 return ctx
.samdb
.schema_format_value("objectSID", binsid
)
326 def dn_exists(ctx
, dn
):
327 '''check if a DN exists'''
329 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
, attrs
=[])
330 except ldb
.LdbError
, (enum
, estr
):
331 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
336 def add_krbtgt_account(ctx
):
337 '''RODCs need a special krbtgt account'''
338 print "Adding %s" % ctx
.krbtgt_dn
340 "dn" : ctx
.krbtgt_dn
,
341 "objectclass" : "user",
342 "useraccountcontrol" : str(samba
.dsdb
.UF_NORMAL_ACCOUNT |
343 samba
.dsdb
.UF_ACCOUNTDISABLE
),
344 "showinadvancedviewonly" : "TRUE",
345 "description" : "krbtgt for %s" % ctx
.samname
}
346 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
348 # now we need to search for the samAccountName attribute on the krbtgt DN,
349 # as this will have been magically set to the krbtgt number
350 res
= ctx
.samdb
.search(base
=ctx
.krbtgt_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["samAccountName"])
351 ctx
.krbtgt_name
= res
[0]["samAccountName"][0]
353 print "Got krbtgt_name=%s" % ctx
.krbtgt_name
356 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
357 m
["msDS-krbTgtLink"] = ldb
.MessageElement(ctx
.krbtgt_dn
,
358 ldb
.FLAG_MOD_REPLACE
, "msDS-krbTgtLink")
361 ctx
.new_krbtgt_dn
= "CN=%s,CN=Users,%s" % (ctx
.krbtgt_name
, ctx
.base_dn
)
362 print "Renaming %s to %s" % (ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
363 ctx
.samdb
.rename(ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
365 def drsuapi_connect(ctx
):
366 '''make a DRSUAPI connection to the naming master'''
367 binding_options
= "seal"
368 if int(ctx
.lp
.get("log level")) >= 4:
369 binding_options
+= ",print"
370 binding_string
= "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
)
371 ctx
.drsuapi
= drsuapi
.drsuapi(binding_string
, ctx
.lp
, ctx
.creds
)
372 (ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drs_DsBind(ctx
.drsuapi
)
374 def create_tmp_samdb(ctx
):
375 '''create a temporary samdb object for schema queries'''
376 ctx
.tmp_schema
= Schema(ctx
.domsid
,
377 schemadn
=ctx
.schema_dn
)
378 ctx
.tmp_samdb
= SamDB(session_info
=system_session(), url
=None, auto_connect
=False,
379 credentials
=ctx
.creds
, lp
=ctx
.lp
, global_schema
=False,
381 ctx
.tmp_samdb
.set_schema(ctx
.tmp_schema
)
383 def build_DsReplicaAttribute(ctx
, attrname
, attrvalue
):
384 '''build a DsReplicaAttributeCtr object'''
385 r
= drsuapi
.DsReplicaAttribute()
386 r
.attid
= ctx
.tmp_samdb
.get_attid_from_lDAPDisplayName(attrname
)
390 def DsAddEntry(ctx
, recs
):
391 '''add a record via the DRSUAPI DsAddEntry call'''
392 if ctx
.drsuapi
is None:
393 ctx
.drsuapi_connect()
394 if ctx
.tmp_samdb
is None:
395 ctx
.create_tmp_samdb()
399 id = drsuapi
.DsReplicaObjectIdentifier()
406 if not isinstance(rec
[a
], list):
410 rattr
= ctx
.tmp_samdb
.dsdb_DsReplicaAttribute(ctx
.tmp_samdb
, a
, v
)
413 attribute_ctr
= drsuapi
.DsReplicaAttributeCtr()
414 attribute_ctr
.num_attributes
= len(attrs
)
415 attribute_ctr
.attributes
= attrs
417 object = drsuapi
.DsReplicaObject()
418 object.identifier
= id
419 object.attribute_ctr
= attribute_ctr
421 list_object
= drsuapi
.DsReplicaObjectListItem()
422 list_object
.object = object
423 objects
.append(list_object
)
425 req2
= drsuapi
.DsAddEntryRequest2()
426 req2
.first_object
= objects
[0]
427 prev
= req2
.first_object
428 for o
in objects
[1:]:
432 (level
, ctr
) = ctx
.drsuapi
.DsAddEntry(ctx
.drsuapi_handle
, 2, req2
)
434 if ctr
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
435 print("DsAddEntry failed with dir_err %u" % ctr
.dir_err
)
436 raise RuntimeError("DsAddEntry failed")
437 if ctr
.extended_err
!= (0, 'WERR_OK'):
438 print("DsAddEntry failed with status %s info %s" % (ctr
.extended_err
))
439 raise RuntimeError("DsAddEntry failed")
442 raise RuntimeError("expected err_ver 1, got %u" % ctr
.err_ver
)
443 if ctr
.err_data
.status
!= (0, 'WERR_OK'):
444 print("DsAddEntry failed with status %s info %s" % (ctr
.err_data
.status
,
445 ctr
.err_data
.info
.extended_err
))
446 raise RuntimeError("DsAddEntry failed")
447 if ctr
.err_data
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
448 print("DsAddEntry failed with dir_err %u" % ctr
.err_data
.dir_err
)
449 raise RuntimeError("DsAddEntry failed")
453 def join_ntdsdsa_obj(ctx
):
454 '''return the ntdsdsa object to add'''
456 print "Adding %s" % ctx
.ntds_dn
459 "objectclass" : "nTDSDSA",
460 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
461 "dMDLocation" : ctx
.schema_dn
}
463 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
465 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
466 rec
["msDS-Behavior-Version"] = str(samba
.dsdb
.DS_DOMAIN_FUNCTION_2008_R2
)
468 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
469 rec
["msDS-HasDomainNCs"] = ctx
.base_dn
472 rec
["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx
.schema_dn
473 rec
["msDS-HasFullReplicaNCs"] = ctx
.full_nc_list
474 rec
["options"] = "37"
476 rec
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
477 rec
["HasMasterNCs"] = []
479 if nc
in ctx
.full_nc_list
:
480 rec
["HasMasterNCs"].append(nc
)
481 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
482 rec
["msDS-HasMasterNCs"] = ctx
.full_nc_list
484 rec
["invocationId"] = ndr_pack(ctx
.invocation_id
)
488 def join_add_ntdsdsa(ctx
):
489 '''add the ntdsdsa object'''
491 rec
= ctx
.join_ntdsdsa_obj()
493 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
495 ctx
.DsAddEntry([rec
])
497 # find the GUID of our NTDS DN
498 res
= ctx
.samdb
.search(base
=ctx
.ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["objectGUID"])
499 ctx
.ntds_guid
= misc
.GUID(ctx
.samdb
.schema_format_value("objectGUID", res
[0]["objectGUID"][0]))
501 def join_add_objects(ctx
):
502 '''add the various objects needed for the join'''
504 print "Adding %s" % ctx
.acct_dn
507 "objectClass": "computer",
508 "displayname": ctx
.samname
,
509 "samaccountname" : ctx
.samname
,
510 "userAccountControl" : str(ctx
.userAccountControl | samba
.dsdb
.UF_ACCOUNTDISABLE
),
511 "dnshostname" : ctx
.dnshostname
}
512 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2008
:
513 rec
['msDS-SupportedEncryptionTypes'] = str(samba
.dsdb
.ENC_ALL_TYPES
)
514 elif ctx
.promote_existing
:
515 rec
['msDS-SupportedEncryptionTypes'] = []
517 rec
["managedby"] = ctx
.managedby
518 elif ctx
.promote_existing
:
519 rec
["managedby"] = []
521 if ctx
.never_reveal_sid
:
522 rec
["msDS-NeverRevealGroup"] = ctx
.never_reveal_sid
523 elif ctx
.promote_existing
:
524 rec
["msDS-NeverRevealGroup"] = []
527 rec
["msDS-RevealOnDemandGroup"] = ctx
.reveal_sid
528 elif ctx
.promote_existing
:
529 rec
["msDS-RevealOnDemandGroup"] = []
531 if ctx
.promote_existing
:
532 if ctx
.promote_from_dn
!= ctx
.acct_dn
:
533 ctx
.samdb
.rename(ctx
.promote_from_dn
, ctx
.acct_dn
)
534 ctx
.samdb
.modify(ldb
.Message
.from_dict(ctx
.samdb
, rec
, ldb
.FLAG_MOD_REPLACE
))
539 ctx
.add_krbtgt_account()
541 print "Adding %s" % ctx
.server_dn
544 "objectclass" : "server",
545 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
546 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
547 samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
548 samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
549 # windows seems to add the dnsHostName later
550 "dnsHostName" : ctx
.dnshostname
}
553 rec
["serverReference"] = ctx
.acct_dn
558 # the rest is done after replication
562 ctx
.join_add_ntdsdsa()
564 if ctx
.connection_dn
is not None:
565 print "Adding %s" % ctx
.connection_dn
567 "dn" : ctx
.connection_dn
,
568 "objectclass" : "nTDSConnection",
569 "enabledconnection" : "TRUE",
571 "fromServer" : ctx
.dc_ntds_dn
}
575 print "Adding SPNs to %s" % ctx
.acct_dn
577 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
578 for i
in range(len(ctx
.SPNs
)):
579 ctx
.SPNs
[i
] = ctx
.SPNs
[i
].replace("$NTDSGUID", str(ctx
.ntds_guid
))
580 m
["servicePrincipalName"] = ldb
.MessageElement(ctx
.SPNs
,
581 ldb
.FLAG_MOD_REPLACE
,
582 "servicePrincipalName")
585 # The account password set operation should normally be done over
586 # LDAP. Windows 2000 DCs however allow this only with SSL
587 # connections which are hard to set up and otherwise refuse with
588 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
590 print "Setting account password for %s" % ctx
.samname
592 ctx
.samdb
.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
593 % ldb
.binary_encode(ctx
.samname
),
595 force_change_at_next_login
=False,
596 username
=ctx
.samname
)
597 except ldb
.LdbError
, (num
, _
):
598 if num
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
600 ctx
.net
.set_password(account_name
=ctx
.samname
,
601 domain_name
=ctx
.domain_name
,
602 newpassword
=ctx
.acct_pass
)
604 res
= ctx
.samdb
.search(base
=ctx
.acct_dn
, scope
=ldb
.SCOPE_BASE
,
605 attrs
=["msDS-KeyVersionNumber"])
606 if "msDS-KeyVersionNumber" in res
[0]:
607 ctx
.key_version_number
= int(res
[0]["msDS-KeyVersionNumber"][0])
609 ctx
.key_version_number
= None
611 print("Enabling account")
613 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
614 m
["userAccountControl"] = ldb
.MessageElement(str(ctx
.userAccountControl
),
615 ldb
.FLAG_MOD_REPLACE
,
616 "userAccountControl")
619 if ctx
.dns_backend
.startswith("BIND9_"):
620 ctx
.dnspass
= samba
.generate_random_password(128, 255)
622 recs
= ctx
.samdb
.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
623 {"DNSDOMAIN": ctx
.dnsdomain
,
624 "DOMAINDN": ctx
.base_dn
,
625 "HOSTNAME" : ctx
.myname
,
626 "DNSPASS_B64": b64encode(ctx
.dnspass
),
627 "DNSNAME" : ctx
.dnshostname
}))
628 for changetype
, msg
in recs
:
629 assert changetype
== ldb
.CHANGETYPE_NONE
630 dns_acct_dn
= msg
["dn"]
631 print "Adding DNS account %s with dns/ SPN" % msg
["dn"]
633 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
634 del msg
["clearTextPassword"]
635 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
636 del msg
["isCriticalSystemObject"]
637 # Disable account until password is set
638 msg
["userAccountControl"] = str(samba
.dsdb
.UF_NORMAL_ACCOUNT |
639 samba
.dsdb
.UF_ACCOUNTDISABLE
)
642 except ldb
.LdbError
, (num
, _
):
643 if num
!= ldb
.ERR_ENTRY_ALREADY_EXISTS
:
646 # The account password set operation should normally be done over
647 # LDAP. Windows 2000 DCs however allow this only with SSL
648 # connections which are hard to set up and otherwise refuse with
649 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
651 print "Setting account password for dns-%s" % ctx
.myname
653 ctx
.samdb
.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
654 % ldb
.binary_encode(ctx
.myname
),
656 force_change_at_next_login
=False,
657 username
=ctx
.samname
)
658 except ldb
.LdbError
, (num
, _
):
659 if num
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
661 ctx
.net
.set_password(account_name
="dns-%s" % ctx
.myname
,
662 domain_name
=ctx
.domain_name
,
663 newpassword
=ctx
.dnspass
)
665 res
= ctx
.samdb
.search(base
=dns_acct_dn
, scope
=ldb
.SCOPE_BASE
,
666 attrs
=["msDS-KeyVersionNumber"])
667 if "msDS-KeyVersionNumber" in res
[0]:
668 ctx
.dns_key_version_number
= int(res
[0]["msDS-KeyVersionNumber"][0])
670 ctx
.dns_key_version_number
= None
672 def join_add_objects2(ctx
):
673 """add the various objects needed for the join, for subdomains post replication"""
675 print "Adding %s" % ctx
.partition_dn
676 name_map
= {'SubdomainAdmins': "%s-%s" % (str(ctx
.domsid
), security
.DOMAIN_RID_ADMINS
)}
677 sd_binary
= descriptor
.get_paritions_crossref_subdomain_descriptor(ctx
.forestsid
, name_map
=name_map
)
679 "dn" : ctx
.partition_dn
,
680 "objectclass" : "crossRef",
681 "objectCategory" : "CN=Cross-Ref,%s" % ctx
.schema_dn
,
682 "nCName" : ctx
.base_dn
,
683 "nETBIOSName" : ctx
.domain_name
,
684 "dnsRoot": ctx
.dnsdomain
,
685 "trustParent" : ctx
.parent_partition_dn
,
686 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_NC|samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
),
687 "ntSecurityDescriptor" : sd_binary
,
690 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
691 rec
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
693 rec2
= ctx
.join_ntdsdsa_obj()
695 objects
= ctx
.DsAddEntry([rec
, rec2
])
696 if len(objects
) != 2:
697 raise DCJoinException("Expected 2 objects from DsAddEntry")
699 ctx
.ntds_guid
= objects
[1].guid
701 print("Replicating partition DN")
702 ctx
.repl
.replicate(ctx
.partition_dn
,
703 misc
.GUID("00000000-0000-0000-0000-000000000000"),
705 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
706 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
708 print("Replicating NTDS DN")
709 ctx
.repl
.replicate(ctx
.ntds_dn
,
710 misc
.GUID("00000000-0000-0000-0000-000000000000"),
712 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
713 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
715 def join_provision(ctx
):
716 """Provision the local SAM."""
718 print "Calling bare provision"
720 smbconf
= ctx
.lp
.configfile
722 presult
= provision(ctx
.logger
, system_session(), smbconf
=smbconf
,
723 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_DRS
, realm
=ctx
.realm
,
724 rootdn
=ctx
.root_dn
, domaindn
=ctx
.base_dn
,
725 schemadn
=ctx
.schema_dn
, configdn
=ctx
.config_dn
,
726 serverdn
=ctx
.server_dn
, domain
=ctx
.domain_name
,
727 hostname
=ctx
.myname
, domainsid
=ctx
.domsid
,
728 machinepass
=ctx
.acct_pass
, serverrole
="active directory domain controller",
729 sitename
=ctx
.site
, lp
=ctx
.lp
, ntdsguid
=ctx
.ntds_guid
,
730 use_ntvfs
=ctx
.use_ntvfs
, dns_backend
=ctx
.dns_backend
)
731 print "Provision OK for domain DN %s" % presult
.domaindn
732 ctx
.local_samdb
= presult
.samdb
734 ctx
.paths
= presult
.paths
735 ctx
.names
= presult
.names
737 # Fix up the forestsid, it may be different if we are joining as a subdomain
738 ctx
.names
.forestsid
= ctx
.forestsid
740 def join_provision_own_domain(ctx
):
741 """Provision the local SAM."""
743 # we now operate exclusively on the local database, which
744 # we need to reopen in order to get the newly created schema
745 print("Reconnecting to local samdb")
746 ctx
.samdb
= SamDB(url
=ctx
.local_samdb
.url
,
747 session_info
=system_session(),
748 lp
=ctx
.local_samdb
.lp
,
750 ctx
.samdb
.set_invocation_id(str(ctx
.invocation_id
))
751 ctx
.local_samdb
= ctx
.samdb
753 ctx
.logger
.info("Finding domain GUID from ncName")
754 res
= ctx
.local_samdb
.search(base
=ctx
.partition_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['ncName'],
755 controls
=["extended_dn:1:1", "reveal_internals:0"])
757 if 'nCName' not in res
[0]:
758 raise DCJoinException("Can't find naming context on partition DN %s in %s" % (ctx
.partition_dn
, ctx
.samdb
.url
))
761 ctx
.names
.domainguid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['ncName'][0]).get_extended_component('GUID')))
763 raise DCJoinException("Can't find GUID in naming master on partition DN %s" % res
[0]['ncName'][0])
765 ctx
.logger
.info("Got domain GUID %s" % ctx
.names
.domainguid
)
767 ctx
.logger
.info("Calling own domain provision")
769 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
771 presult
= provision_fill(ctx
.local_samdb
, secrets_ldb
,
772 ctx
.logger
, ctx
.names
, ctx
.paths
,
773 dom_for_fun_level
=DS_DOMAIN_FUNCTION_2003
,
774 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_SUBDOMAIN
,
775 machinepass
=ctx
.acct_pass
, serverrole
="active directory domain controller",
776 lp
=ctx
.lp
, hostip
=ctx
.names
.hostip
, hostip6
=ctx
.names
.hostip6
,
777 dns_backend
=ctx
.dns_backend
, adminpass
=ctx
.adminpass
)
778 print("Provision OK for domain %s" % ctx
.names
.dnsdomain
)
780 def join_replicate(ctx
):
781 """Replicate the SAM."""
783 print "Starting replication"
784 ctx
.local_samdb
.transaction_start()
786 source_dsa_invocation_id
= misc
.GUID(ctx
.samdb
.get_invocation_id())
787 if ctx
.ntds_guid
is None:
788 print("Using DS_BIND_GUID_W2K3")
789 destination_dsa_guid
= misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID_W2K3
)
791 destination_dsa_guid
= ctx
.ntds_guid
794 repl_creds
= Credentials()
795 repl_creds
.guess(ctx
.lp
)
796 repl_creds
.set_kerberos_state(DONT_USE_KERBEROS
)
797 repl_creds
.set_username(ctx
.samname
)
798 repl_creds
.set_password(ctx
.acct_pass
)
800 repl_creds
= ctx
.creds
802 binding_options
= "seal"
803 if int(ctx
.lp
.get("log level")) >= 5:
804 binding_options
+= ",print"
805 repl
= drs_utils
.drs_Replicate(
806 "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
807 ctx
.lp
, repl_creds
, ctx
.local_samdb
, ctx
.invocation_id
)
809 repl
.replicate(ctx
.schema_dn
, source_dsa_invocation_id
,
810 destination_dsa_guid
, schema
=True, rodc
=ctx
.RODC
,
811 replica_flags
=ctx
.replica_flags
)
812 repl
.replicate(ctx
.config_dn
, source_dsa_invocation_id
,
813 destination_dsa_guid
, rodc
=ctx
.RODC
,
814 replica_flags
=ctx
.replica_flags
)
815 if not ctx
.subdomain
:
816 # Replicate first the critical object for the basedn
817 if not ctx
.domain_replica_flags
& drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
:
818 print "Replicating critical objects from the base DN of the domain"
819 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi
.DRSUAPI_DRS_GET_ANC
820 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
821 destination_dsa_guid
, rodc
=ctx
.RODC
,
822 replica_flags
=ctx
.domain_replica_flags
)
823 ctx
.domain_replica_flags ^
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi
.DRSUAPI_DRS_GET_ANC
825 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_GET_ANC
826 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
827 destination_dsa_guid
, rodc
=ctx
.RODC
,
828 replica_flags
=ctx
.domain_replica_flags
)
829 print "Done with always replicated NC (base, config, schema)"
831 for nc
in (ctx
.domaindns_zone
, ctx
.forestdns_zone
):
832 if nc
in ctx
.nc_list
:
833 print "Replicating %s" % (str(nc
))
834 repl
.replicate(nc
, source_dsa_invocation_id
,
835 destination_dsa_guid
, rodc
=ctx
.RODC
,
836 replica_flags
=ctx
.replica_flags
)
838 # FIXME At this point we should add an entry in the forestdns and domaindns NC
839 # (those under CN=Partions,DC=...)
840 # in order to indicate that we hold a replica for this NC
843 repl
.replicate(ctx
.acct_dn
, source_dsa_invocation_id
,
844 destination_dsa_guid
,
845 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
846 repl
.replicate(ctx
.new_krbtgt_dn
, source_dsa_invocation_id
,
847 destination_dsa_guid
,
848 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
850 ctx
.source_dsa_invocation_id
= source_dsa_invocation_id
851 ctx
.destination_dsa_guid
= destination_dsa_guid
853 print "Committing SAM database"
855 ctx
.local_samdb
.transaction_cancel()
858 ctx
.local_samdb
.transaction_commit()
860 def send_DsReplicaUpdateRefs(ctx
, dn
):
861 r
= drsuapi
.DsReplicaUpdateRefsRequest1()
862 r
.naming_context
= drsuapi
.DsReplicaObjectIdentifier()
863 r
.naming_context
.dn
= str(dn
)
864 r
.naming_context
.guid
= misc
.GUID("00000000-0000-0000-0000-000000000000")
865 r
.naming_context
.sid
= security
.dom_sid("S-0-0")
866 r
.dest_dsa_guid
= ctx
.ntds_guid
867 r
.dest_dsa_dns_name
= "%s._msdcs.%s" % (str(ctx
.ntds_guid
), ctx
.dnsforest
)
868 r
.options
= drsuapi
.DRSUAPI_DRS_ADD_REF | drsuapi
.DRSUAPI_DRS_DEL_REF
870 r
.options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
873 ctx
.drsuapi
.DsReplicaUpdateRefs(ctx
.drsuapi_handle
, 1, r
)
875 def join_finalise(ctx
):
876 """Finalise the join, mark us synchronised and setup secrets db."""
878 # FIXME we shouldn't do this in all cases
879 # If for some reasons we joined in another site than the one of
880 # DC we just replicated from then we don't need to send the updatereplicateref
881 # as replication between sites is time based and on the initiative of the
883 ctx
.logger
.info("Sending DsReplicaUpdateRefs for all the replicated partitions")
884 for nc
in ctx
.nc_list
:
885 ctx
.send_DsReplicaUpdateRefs(nc
)
888 print "Setting RODC invocationId"
889 ctx
.local_samdb
.set_invocation_id(str(ctx
.invocation_id
))
890 ctx
.local_samdb
.set_opaque_integer("domainFunctionality",
891 ctx
.behavior_version
)
893 m
.dn
= ldb
.Dn(ctx
.local_samdb
, "%s" % ctx
.ntds_dn
)
894 m
["invocationId"] = ldb
.MessageElement(ndr_pack(ctx
.invocation_id
),
895 ldb
.FLAG_MOD_REPLACE
,
897 ctx
.local_samdb
.modify(m
)
899 # Note: as RODC the invocationId is only stored
900 # on the RODC itself, the other DCs never see it.
902 # Thats is why we fix up the replPropertyMetaData stamp
903 # for the 'invocationId' attribute, we need to change
904 # the 'version' to '0', this is what windows 2008r2 does as RODC
906 # This means if the object on a RWDC ever gets a invocationId
907 # attribute, it will have version '1' (or higher), which will
908 # will overwrite the RODC local value.
909 ctx
.local_samdb
.set_attribute_replmetadata_version(m
.dn
,
913 ctx
.logger
.info("Setting isSynchronized and dsServiceName")
915 m
.dn
= ldb
.Dn(ctx
.local_samdb
, '@ROOTDSE')
916 m
["isSynchronized"] = ldb
.MessageElement("TRUE", ldb
.FLAG_MOD_REPLACE
, "isSynchronized")
917 m
["dsServiceName"] = ldb
.MessageElement("<GUID=%s>" % str(ctx
.ntds_guid
),
918 ldb
.FLAG_MOD_REPLACE
, "dsServiceName")
919 ctx
.local_samdb
.modify(m
)
924 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
926 ctx
.logger
.info("Setting up secrets database")
927 secretsdb_self_join(secrets_ldb
, domain
=ctx
.domain_name
,
929 dnsdomain
=ctx
.dnsdomain
,
930 netbiosname
=ctx
.myname
,
931 domainsid
=ctx
.domsid
,
932 machinepass
=ctx
.acct_pass
,
933 secure_channel_type
=ctx
.secure_channel_type
,
934 key_version_number
=ctx
.key_version_number
)
936 if ctx
.dns_backend
.startswith("BIND9_"):
937 setup_bind9_dns(ctx
.local_samdb
, secrets_ldb
,
938 ctx
.names
, ctx
.paths
, ctx
.lp
, ctx
.logger
,
939 dns_backend
=ctx
.dns_backend
,
940 dnspass
=ctx
.dnspass
, os_level
=ctx
.behavior_version
,
941 targetdir
=ctx
.targetdir
,
942 key_version_number
=ctx
.dns_key_version_number
)
944 def join_setup_trusts(ctx
):
945 """provision the local SAM."""
947 def arcfour_encrypt(key
, data
):
948 from Crypto
.Cipher
import ARC4
950 return c
.encrypt(data
)
952 def string_to_array(string
):
953 blob
= [0] * len(string
)
955 for i
in range(len(string
)):
956 blob
[i
] = ord(string
[i
])
960 print "Setup domain trusts with server %s" % ctx
.server
961 binding_options
= "" # why doesn't signing work here? w2k8r2 claims no session key
962 lsaconn
= lsa
.lsarpc("ncacn_np:%s[%s]" % (ctx
.server
, binding_options
),
965 objectAttr
= lsa
.ObjectAttribute()
966 objectAttr
.sec_qos
= lsa
.QosInfo()
968 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
969 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
971 info
= lsa
.TrustDomainInfoInfoEx()
972 info
.domain_name
.string
= ctx
.dnsdomain
973 info
.netbios_name
.string
= ctx
.domain_name
974 info
.sid
= ctx
.domsid
975 info
.trust_direction
= lsa
.LSA_TRUST_DIRECTION_INBOUND | lsa
.LSA_TRUST_DIRECTION_OUTBOUND
976 info
.trust_type
= lsa
.LSA_TRUST_TYPE_UPLEVEL
977 info
.trust_attributes
= lsa
.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
980 oldname
= lsa
.String()
981 oldname
.string
= ctx
.dnsdomain
982 oldinfo
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, oldname
,
983 lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
984 print("Removing old trust record for %s (SID %s)" % (ctx
.dnsdomain
, oldinfo
.info_ex
.sid
))
985 lsaconn
.DeleteTrustedDomain(pol_handle
, oldinfo
.info_ex
.sid
)
989 password_blob
= string_to_array(ctx
.trustdom_pass
.encode('utf-16-le'))
991 clear_value
= drsblobs
.AuthInfoClear()
992 clear_value
.size
= len(password_blob
)
993 clear_value
.password
= password_blob
995 clear_authentication_information
= drsblobs
.AuthenticationInformation()
996 clear_authentication_information
.LastUpdateTime
= samba
.unix2nttime(int(time
.time()))
997 clear_authentication_information
.AuthType
= lsa
.TRUST_AUTH_TYPE_CLEAR
998 clear_authentication_information
.AuthInfo
= clear_value
1000 authentication_information_array
= drsblobs
.AuthenticationInformationArray()
1001 authentication_information_array
.count
= 1
1002 authentication_information_array
.array
= [clear_authentication_information
]
1004 outgoing
= drsblobs
.trustAuthInOutBlob()
1006 outgoing
.current
= authentication_information_array
1008 trustpass
= drsblobs
.trustDomainPasswords()
1009 confounder
= [3] * 512
1011 for i
in range(512):
1012 confounder
[i
] = random
.randint(0, 255)
1014 trustpass
.confounder
= confounder
1016 trustpass
.outgoing
= outgoing
1017 trustpass
.incoming
= outgoing
1019 trustpass_blob
= ndr_pack(trustpass
)
1021 encrypted_trustpass
= arcfour_encrypt(lsaconn
.session_key
, trustpass_blob
)
1023 auth_blob
= lsa
.DATA_BUF2()
1024 auth_blob
.size
= len(encrypted_trustpass
)
1025 auth_blob
.data
= string_to_array(encrypted_trustpass
)
1027 auth_info
= lsa
.TrustDomainInfoAuthInfoInternal()
1028 auth_info
.auth_blob
= auth_blob
1030 trustdom_handle
= lsaconn
.CreateTrustedDomainEx2(pol_handle
,
1033 security
.SEC_STD_DELETE
)
1036 "dn" : "cn=%s,cn=system,%s" % (ctx
.dnsforest
, ctx
.base_dn
),
1037 "objectclass" : "trustedDomain",
1038 "trustType" : str(info
.trust_type
),
1039 "trustAttributes" : str(info
.trust_attributes
),
1040 "trustDirection" : str(info
.trust_direction
),
1041 "flatname" : ctx
.forest_domain_name
,
1042 "trustPartner" : ctx
.dnsforest
,
1043 "trustAuthIncoming" : ndr_pack(outgoing
),
1044 "trustAuthOutgoing" : ndr_pack(outgoing
),
1045 "securityIdentifier" : ndr_pack(ctx
.forestsid
)
1047 ctx
.local_samdb
.add(rec
)
1050 "dn" : "cn=%s$,cn=users,%s" % (ctx
.forest_domain_name
, ctx
.base_dn
),
1051 "objectclass" : "user",
1052 "userAccountControl" : str(samba
.dsdb
.UF_INTERDOMAIN_TRUST_ACCOUNT
),
1053 "clearTextPassword" : ctx
.trustdom_pass
.encode('utf-16-le'),
1054 "samAccountName" : "%s$" % ctx
.forest_domain_name
1056 ctx
.local_samdb
.add(rec
)
1060 # nc_list is the list of naming context (NC) for which we will
1061 # replicate in and send a updateRef command to the partner DC
1063 # full_nc_list is the list of naming context (NC) we hold
1064 # read/write copies of. These are not subsets of each other.
1065 ctx
.nc_list
= [ ctx
.config_dn
, ctx
.schema_dn
]
1066 ctx
.full_nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
1068 if ctx
.subdomain
and ctx
.dns_backend
!= "NONE":
1069 ctx
.full_nc_list
+= [ctx
.domaindns_zone
]
1071 elif not ctx
.subdomain
:
1072 ctx
.nc_list
+= [ctx
.base_dn
]
1074 if ctx
.dns_backend
!= "NONE":
1075 ctx
.nc_list
+= [ctx
.domaindns_zone
]
1076 ctx
.nc_list
+= [ctx
.forestdns_zone
]
1077 ctx
.full_nc_list
+= [ctx
.domaindns_zone
]
1078 ctx
.full_nc_list
+= [ctx
.forestdns_zone
]
1080 if ctx
.promote_existing
:
1081 ctx
.promote_possible()
1083 ctx
.cleanup_old_join()
1086 ctx
.join_add_objects()
1087 ctx
.join_provision()
1088 ctx
.join_replicate()
1090 ctx
.join_add_objects2()
1091 ctx
.join_provision_own_domain()
1092 ctx
.join_setup_trusts()
1095 print "Join failed - cleaning up"
1096 ctx
.cleanup_old_join()
1100 def join_RODC(logger
=None, server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
1101 targetdir
=None, domain
=None, domain_critical_only
=False,
1102 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
1103 promote_existing
=False):
1104 """Join as a RODC."""
1106 ctx
= dc_join(logger
, server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
,
1107 machinepass
, use_ntvfs
, dns_backend
, promote_existing
)
1109 lp
.set("workgroup", ctx
.domain_name
)
1110 logger
.info("workgroup is %s" % ctx
.domain_name
)
1112 lp
.set("realm", ctx
.realm
)
1113 logger
.info("realm is %s" % ctx
.realm
)
1115 ctx
.krbtgt_dn
= "CN=krbtgt_%s,CN=Users,%s" % (ctx
.myname
, ctx
.base_dn
)
1117 # setup some defaults for accounts that should be replicated to this RODC
1118 ctx
.never_reveal_sid
= [
1119 "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_DENY
),
1120 "<SID=%s>" % security
.SID_BUILTIN_ADMINISTRATORS
,
1121 "<SID=%s>" % security
.SID_BUILTIN_SERVER_OPERATORS
,
1122 "<SID=%s>" % security
.SID_BUILTIN_BACKUP_OPERATORS
,
1123 "<SID=%s>" % security
.SID_BUILTIN_ACCOUNT_OPERATORS
]
1124 ctx
.reveal_sid
= "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_ALLOW
)
1126 mysid
= ctx
.get_mysid()
1127 admin_dn
= "<SID=%s>" % mysid
1128 ctx
.managedby
= admin_dn
1130 ctx
.userAccountControl
= (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
1131 samba
.dsdb
.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1132 samba
.dsdb
.UF_PARTIAL_SECRETS_ACCOUNT
)
1134 ctx
.SPNs
.extend([ "RestrictedKrbHost/%s" % ctx
.myname
,
1135 "RestrictedKrbHost/%s" % ctx
.dnshostname
])
1137 ctx
.connection_dn
= "CN=RODC Connection (FRS),%s" % ctx
.ntds_dn
1138 ctx
.secure_channel_type
= misc
.SEC_CHAN_RODC
1140 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1141 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1142 drsuapi
.DRSUAPI_DRS_GET_ANC |
1143 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED |
1144 drsuapi
.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1145 drsuapi
.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP
)
1146 ctx
.domain_replica_flags
= ctx
.replica_flags
1147 if domain_critical_only
:
1148 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
1152 logger
.info("Joined domain %s (SID %s) as an RODC" % (ctx
.domain_name
, ctx
.domsid
))
1155 def join_DC(logger
=None, server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
1156 targetdir
=None, domain
=None, domain_critical_only
=False,
1157 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
1158 promote_existing
=False):
1160 ctx
= dc_join(logger
, server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
,
1161 machinepass
, use_ntvfs
, dns_backend
, promote_existing
)
1163 lp
.set("workgroup", ctx
.domain_name
)
1164 logger
.info("workgroup is %s" % ctx
.domain_name
)
1166 lp
.set("realm", ctx
.realm
)
1167 logger
.info("realm is %s" % ctx
.realm
)
1169 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
1171 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
1172 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
1174 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
1175 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1176 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1177 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1178 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
1179 ctx
.domain_replica_flags
= ctx
.replica_flags
1180 if domain_critical_only
:
1181 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
1184 logger
.info("Joined domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
))
1186 def join_subdomain(logger
=None, server
=None, creds
=None, lp
=None, site
=None,
1187 netbios_name
=None, targetdir
=None, parent_domain
=None, dnsdomain
=None,
1188 netbios_domain
=None, machinepass
=None, adminpass
=None, use_ntvfs
=False,
1191 ctx
= dc_join(logger
, server
, creds
, lp
, site
, netbios_name
, targetdir
, parent_domain
,
1192 machinepass
, use_ntvfs
, dns_backend
)
1193 ctx
.subdomain
= True
1194 if adminpass
is None:
1195 ctx
.adminpass
= samba
.generate_random_password(12, 32)
1197 ctx
.adminpass
= adminpass
1198 ctx
.parent_domain_name
= ctx
.domain_name
1199 ctx
.domain_name
= netbios_domain
1200 ctx
.realm
= dnsdomain
1201 ctx
.parent_dnsdomain
= ctx
.dnsdomain
1202 ctx
.parent_partition_dn
= ctx
.get_parent_partition_dn()
1203 ctx
.dnsdomain
= dnsdomain
1204 ctx
.partition_dn
= "CN=%s,CN=Partitions,%s" % (ctx
.domain_name
, ctx
.config_dn
)
1205 ctx
.naming_master
= ctx
.get_naming_master()
1206 if ctx
.naming_master
!= ctx
.server
:
1207 logger
.info("Reconnecting to naming master %s" % ctx
.naming_master
)
1208 ctx
.server
= ctx
.naming_master
1209 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
1210 session_info
=system_session(),
1211 credentials
=ctx
.creds
, lp
=ctx
.lp
)
1212 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=['dnsHostName'],
1214 ctx
.server
= res
[0]["dnsHostName"]
1215 logger
.info("DNS name of new naming master is %s" % ctx
.server
)
1217 ctx
.base_dn
= samba
.dn_from_dns_name(dnsdomain
)
1218 ctx
.forestsid
= ctx
.domsid
1219 ctx
.domsid
= security
.random_sid()
1221 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
.lower(), ctx
.dnsdomain
)
1222 ctx
.trustdom_pass
= samba
.generate_random_password(128, 128)
1224 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
1226 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
1227 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
1229 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
1230 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1231 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1232 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1233 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
1234 ctx
.domain_replica_flags
= ctx
.replica_flags
1237 ctx
.logger
.info("Created domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
))