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
.credentials
import Credentials
, DONT_USE_KERBEROS
28 from samba
.provision
import secretsdb_self_join
, provision
, provision_fill
, FILL_DRS
, FILL_SUBDOMAIN
29 from samba
.provision
.common
import setup_path
30 from samba
.schema
import Schema
31 from samba
.net
import Net
32 from samba
.provision
.sambadns
import setup_bind9_dns
33 from samba
import read_and_sub_file
34 from base64
import b64encode
40 # this makes debugging easier
41 talloc
.enable_null_tracking()
43 class DCJoinException(Exception):
45 def __init__(self
, msg
):
46 super(DCJoinException
, self
).__init
__("Can't join, error: %s" % msg
)
49 class dc_join(object):
50 """Perform a DC join."""
52 def __init__(ctx
, server
=None, creds
=None, lp
=None, site
=None,
53 netbios_name
=None, targetdir
=None, domain
=None,
54 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
55 promote_existing
=False):
59 ctx
.netbios_name
= netbios_name
60 ctx
.targetdir
= targetdir
61 ctx
.use_ntvfs
= use_ntvfs
63 ctx
.promote_existing
= promote_existing
64 ctx
.promote_from_dn
= None
69 ctx
.creds
.set_gensec_features(creds
.get_gensec_features() | gensec
.FEATURE_SEAL
)
70 ctx
.net
= Net(creds
=ctx
.creds
, lp
=ctx
.lp
)
72 if server
is not None:
75 print("Finding a writeable DC for domain '%s'" % domain
)
76 ctx
.server
= ctx
.find_dc(domain
)
77 print("Found DC %s" % ctx
.server
)
79 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
80 session_info
=system_session(),
81 credentials
=ctx
.creds
, lp
=ctx
.lp
)
84 ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
85 except ldb
.LdbError
, (enum
, estr
):
86 raise DCJoinException(estr
)
89 ctx
.myname
= netbios_name
90 ctx
.samname
= "%s$" % ctx
.myname
91 ctx
.base_dn
= str(ctx
.samdb
.get_default_basedn())
92 ctx
.root_dn
= str(ctx
.samdb
.get_root_basedn())
93 ctx
.schema_dn
= str(ctx
.samdb
.get_schema_basedn())
94 ctx
.config_dn
= str(ctx
.samdb
.get_config_basedn())
95 ctx
.domsid
= ctx
.samdb
.get_domain_sid()
96 ctx
.domain_name
= ctx
.get_domain_name()
97 ctx
.forest_domain_name
= ctx
.get_forest_domain_name()
98 ctx
.invocation_id
= misc
.GUID(str(uuid
.uuid4()))
100 ctx
.dc_ntds_dn
= ctx
.samdb
.get_dsServiceName()
101 ctx
.dc_dnsHostName
= ctx
.get_dnsHostName()
102 ctx
.behavior_version
= ctx
.get_behavior_version()
104 if machinepass
is not None:
105 ctx
.acct_pass
= machinepass
107 ctx
.acct_pass
= samba
.generate_random_password(32, 40)
109 # work out the DNs of all the objects we will be adding
110 ctx
.server_dn
= "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx
.myname
, ctx
.site
, ctx
.config_dn
)
111 ctx
.ntds_dn
= "CN=NTDS Settings,%s" % ctx
.server_dn
112 topology_base
= "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx
.base_dn
113 if ctx
.dn_exists(topology_base
):
114 ctx
.topology_dn
= "CN=%s,%s" % (ctx
.myname
, topology_base
)
116 ctx
.topology_dn
= None
118 ctx
.dnsdomain
= ctx
.samdb
.domain_dns_name()
119 ctx
.dnsforest
= ctx
.samdb
.forest_dns_name()
120 ctx
.domaindns_zone
= 'DC=DomainDnsZones,%s' % ctx
.base_dn
121 ctx
.forestdns_zone
= 'DC=ForestDnsZones,%s' % ctx
.base_dn
123 res_domaindns
= ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
,
125 base
=ctx
.samdb
.get_partitions_dn(),
126 expression
="(&(objectClass=crossRef)(ncName=%s))" % ctx
.domaindns_zone
)
127 if dns_backend
is None:
128 ctx
.dns_backend
= "NONE"
130 if len(res_domaindns
) == 0:
131 ctx
.dns_backend
= "NONE"
132 print "NO DNS zone information found in source domain, not replicating DNS"
134 ctx
.dns_backend
= dns_backend
136 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
, ctx
.dnsdomain
)
138 ctx
.realm
= ctx
.dnsdomain
140 ctx
.acct_dn
= "CN=%s,OU=Domain Controllers,%s" % (ctx
.myname
, ctx
.base_dn
)
144 ctx
.SPNs
= [ "HOST/%s" % ctx
.myname
,
145 "HOST/%s" % ctx
.dnshostname
,
146 "GC/%s/%s" % (ctx
.dnshostname
, ctx
.dnsforest
) ]
148 # these elements are optional
149 ctx
.never_reveal_sid
= None
150 ctx
.reveal_sid
= None
151 ctx
.connection_dn
= None
156 ctx
.subdomain
= False
158 def del_noerror(ctx
, dn
, recursive
=False):
161 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
165 ctx
.del_noerror(r
.dn
, recursive
=True)
168 print "Deleted %s" % dn
172 def cleanup_old_join(ctx
):
173 """Remove any DNs from a previous join."""
175 # find the krbtgt link
176 print("checking sAMAccountName")
180 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
181 expression
='sAMAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
182 attrs
=["msDS-krbTgtLink"])
184 ctx
.del_noerror(res
[0].dn
, recursive
=True)
186 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
187 expression
='(&(sAMAccountName=%s)(servicePrincipalName=%s))' % (ldb
.binary_encode("dns-%s" % ctx
.myname
), ldb
.binary_encode("dns/%s" % ctx
.dnshostname
)),
190 ctx
.del_noerror(res
[0].dn
, recursive
=True)
192 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
193 expression
='(sAMAccountName=%s)' % ldb
.binary_encode("dns-%s" % ctx
.myname
),
196 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
)))
198 if ctx
.connection_dn
is not None:
199 ctx
.del_noerror(ctx
.connection_dn
)
200 if ctx
.krbtgt_dn
is not None:
201 ctx
.del_noerror(ctx
.krbtgt_dn
)
202 ctx
.del_noerror(ctx
.ntds_dn
)
203 ctx
.del_noerror(ctx
.server_dn
, recursive
=True)
205 ctx
.del_noerror(ctx
.topology_dn
)
207 ctx
.del_noerror(ctx
.partition_dn
)
209 ctx
.new_krbtgt_dn
= res
[0]["msDS-Krbtgtlink"][0]
210 ctx
.del_noerror(ctx
.new_krbtgt_dn
)
213 binding_options
= "sign"
214 lsaconn
= lsa
.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
217 objectAttr
= lsa
.ObjectAttribute()
218 objectAttr
.sec_qos
= lsa
.QosInfo()
220 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
221 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
224 name
.string
= ctx
.realm
225 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
227 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
230 name
.string
= ctx
.forest_domain_name
231 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
233 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
238 def promote_possible(ctx
):
239 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
241 # This shouldn't happen
242 raise Exception("Can not promote into a subdomain")
244 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
245 expression
='sAMAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
246 attrs
=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
248 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx
.samname
)
249 if "msDS-krbTgtLink" in res
[0] or "serverReferenceBL" in res
[0] or "rIDSetReferences" in res
[0]:
250 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx
.samname
)
251 if (int(res
[0]["userAccountControl"][0]) & (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT|samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT
) == 0):
252 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx
.samname
)
254 ctx
.promote_from_dn
= res
[0].dn
257 def find_dc(ctx
, domain
):
258 """find a writeable DC for the given domain"""
260 ctx
.cldap_ret
= ctx
.net
.finddc(domain
=domain
, flags
=nbt
.NBT_SERVER_LDAP | nbt
.NBT_SERVER_DS | nbt
.NBT_SERVER_WRITABLE
)
262 raise Exception("Failed to find a writeable DC for domain '%s'" % domain
)
263 if ctx
.cldap_ret
.client_site
is not None and ctx
.cldap_ret
.client_site
!= "":
264 ctx
.site
= ctx
.cldap_ret
.client_site
265 return ctx
.cldap_ret
.pdc_dns_name
268 def get_behavior_version(ctx
):
269 res
= ctx
.samdb
.search(base
=ctx
.base_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["msDS-Behavior-Version"])
270 if "msDS-Behavior-Version" in res
[0]:
271 return int(res
[0]["msDS-Behavior-Version"][0])
273 return samba
.dsdb
.DS_DOMAIN_FUNCTION_2000
275 def get_dnsHostName(ctx
):
276 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])
277 return res
[0]["dnsHostName"][0]
279 def get_domain_name(ctx
):
280 '''get netbios name of the domain from the partitions record'''
281 partitions_dn
= ctx
.samdb
.get_partitions_dn()
282 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
283 expression
='ncName=%s' % ctx
.samdb
.get_default_basedn())
284 return res
[0]["nETBIOSName"][0]
286 def get_forest_domain_name(ctx
):
287 '''get netbios name of the domain from the partitions record'''
288 partitions_dn
= ctx
.samdb
.get_partitions_dn()
289 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
290 expression
='ncName=%s' % ctx
.samdb
.get_root_basedn())
291 return res
[0]["nETBIOSName"][0]
293 def get_parent_partition_dn(ctx
):
294 '''get the parent domain partition DN from parent DNS name'''
295 res
= ctx
.samdb
.search(base
=ctx
.config_dn
, attrs
=[],
296 expression
='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
297 (ctx
.parent_dnsdomain
, ldb
.OID_COMPARATOR_AND
, samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
))
298 return str(res
[0].dn
)
300 def get_naming_master(ctx
):
301 '''get the parent domain partition DN from parent DNS name'''
302 res
= ctx
.samdb
.search(base
='CN=Partitions,%s' % ctx
.config_dn
, attrs
=['fSMORoleOwner'],
303 scope
=ldb
.SCOPE_BASE
, controls
=["extended_dn:1:1"])
304 if not 'fSMORoleOwner' in res
[0]:
305 raise DCJoinException("Can't find naming master on partition DN %s" % ctx
.partition_dn
)
306 master_guid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
307 master_host
= '%s._msdcs.%s' % (master_guid
, ctx
.dnsforest
)
311 '''get the SID of the connected user. Only works with w2k8 and later,
312 so only used for RODC join'''
313 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["tokenGroups"])
314 binsid
= res
[0]["tokenGroups"][0]
315 return ctx
.samdb
.schema_format_value("objectSID", binsid
)
317 def dn_exists(ctx
, dn
):
318 '''check if a DN exists'''
320 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
, attrs
=[])
321 except ldb
.LdbError
, (enum
, estr
):
322 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
327 def add_krbtgt_account(ctx
):
328 '''RODCs need a special krbtgt account'''
329 print "Adding %s" % ctx
.krbtgt_dn
331 "dn" : ctx
.krbtgt_dn
,
332 "objectclass" : "user",
333 "useraccountcontrol" : str(samba
.dsdb
.UF_NORMAL_ACCOUNT |
334 samba
.dsdb
.UF_ACCOUNTDISABLE
),
335 "showinadvancedviewonly" : "TRUE",
336 "description" : "krbtgt for %s" % ctx
.samname
}
337 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
339 # now we need to search for the samAccountName attribute on the krbtgt DN,
340 # as this will have been magically set to the krbtgt number
341 res
= ctx
.samdb
.search(base
=ctx
.krbtgt_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["samAccountName"])
342 ctx
.krbtgt_name
= res
[0]["samAccountName"][0]
344 print "Got krbtgt_name=%s" % ctx
.krbtgt_name
347 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
348 m
["msDS-krbTgtLink"] = ldb
.MessageElement(ctx
.krbtgt_dn
,
349 ldb
.FLAG_MOD_REPLACE
, "msDS-krbTgtLink")
352 ctx
.new_krbtgt_dn
= "CN=%s,CN=Users,%s" % (ctx
.krbtgt_name
, ctx
.base_dn
)
353 print "Renaming %s to %s" % (ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
354 ctx
.samdb
.rename(ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
356 def drsuapi_connect(ctx
):
357 '''make a DRSUAPI connection to the naming master'''
358 binding_options
= "seal"
359 if int(ctx
.lp
.get("log level")) >= 4:
360 binding_options
+= ",print"
361 binding_string
= "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
)
362 ctx
.drsuapi
= drsuapi
.drsuapi(binding_string
, ctx
.lp
, ctx
.creds
)
363 (ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drs_DsBind(ctx
.drsuapi
)
365 def create_tmp_samdb(ctx
):
366 '''create a temporary samdb object for schema queries'''
367 ctx
.tmp_schema
= Schema(security
.dom_sid(ctx
.domsid
),
368 schemadn
=ctx
.schema_dn
)
369 ctx
.tmp_samdb
= SamDB(session_info
=system_session(), url
=None, auto_connect
=False,
370 credentials
=ctx
.creds
, lp
=ctx
.lp
, global_schema
=False,
372 ctx
.tmp_samdb
.set_schema(ctx
.tmp_schema
)
374 def build_DsReplicaAttribute(ctx
, attrname
, attrvalue
):
375 '''build a DsReplicaAttributeCtr object'''
376 r
= drsuapi
.DsReplicaAttribute()
377 r
.attid
= ctx
.tmp_samdb
.get_attid_from_lDAPDisplayName(attrname
)
381 def DsAddEntry(ctx
, recs
):
382 '''add a record via the DRSUAPI DsAddEntry call'''
383 if ctx
.drsuapi
is None:
384 ctx
.drsuapi_connect()
385 if ctx
.tmp_samdb
is None:
386 ctx
.create_tmp_samdb()
390 id = drsuapi
.DsReplicaObjectIdentifier()
397 if not isinstance(rec
[a
], list):
401 rattr
= ctx
.tmp_samdb
.dsdb_DsReplicaAttribute(ctx
.tmp_samdb
, a
, v
)
404 attribute_ctr
= drsuapi
.DsReplicaAttributeCtr()
405 attribute_ctr
.num_attributes
= len(attrs
)
406 attribute_ctr
.attributes
= attrs
408 object = drsuapi
.DsReplicaObject()
409 object.identifier
= id
410 object.attribute_ctr
= attribute_ctr
412 list_object
= drsuapi
.DsReplicaObjectListItem()
413 list_object
.object = object
414 objects
.append(list_object
)
416 req2
= drsuapi
.DsAddEntryRequest2()
417 req2
.first_object
= objects
[0]
418 prev
= req2
.first_object
419 for o
in objects
[1:]:
423 (level
, ctr
) = ctx
.drsuapi
.DsAddEntry(ctx
.drsuapi_handle
, 2, req2
)
425 if ctr
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
426 print("DsAddEntry failed with dir_err %u" % ctr
.dir_err
)
427 raise RuntimeError("DsAddEntry failed")
428 if ctr
.extended_err
!= (0, 'WERR_OK'):
429 print("DsAddEntry failed with status %s info %s" % (ctr
.extended_err
))
430 raise RuntimeError("DsAddEntry failed")
433 raise RuntimeError("expected err_ver 1, got %u" % ctr
.err_ver
)
434 if ctr
.err_data
.status
!= (0, 'WERR_OK'):
435 print("DsAddEntry failed with status %s info %s" % (ctr
.err_data
.status
,
436 ctr
.err_data
.info
.extended_err
))
437 raise RuntimeError("DsAddEntry failed")
438 if ctr
.err_data
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
439 print("DsAddEntry failed with dir_err %u" % ctr
.err_data
.dir_err
)
440 raise RuntimeError("DsAddEntry failed")
444 def join_add_ntdsdsa(ctx
):
445 '''add the ntdsdsa object'''
447 print "Adding %s" % ctx
.ntds_dn
450 "objectclass" : "nTDSDSA",
451 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
452 "dMDLocation" : ctx
.schema_dn
}
454 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
456 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
457 rec
["msDS-Behavior-Version"] = str(samba
.dsdb
.DS_DOMAIN_FUNCTION_2008_R2
)
459 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
460 rec
["msDS-HasDomainNCs"] = ctx
.base_dn
463 rec
["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx
.schema_dn
464 rec
["msDS-HasFullReplicaNCs"] = ctx
.nc_list
465 rec
["options"] = "37"
466 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
468 rec
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
469 rec
["HasMasterNCs"] = nc_list
470 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
471 rec
["msDS-HasMasterNCs"] = ctx
.nc_list
473 rec
["invocationId"] = ndr_pack(ctx
.invocation_id
)
474 ctx
.DsAddEntry([rec
])
476 # find the GUID of our NTDS DN
477 res
= ctx
.samdb
.search(base
=ctx
.ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["objectGUID"])
478 ctx
.ntds_guid
= misc
.GUID(ctx
.samdb
.schema_format_value("objectGUID", res
[0]["objectGUID"][0]))
480 def join_add_objects(ctx
):
481 '''add the various objects needed for the join'''
483 print "Adding %s" % ctx
.acct_dn
486 "objectClass": "computer",
487 "displayname": ctx
.samname
,
488 "samaccountname" : ctx
.samname
,
489 "userAccountControl" : str(ctx
.userAccountControl | samba
.dsdb
.UF_ACCOUNTDISABLE
),
490 "dnshostname" : ctx
.dnshostname
}
491 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2008
:
492 rec
['msDS-SupportedEncryptionTypes'] = str(samba
.dsdb
.ENC_ALL_TYPES
)
493 elif ctx
.promote_existing
:
494 rec
['msDS-SupportedEncryptionTypes'] = []
496 rec
["managedby"] = ctx
.managedby
497 elif ctx
.promote_existing
:
498 rec
["managedby"] = []
500 if ctx
.never_reveal_sid
:
501 rec
["msDS-NeverRevealGroup"] = ctx
.never_reveal_sid
502 elif ctx
.promote_existing
:
503 rec
["msDS-NeverRevealGroup"] = []
506 rec
["msDS-RevealOnDemandGroup"] = ctx
.reveal_sid
507 elif ctx
.promote_existing
:
508 rec
["msDS-RevealOnDemandGroup"] = []
510 if ctx
.promote_existing
:
511 if ctx
.promote_from_dn
!= ctx
.acct_dn
:
512 ctx
.samdb
.rename(ctx
.promote_from_dn
, ctx
.acct_dn
)
513 ctx
.samdb
.modify(ldb
.Message
.from_dict(ctx
.samdb
, rec
, ldb
.FLAG_MOD_REPLACE
))
518 ctx
.add_krbtgt_account()
520 print "Adding %s" % ctx
.server_dn
523 "objectclass" : "server",
524 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
525 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
526 samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
527 samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
528 # windows seems to add the dnsHostName later
529 "dnsHostName" : ctx
.dnshostname
}
532 rec
["serverReference"] = ctx
.acct_dn
537 # the rest is done after replication
541 ctx
.join_add_ntdsdsa()
543 if ctx
.connection_dn
is not None:
544 print "Adding %s" % ctx
.connection_dn
546 "dn" : ctx
.connection_dn
,
547 "objectclass" : "nTDSConnection",
548 "enabledconnection" : "TRUE",
550 "fromServer" : ctx
.dc_ntds_dn
}
554 print "Adding SPNs to %s" % ctx
.acct_dn
556 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
557 for i
in range(len(ctx
.SPNs
)):
558 ctx
.SPNs
[i
] = ctx
.SPNs
[i
].replace("$NTDSGUID", str(ctx
.ntds_guid
))
559 m
["servicePrincipalName"] = ldb
.MessageElement(ctx
.SPNs
,
560 ldb
.FLAG_MOD_REPLACE
,
561 "servicePrincipalName")
564 # The account password set operation should normally be done over
565 # LDAP. Windows 2000 DCs however allow this only with SSL
566 # connections which are hard to set up and otherwise refuse with
567 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
569 print "Setting account password for %s" % ctx
.samname
571 ctx
.samdb
.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
572 % ldb
.binary_encode(ctx
.samname
),
574 force_change_at_next_login
=False,
575 username
=ctx
.samname
)
576 except ldb
.LdbError
, (num
, _
):
577 if num
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
579 ctx
.net
.set_password(account_name
=ctx
.samname
,
580 domain_name
=ctx
.domain_name
,
581 newpassword
=ctx
.acct_pass
)
583 res
= ctx
.samdb
.search(base
=ctx
.acct_dn
, scope
=ldb
.SCOPE_BASE
,
584 attrs
=["msDS-KeyVersionNumber"])
585 if "msDS-KeyVersionNumber" in res
[0]:
586 ctx
.key_version_number
= int(res
[0]["msDS-KeyVersionNumber"][0])
588 ctx
.key_version_number
= None
590 print("Enabling account")
592 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
593 m
["userAccountControl"] = ldb
.MessageElement(str(ctx
.userAccountControl
),
594 ldb
.FLAG_MOD_REPLACE
,
595 "userAccountControl")
598 if ctx
.dns_backend
.startswith("BIND9_"):
599 ctx
.dnspass
= samba
.generate_random_password(128, 255)
601 recs
= ctx
.samdb
.parse_ldif(read_and_sub_file(setup_path("provision_dns_add_samba.ldif"),
602 {"DNSDOMAIN": ctx
.dnsdomain
,
603 "DOMAINDN": ctx
.base_dn
,
604 "HOSTNAME" : ctx
.myname
,
605 "DNSPASS_B64": b64encode(ctx
.dnspass
),
606 "DNSNAME" : ctx
.dnshostname
}))
607 for changetype
, msg
in recs
:
608 assert changetype
== ldb
.CHANGETYPE_NONE
609 dns_acct_dn
= msg
["dn"]
610 print "Adding DNS account %s with dns/ SPN" % msg
["dn"]
612 # Remove dns password (we will set it as a modify, as we can't do clearTextPassword over LDAP)
613 del msg
["clearTextPassword"]
614 # Remove isCriticalSystemObject for similar reasons, it cannot be set over LDAP
615 del msg
["isCriticalSystemObject"]
616 # Disable account until password is set
617 msg
["userAccountControl"] = str(samba
.dsdb
.UF_NORMAL_ACCOUNT |
618 samba
.dsdb
.UF_ACCOUNTDISABLE
)
621 except ldb
.LdbError
, (num
, _
):
622 if num
!= ldb
.ERR_ENTRY_ALREADY_EXISTS
:
625 # The account password set operation should normally be done over
626 # LDAP. Windows 2000 DCs however allow this only with SSL
627 # connections which are hard to set up and otherwise refuse with
628 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
630 print "Setting account password for dns-%s" % ctx
.myname
632 ctx
.samdb
.setpassword("(&(objectClass=user)(samAccountName=dns-%s))"
633 % ldb
.binary_encode(ctx
.myname
),
635 force_change_at_next_login
=False,
636 username
=ctx
.samname
)
637 except ldb
.LdbError
, (num
, _
):
638 if num
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
640 ctx
.net
.set_password(account_name
="dns-%s" % ctx
.myname
,
641 domain_name
=ctx
.domain_name
,
642 newpassword
=ctx
.dnspass
)
644 res
= ctx
.samdb
.search(base
=dns_acct_dn
, scope
=ldb
.SCOPE_BASE
,
645 attrs
=["msDS-KeyVersionNumber"])
646 if "msDS-KeyVersionNumber" in res
[0]:
647 ctx
.dns_key_version_number
= int(res
[0]["msDS-KeyVersionNumber"][0])
649 ctx
.dns_key_version_number
= None
651 def join_add_objects2(ctx
):
652 """add the various objects needed for the join, for subdomains post replication"""
654 print "Adding %s" % ctx
.partition_dn
655 # NOTE: windows sends a ntSecurityDescriptor here, we
658 "dn" : ctx
.partition_dn
,
659 "objectclass" : "crossRef",
660 "objectCategory" : "CN=Cross-Ref,%s" % ctx
.schema_dn
,
661 "nCName" : ctx
.base_dn
,
662 "nETBIOSName" : ctx
.domain_name
,
663 "dnsRoot": ctx
.dnsdomain
,
664 "trustParent" : ctx
.parent_partition_dn
,
665 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_NC|samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
)}
666 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
667 rec
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
671 "objectclass" : "nTDSDSA",
672 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
673 "dMDLocation" : ctx
.schema_dn
}
675 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
677 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
678 rec2
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
680 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
681 rec2
["msDS-HasDomainNCs"] = ctx
.base_dn
683 rec2
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
684 rec2
["HasMasterNCs"] = nc_list
685 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
686 rec2
["msDS-HasMasterNCs"] = ctx
.nc_list
687 rec2
["options"] = "1"
688 rec2
["invocationId"] = ndr_pack(ctx
.invocation_id
)
690 objects
= ctx
.DsAddEntry([rec
, rec2
])
691 if len(objects
) != 2:
692 raise DCJoinException("Expected 2 objects from DsAddEntry")
694 ctx
.ntds_guid
= objects
[1].guid
696 print("Replicating partition DN")
697 ctx
.repl
.replicate(ctx
.partition_dn
,
698 misc
.GUID("00000000-0000-0000-0000-000000000000"),
700 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
701 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
703 print("Replicating NTDS DN")
704 ctx
.repl
.replicate(ctx
.ntds_dn
,
705 misc
.GUID("00000000-0000-0000-0000-000000000000"),
707 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
708 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
710 def join_provision(ctx
):
711 """Provision the local SAM."""
713 print "Calling bare provision"
715 logger
= logging
.getLogger("provision")
716 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
717 smbconf
= ctx
.lp
.configfile
719 presult
= provision(logger
, system_session(), None, smbconf
=smbconf
,
720 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_DRS
, realm
=ctx
.realm
,
721 rootdn
=ctx
.root_dn
, domaindn
=ctx
.base_dn
,
722 schemadn
=ctx
.schema_dn
, configdn
=ctx
.config_dn
,
723 serverdn
=ctx
.server_dn
, domain
=ctx
.domain_name
,
724 hostname
=ctx
.myname
, domainsid
=ctx
.domsid
,
725 machinepass
=ctx
.acct_pass
, serverrole
="domain controller",
726 sitename
=ctx
.site
, lp
=ctx
.lp
, ntdsguid
=ctx
.ntds_guid
,
727 use_ntvfs
=ctx
.use_ntvfs
, dns_backend
=ctx
.dns_backend
)
728 print "Provision OK for domain DN %s" % presult
.domaindn
729 ctx
.local_samdb
= presult
.samdb
731 ctx
.paths
= presult
.paths
732 ctx
.names
= presult
.names
734 def join_provision_own_domain(ctx
):
735 """Provision the local SAM."""
737 # we now operate exclusively on the local database, which
738 # we need to reopen in order to get the newly created schema
739 print("Reconnecting to local samdb")
740 ctx
.samdb
= SamDB(url
=ctx
.local_samdb
.url
,
741 session_info
=system_session(),
742 lp
=ctx
.local_samdb
.lp
,
744 ctx
.samdb
.set_invocation_id(str(ctx
.invocation_id
))
745 ctx
.local_samdb
= ctx
.samdb
747 print("Finding domain GUID from ncName")
748 res
= ctx
.local_samdb
.search(base
=ctx
.partition_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['ncName'],
749 controls
=["extended_dn:1:1"])
750 domguid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['ncName'][0]).get_extended_component('GUID')))
751 print("Got domain GUID %s" % domguid
)
753 print("Calling own domain provision")
755 logger
= logging
.getLogger("provision")
756 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
758 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
760 presult
= provision_fill(ctx
.local_samdb
, secrets_ldb
,
761 logger
, ctx
.names
, ctx
.paths
, domainsid
=security
.dom_sid(ctx
.domsid
),
763 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_SUBDOMAIN
,
764 machinepass
=ctx
.acct_pass
, serverrole
="domain controller",
765 lp
=ctx
.lp
, hostip
=ctx
.names
.hostip
, hostip6
=ctx
.names
.hostip6
,
766 dns_backend
=ctx
.dns_backend
)
767 print("Provision OK for domain %s" % ctx
.names
.dnsdomain
)
769 def join_replicate(ctx
):
770 """Replicate the SAM."""
772 print "Starting replication"
773 ctx
.local_samdb
.transaction_start()
775 source_dsa_invocation_id
= misc
.GUID(ctx
.samdb
.get_invocation_id())
776 if ctx
.ntds_guid
is None:
777 print("Using DS_BIND_GUID_W2K3")
778 destination_dsa_guid
= misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID_W2K3
)
780 destination_dsa_guid
= ctx
.ntds_guid
783 repl_creds
= Credentials()
784 repl_creds
.guess(ctx
.lp
)
785 repl_creds
.set_kerberos_state(DONT_USE_KERBEROS
)
786 repl_creds
.set_username(ctx
.samname
)
787 repl_creds
.set_password(ctx
.acct_pass
)
789 repl_creds
= ctx
.creds
791 binding_options
= "seal"
792 if int(ctx
.lp
.get("log level")) >= 5:
793 binding_options
+= ",print"
794 repl
= drs_utils
.drs_Replicate(
795 "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
796 ctx
.lp
, repl_creds
, ctx
.local_samdb
, ctx
.invocation_id
)
798 repl
.replicate(ctx
.schema_dn
, source_dsa_invocation_id
,
799 destination_dsa_guid
, schema
=True, rodc
=ctx
.RODC
,
800 replica_flags
=ctx
.replica_flags
)
801 repl
.replicate(ctx
.config_dn
, source_dsa_invocation_id
,
802 destination_dsa_guid
, rodc
=ctx
.RODC
,
803 replica_flags
=ctx
.replica_flags
)
804 if not ctx
.subdomain
:
805 # Replicate first the critical object for the basedn
806 if not ctx
.domain_replica_flags
& drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
:
807 print "Replicating critical objects from the base DN of the domain"
808 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi
.DRSUAPI_DRS_GET_ANC
809 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
810 destination_dsa_guid
, rodc
=ctx
.RODC
,
811 replica_flags
=ctx
.domain_replica_flags
)
812 ctx
.domain_replica_flags ^
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi
.DRSUAPI_DRS_GET_ANC
814 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_GET_ANC
815 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
816 destination_dsa_guid
, rodc
=ctx
.RODC
,
817 replica_flags
=ctx
.domain_replica_flags
)
818 print "Done with always replicated NC (base, config, schema)"
820 for nc
in (ctx
.domaindns_zone
, ctx
.forestdns_zone
):
821 if nc
in ctx
.nc_list
:
822 print "Replicating %s" % (str(nc
))
823 repl
.replicate(nc
, source_dsa_invocation_id
,
824 destination_dsa_guid
, rodc
=ctx
.RODC
,
825 replica_flags
=ctx
.replica_flags
)
827 if 'DC=ForestDnsZones,%s' % ctx
.root_dn
in ctx
.nc_list
:
828 repl
.replicate('DC=ForestDnsZones,%s' % ctx
.root_dn
, source_dsa_invocation_id
,
829 destination_dsa_guid
, rodc
=ctx
.RODC
,
830 replica_flags
=ctx
.replica_flags
)
831 # FIXME At this point we should add an entry in the forestdns and domaindns NC
832 # (those under CN=Partions,DC=...)
833 # in order to indicate that we hold a replica for this NC
836 repl
.replicate(ctx
.acct_dn
, source_dsa_invocation_id
,
837 destination_dsa_guid
,
838 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
839 repl
.replicate(ctx
.new_krbtgt_dn
, source_dsa_invocation_id
,
840 destination_dsa_guid
,
841 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
843 ctx
.source_dsa_invocation_id
= source_dsa_invocation_id
844 ctx
.destination_dsa_guid
= destination_dsa_guid
846 print "Committing SAM database"
848 ctx
.local_samdb
.transaction_cancel()
851 ctx
.local_samdb
.transaction_commit()
853 def send_DsReplicaUpdateRefs(ctx
, dn
):
854 r
= drsuapi
.DsReplicaUpdateRefsRequest1()
855 r
.naming_context
= drsuapi
.DsReplicaObjectIdentifier()
856 r
.naming_context
.dn
= str(dn
)
857 r
.naming_context
.guid
= misc
.GUID("00000000-0000-0000-0000-000000000000")
858 r
.naming_context
.sid
= security
.dom_sid("S-0-0")
859 r
.dest_dsa_guid
= ctx
.ntds_guid
860 r
.dest_dsa_dns_name
= "%s._msdcs.%s" % (str(ctx
.ntds_guid
), ctx
.dnsforest
)
861 r
.options
= drsuapi
.DRSUAPI_DRS_ADD_REF | drsuapi
.DRSUAPI_DRS_DEL_REF
863 r
.options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
866 ctx
.drsuapi
.DsReplicaUpdateRefs(ctx
.drsuapi_handle
, 1, r
)
868 def join_finalise(ctx
):
869 """Finalise the join, mark us synchronised and setup secrets db."""
871 logger
= logging
.getLogger("provision")
872 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
874 # FIXME we shouldn't do this in all cases
875 # If for some reasons we joined in another site than the one of
876 # DC we just replicated from then we don't need to send the updatereplicateref
877 # as replication between sites is time based and on the initiative of the
879 print "Sending DsReplicateUpdateRefs for all the replicated partitions"
880 for nc
in ctx
.full_nc_list
:
881 ctx
.send_DsReplicaUpdateRefs(nc
)
884 print "Setting RODC invocationId"
885 ctx
.local_samdb
.set_invocation_id(str(ctx
.invocation_id
))
886 ctx
.local_samdb
.set_opaque_integer("domainFunctionality",
887 ctx
.behavior_version
)
889 m
.dn
= ldb
.Dn(ctx
.local_samdb
, "%s" % ctx
.ntds_dn
)
890 m
["invocationId"] = ldb
.MessageElement(ndr_pack(ctx
.invocation_id
),
891 ldb
.FLAG_MOD_REPLACE
,
893 ctx
.local_samdb
.modify(m
)
895 # Note: as RODC the invocationId is only stored
896 # on the RODC itself, the other DCs never see it.
898 # Thats is why we fix up the replPropertyMetaData stamp
899 # for the 'invocationId' attribute, we need to change
900 # the 'version' to '0', this is what windows 2008r2 does as RODC
902 # This means if the object on a RWDC ever gets a invocationId
903 # attribute, it will have version '1' (or higher), which will
904 # will overwrite the RODC local value.
905 ctx
.local_samdb
.set_attribute_replmetadata_version(m
.dn
,
909 print "Setting isSynchronized and dsServiceName"
911 m
.dn
= ldb
.Dn(ctx
.local_samdb
, '@ROOTDSE')
912 m
["isSynchronized"] = ldb
.MessageElement("TRUE", ldb
.FLAG_MOD_REPLACE
, "isSynchronized")
913 m
["dsServiceName"] = ldb
.MessageElement("<GUID=%s>" % str(ctx
.ntds_guid
),
914 ldb
.FLAG_MOD_REPLACE
, "dsServiceName")
915 ctx
.local_samdb
.modify(m
)
920 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
922 print "Setting up secrets database"
923 secretsdb_self_join(secrets_ldb
, domain
=ctx
.domain_name
,
925 dnsdomain
=ctx
.dnsdomain
,
926 netbiosname
=ctx
.myname
,
927 domainsid
=security
.dom_sid(ctx
.domsid
),
928 machinepass
=ctx
.acct_pass
,
929 secure_channel_type
=ctx
.secure_channel_type
,
930 key_version_number
=ctx
.key_version_number
)
932 if ctx
.dns_backend
.startswith("BIND9_"):
933 setup_bind9_dns(ctx
.local_samdb
, secrets_ldb
, security
.dom_sid(ctx
.domsid
),
934 ctx
.names
, ctx
.paths
, ctx
.lp
, logger
,
935 dns_backend
=ctx
.dns_backend
,
936 dnspass
=ctx
.dnspass
, os_level
=ctx
.behavior_version
,
937 targetdir
=ctx
.targetdir
,
938 key_version_number
=ctx
.dns_key_version_number
)
940 def join_setup_trusts(ctx
):
941 """provision the local SAM."""
943 def arcfour_encrypt(key
, data
):
944 from Crypto
.Cipher
import ARC4
946 return c
.encrypt(data
)
948 def string_to_array(string
):
949 blob
= [0] * len(string
)
951 for i
in range(len(string
)):
952 blob
[i
] = ord(string
[i
])
956 print "Setup domain trusts with server %s" % ctx
.server
957 binding_options
= "" # why doesn't signing work here? w2k8r2 claims no session key
958 lsaconn
= lsa
.lsarpc("ncacn_np:%s[%s]" % (ctx
.server
, binding_options
),
961 objectAttr
= lsa
.ObjectAttribute()
962 objectAttr
.sec_qos
= lsa
.QosInfo()
964 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
965 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
967 info
= lsa
.TrustDomainInfoInfoEx()
968 info
.domain_name
.string
= ctx
.dnsdomain
969 info
.netbios_name
.string
= ctx
.domain_name
970 info
.sid
= security
.dom_sid(ctx
.domsid
)
971 info
.trust_direction
= lsa
.LSA_TRUST_DIRECTION_INBOUND | lsa
.LSA_TRUST_DIRECTION_OUTBOUND
972 info
.trust_type
= lsa
.LSA_TRUST_TYPE_UPLEVEL
973 info
.trust_attributes
= lsa
.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
976 oldname
= lsa
.String()
977 oldname
.string
= ctx
.dnsdomain
978 oldinfo
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, oldname
,
979 lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
980 print("Removing old trust record for %s (SID %s)" % (ctx
.dnsdomain
, oldinfo
.info_ex
.sid
))
981 lsaconn
.DeleteTrustedDomain(pol_handle
, oldinfo
.info_ex
.sid
)
985 password_blob
= string_to_array(ctx
.trustdom_pass
.encode('utf-16-le'))
987 clear_value
= drsblobs
.AuthInfoClear()
988 clear_value
.size
= len(password_blob
)
989 clear_value
.password
= password_blob
991 clear_authentication_information
= drsblobs
.AuthenticationInformation()
992 clear_authentication_information
.LastUpdateTime
= samba
.unix2nttime(int(time
.time()))
993 clear_authentication_information
.AuthType
= lsa
.TRUST_AUTH_TYPE_CLEAR
994 clear_authentication_information
.AuthInfo
= clear_value
996 authentication_information_array
= drsblobs
.AuthenticationInformationArray()
997 authentication_information_array
.count
= 1
998 authentication_information_array
.array
= [clear_authentication_information
]
1000 outgoing
= drsblobs
.trustAuthInOutBlob()
1002 outgoing
.current
= authentication_information_array
1004 trustpass
= drsblobs
.trustDomainPasswords()
1005 confounder
= [3] * 512
1007 for i
in range(512):
1008 confounder
[i
] = random
.randint(0, 255)
1010 trustpass
.confounder
= confounder
1012 trustpass
.outgoing
= outgoing
1013 trustpass
.incoming
= outgoing
1015 trustpass_blob
= ndr_pack(trustpass
)
1017 encrypted_trustpass
= arcfour_encrypt(lsaconn
.session_key
, trustpass_blob
)
1019 auth_blob
= lsa
.DATA_BUF2()
1020 auth_blob
.size
= len(encrypted_trustpass
)
1021 auth_blob
.data
= string_to_array(encrypted_trustpass
)
1023 auth_info
= lsa
.TrustDomainInfoAuthInfoInternal()
1024 auth_info
.auth_blob
= auth_blob
1026 trustdom_handle
= lsaconn
.CreateTrustedDomainEx2(pol_handle
,
1029 security
.SEC_STD_DELETE
)
1032 "dn" : "cn=%s,cn=system,%s" % (ctx
.dnsforest
, ctx
.base_dn
),
1033 "objectclass" : "trustedDomain",
1034 "trustType" : str(info
.trust_type
),
1035 "trustAttributes" : str(info
.trust_attributes
),
1036 "trustDirection" : str(info
.trust_direction
),
1037 "flatname" : ctx
.forest_domain_name
,
1038 "trustPartner" : ctx
.dnsforest
,
1039 "trustAuthIncoming" : ndr_pack(outgoing
),
1040 "trustAuthOutgoing" : ndr_pack(outgoing
)
1042 ctx
.local_samdb
.add(rec
)
1045 "dn" : "cn=%s$,cn=users,%s" % (ctx
.forest_domain_name
, ctx
.base_dn
),
1046 "objectclass" : "user",
1047 "userAccountControl" : str(samba
.dsdb
.UF_INTERDOMAIN_TRUST_ACCOUNT
),
1048 "clearTextPassword" : ctx
.trustdom_pass
.encode('utf-16-le')
1050 ctx
.local_samdb
.add(rec
)
1054 # full_nc_list is the list of naming context (NC) for which we will
1055 # send a updateRef command to the partner DC
1056 ctx
.nc_list
= [ ctx
.config_dn
, ctx
.schema_dn
]
1057 ctx
.full_nc_list
= [ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
1059 if not ctx
.subdomain
:
1060 ctx
.nc_list
+= [ctx
.base_dn
]
1061 if ctx
.dns_backend
!= "NONE":
1062 ctx
.nc_list
+= [ctx
.domaindns_zone
]
1064 if ctx
.dns_backend
!= "NONE":
1065 ctx
.full_nc_list
+= ['DC=DomainDnsZones,%s' % ctx
.base_dn
]
1066 ctx
.full_nc_list
+= ['DC=ForestDnsZones,%s' % ctx
.root_dn
]
1067 ctx
.nc_list
+= ['DC=ForestDnsZones,%s' % ctx
.root_dn
]
1069 if ctx
.promote_existing
:
1070 ctx
.promote_possible()
1072 ctx
.cleanup_old_join()
1075 ctx
.join_add_objects()
1076 ctx
.join_provision()
1077 ctx
.join_replicate()
1079 ctx
.join_add_objects2()
1080 ctx
.join_provision_own_domain()
1081 ctx
.join_setup_trusts()
1084 print "Join failed - cleaning up"
1085 ctx
.cleanup_old_join()
1089 def join_RODC(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
1090 targetdir
=None, domain
=None, domain_critical_only
=False,
1091 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
1092 promote_existing
=False):
1093 """Join as a RODC."""
1095 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
,
1096 machinepass
, use_ntvfs
, dns_backend
, promote_existing
)
1098 lp
.set("workgroup", ctx
.domain_name
)
1099 print("workgroup is %s" % ctx
.domain_name
)
1101 lp
.set("realm", ctx
.realm
)
1102 print("realm is %s" % ctx
.realm
)
1104 ctx
.krbtgt_dn
= "CN=krbtgt_%s,CN=Users,%s" % (ctx
.myname
, ctx
.base_dn
)
1106 # setup some defaults for accounts that should be replicated to this RODC
1107 ctx
.never_reveal_sid
= [
1108 "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_DENY
),
1109 "<SID=%s>" % security
.SID_BUILTIN_ADMINISTRATORS
,
1110 "<SID=%s>" % security
.SID_BUILTIN_SERVER_OPERATORS
,
1111 "<SID=%s>" % security
.SID_BUILTIN_BACKUP_OPERATORS
,
1112 "<SID=%s>" % security
.SID_BUILTIN_ACCOUNT_OPERATORS
]
1113 ctx
.reveal_sid
= "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_ALLOW
)
1115 mysid
= ctx
.get_mysid()
1116 admin_dn
= "<SID=%s>" % mysid
1117 ctx
.managedby
= admin_dn
1119 ctx
.userAccountControl
= (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
1120 samba
.dsdb
.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1121 samba
.dsdb
.UF_PARTIAL_SECRETS_ACCOUNT
)
1123 ctx
.SPNs
.extend([ "RestrictedKrbHost/%s" % ctx
.myname
,
1124 "RestrictedKrbHost/%s" % ctx
.dnshostname
])
1126 ctx
.connection_dn
= "CN=RODC Connection (FRS),%s" % ctx
.ntds_dn
1127 ctx
.secure_channel_type
= misc
.SEC_CHAN_RODC
1129 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1130 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1131 drsuapi
.DRSUAPI_DRS_GET_ANC |
1132 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED |
1133 drsuapi
.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1134 drsuapi
.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP
)
1135 ctx
.domain_replica_flags
= ctx
.replica_flags
1136 if domain_critical_only
:
1137 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
1141 print "Joined domain %s (SID %s) as an RODC" % (ctx
.domain_name
, ctx
.domsid
)
1144 def join_DC(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
1145 targetdir
=None, domain
=None, domain_critical_only
=False,
1146 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
1147 promote_existing
=False):
1149 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
,
1150 machinepass
, use_ntvfs
, dns_backend
, promote_existing
)
1152 lp
.set("workgroup", ctx
.domain_name
)
1153 print("workgroup is %s" % ctx
.domain_name
)
1155 lp
.set("realm", ctx
.realm
)
1156 print("realm is %s" % ctx
.realm
)
1158 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
1160 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
1161 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
1163 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
1164 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1165 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1166 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1167 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
1168 ctx
.domain_replica_flags
= ctx
.replica_flags
1169 if domain_critical_only
:
1170 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
1173 print "Joined domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
)
1175 def join_subdomain(server
=None, creds
=None, lp
=None, site
=None,
1176 netbios_name
=None, targetdir
=None, parent_domain
=None, dnsdomain
=None,
1177 netbios_domain
=None, machinepass
=None, use_ntvfs
=False,
1180 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, parent_domain
,
1181 machinepass
, use_ntvfs
, dns_backend
)
1182 ctx
.subdomain
= True
1183 ctx
.parent_domain_name
= ctx
.domain_name
1184 ctx
.domain_name
= netbios_domain
1185 ctx
.realm
= dnsdomain
1186 ctx
.parent_dnsdomain
= ctx
.dnsdomain
1187 ctx
.parent_partition_dn
= ctx
.get_parent_partition_dn()
1188 ctx
.dnsdomain
= dnsdomain
1189 ctx
.partition_dn
= "CN=%s,CN=Partitions,%s" % (ctx
.domain_name
, ctx
.config_dn
)
1190 ctx
.naming_master
= ctx
.get_naming_master()
1191 if ctx
.naming_master
!= ctx
.server
:
1192 print("Reconnecting to naming master %s" % ctx
.naming_master
)
1193 ctx
.server
= ctx
.naming_master
1194 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
1195 session_info
=system_session(),
1196 credentials
=ctx
.creds
, lp
=ctx
.lp
)
1198 ctx
.base_dn
= samba
.dn_from_dns_name(dnsdomain
)
1199 ctx
.domsid
= str(security
.random_sid())
1201 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
, ctx
.dnsdomain
)
1202 ctx
.trustdom_pass
= samba
.generate_random_password(128, 128)
1204 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
1206 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
1207 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
1209 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
1210 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1211 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1212 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1213 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
1214 ctx
.domain_replica_flags
= ctx
.replica_flags
1217 print "Created domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
)