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
.schema
import Schema
30 from samba
.net
import Net
31 from samba
.provision
.sambadns
import setup_bind9_dns
37 # this makes debugging easier
38 talloc
.enable_null_tracking()
40 class DCJoinException(Exception):
42 def __init__(self
, msg
):
43 super(DCJoinException
, self
).__init
__("Can't join, error: %s" % msg
)
46 class dc_join(object):
47 """Perform a DC join."""
49 def __init__(ctx
, server
=None, creds
=None, lp
=None, site
=None,
50 netbios_name
=None, targetdir
=None, domain
=None,
51 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
52 promote_existing
=False):
56 ctx
.netbios_name
= netbios_name
57 ctx
.targetdir
= targetdir
58 ctx
.use_ntvfs
= use_ntvfs
60 ctx
.promote_existing
= promote_existing
61 ctx
.promote_from_dn
= None
66 ctx
.creds
.set_gensec_features(creds
.get_gensec_features() | gensec
.FEATURE_SEAL
)
67 ctx
.net
= Net(creds
=ctx
.creds
, lp
=ctx
.lp
)
69 if server
is not None:
72 print("Finding a writeable DC for domain '%s'" % domain
)
73 ctx
.server
= ctx
.find_dc(domain
)
74 print("Found DC %s" % ctx
.server
)
76 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
77 session_info
=system_session(),
78 credentials
=ctx
.creds
, lp
=ctx
.lp
)
81 ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
82 except ldb
.LdbError
, (enum
, estr
):
83 raise DCJoinException(estr
)
86 ctx
.myname
= netbios_name
87 ctx
.samname
= "%s$" % ctx
.myname
88 ctx
.base_dn
= str(ctx
.samdb
.get_default_basedn())
89 ctx
.root_dn
= str(ctx
.samdb
.get_root_basedn())
90 ctx
.schema_dn
= str(ctx
.samdb
.get_schema_basedn())
91 ctx
.config_dn
= str(ctx
.samdb
.get_config_basedn())
92 ctx
.domsid
= ctx
.samdb
.get_domain_sid()
93 ctx
.domain_name
= ctx
.get_domain_name()
94 ctx
.forest_domain_name
= ctx
.get_forest_domain_name()
95 ctx
.invocation_id
= misc
.GUID(str(uuid
.uuid4()))
97 ctx
.dc_ntds_dn
= ctx
.samdb
.get_dsServiceName()
98 ctx
.dc_dnsHostName
= ctx
.get_dnsHostName()
99 ctx
.behavior_version
= ctx
.get_behavior_version()
101 if machinepass
is not None:
102 ctx
.acct_pass
= machinepass
104 ctx
.acct_pass
= samba
.generate_random_password(32, 40)
106 # work out the DNs of all the objects we will be adding
107 ctx
.server_dn
= "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx
.myname
, ctx
.site
, ctx
.config_dn
)
108 ctx
.ntds_dn
= "CN=NTDS Settings,%s" % ctx
.server_dn
109 topology_base
= "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx
.base_dn
110 if ctx
.dn_exists(topology_base
):
111 ctx
.topology_dn
= "CN=%s,%s" % (ctx
.myname
, topology_base
)
113 ctx
.topology_dn
= None
115 ctx
.dnsdomain
= ctx
.samdb
.domain_dns_name()
116 ctx
.dnsforest
= ctx
.samdb
.forest_dns_name()
117 ctx
.domaindns_zone
= 'DC=DomainDnsZones,%s' % ctx
.base_dn
119 res_domaindns
= ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
,
121 base
=ctx
.samdb
.get_partitions_dn(),
122 expression
="(&(objectClass=crossRef)(ncName=%s))" % ctx
.domaindns_zone
)
123 if dns_backend
is None:
124 ctx
.dns_backend
= "NONE"
126 if len(res_domaindns
) == 0:
127 ctx
.dns_backend
= "NONE"
128 print "NO DNS zone information found in source domain, not replicating DNS"
130 ctx
.dns_backend
= dns_backend
132 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
, ctx
.dnsdomain
)
134 ctx
.realm
= ctx
.dnsdomain
136 ctx
.acct_dn
= "CN=%s,OU=Domain Controllers,%s" % (ctx
.myname
, ctx
.base_dn
)
140 ctx
.SPNs
= [ "HOST/%s" % ctx
.myname
,
141 "HOST/%s" % ctx
.dnshostname
,
142 "GC/%s/%s" % (ctx
.dnshostname
, ctx
.dnsforest
) ]
144 # these elements are optional
145 ctx
.never_reveal_sid
= None
146 ctx
.reveal_sid
= None
147 ctx
.connection_dn
= None
152 ctx
.subdomain
= False
154 def del_noerror(ctx
, dn
, recursive
=False):
157 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
161 ctx
.del_noerror(r
.dn
, recursive
=True)
164 print "Deleted %s" % dn
168 def cleanup_old_join(ctx
):
169 """Remove any DNs from a previous join."""
171 # find the krbtgt link
172 print("checking sAMAccountName")
176 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
177 expression
='sAMAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
178 attrs
=["msDS-krbTgtLink"])
180 ctx
.del_noerror(res
[0].dn
, recursive
=True)
181 if ctx
.connection_dn
is not None:
182 ctx
.del_noerror(ctx
.connection_dn
)
183 if ctx
.krbtgt_dn
is not None:
184 ctx
.del_noerror(ctx
.krbtgt_dn
)
185 ctx
.del_noerror(ctx
.ntds_dn
)
186 ctx
.del_noerror(ctx
.server_dn
, recursive
=True)
188 ctx
.del_noerror(ctx
.topology_dn
)
190 ctx
.del_noerror(ctx
.partition_dn
)
192 ctx
.new_krbtgt_dn
= res
[0]["msDS-Krbtgtlink"][0]
193 ctx
.del_noerror(ctx
.new_krbtgt_dn
)
196 binding_options
= "sign"
197 lsaconn
= lsa
.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
200 objectAttr
= lsa
.ObjectAttribute()
201 objectAttr
.sec_qos
= lsa
.QosInfo()
203 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
204 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
207 name
.string
= ctx
.realm
208 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
210 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
213 name
.string
= ctx
.forest_domain_name
214 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
216 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
221 def promote_possible(ctx
):
222 """confirm that the account is just a bare NT4 BDC or a member server, so can be safely promoted"""
224 # This shouldn't happen
225 raise Exception("Can not promote into a subdomain")
227 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
228 expression
='sAMAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
229 attrs
=["msDS-krbTgtLink", "userAccountControl", "serverReferenceBL", "rIDSetReferences"])
231 raise Exception("Could not find domain member account '%s' to promote to a DC, use 'samba-tool domain join' instead'" % ctx
.samname
)
232 if "msDS-krbTgtLink" in res
[0] or "serverReferenceBL" in res
[0] or "rIDSetReferences" in res
[0]:
233 raise Exception("Account '%s' appears to be an active DC, use 'samba-tool domain join' if you must re-create this account" % ctx
.samname
)
234 if (int(res
[0]["userAccountControl"][0]) & (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT|samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT
) == 0):
235 raise Exception("Account %s is not a domain member or a bare NT4 BDC, use 'samba-tool domain join' instead'" % ctx
.samname
)
237 ctx
.promote_from_dn
= res
[0].dn
240 def find_dc(ctx
, domain
):
241 """find a writeable DC for the given domain"""
243 ctx
.cldap_ret
= ctx
.net
.finddc(domain
=domain
, flags
=nbt
.NBT_SERVER_LDAP | nbt
.NBT_SERVER_DS | nbt
.NBT_SERVER_WRITABLE
)
245 raise Exception("Failed to find a writeable DC for domain '%s'" % domain
)
246 if ctx
.cldap_ret
.client_site
is not None and ctx
.cldap_ret
.client_site
!= "":
247 ctx
.site
= ctx
.cldap_ret
.client_site
248 return ctx
.cldap_ret
.pdc_dns_name
251 def get_behavior_version(ctx
):
252 res
= ctx
.samdb
.search(base
=ctx
.base_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["msDS-Behavior-Version"])
253 if "msDS-Behavior-Version" in res
[0]:
254 return int(res
[0]["msDS-Behavior-Version"][0])
256 return samba
.dsdb
.DS_DOMAIN_FUNCTION_2000
258 def get_dnsHostName(ctx
):
259 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])
260 return res
[0]["dnsHostName"][0]
262 def get_domain_name(ctx
):
263 '''get netbios name of the domain from the partitions record'''
264 partitions_dn
= ctx
.samdb
.get_partitions_dn()
265 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
266 expression
='ncName=%s' % ctx
.samdb
.get_default_basedn())
267 return res
[0]["nETBIOSName"][0]
269 def get_forest_domain_name(ctx
):
270 '''get netbios name of the domain from the partitions record'''
271 partitions_dn
= ctx
.samdb
.get_partitions_dn()
272 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
273 expression
='ncName=%s' % ctx
.samdb
.get_root_basedn())
274 return res
[0]["nETBIOSName"][0]
276 def get_parent_partition_dn(ctx
):
277 '''get the parent domain partition DN from parent DNS name'''
278 res
= ctx
.samdb
.search(base
=ctx
.config_dn
, attrs
=[],
279 expression
='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
280 (ctx
.parent_dnsdomain
, ldb
.OID_COMPARATOR_AND
, samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
))
281 return str(res
[0].dn
)
283 def get_naming_master(ctx
):
284 '''get the parent domain partition DN from parent DNS name'''
285 res
= ctx
.samdb
.search(base
='CN=Partitions,%s' % ctx
.config_dn
, attrs
=['fSMORoleOwner'],
286 scope
=ldb
.SCOPE_BASE
, controls
=["extended_dn:1:1"])
287 if not 'fSMORoleOwner' in res
[0]:
288 raise DCJoinException("Can't find naming master on partition DN %s" % ctx
.partition_dn
)
289 master_guid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
290 master_host
= '%s._msdcs.%s' % (master_guid
, ctx
.dnsforest
)
294 '''get the SID of the connected user. Only works with w2k8 and later,
295 so only used for RODC join'''
296 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["tokenGroups"])
297 binsid
= res
[0]["tokenGroups"][0]
298 return ctx
.samdb
.schema_format_value("objectSID", binsid
)
300 def dn_exists(ctx
, dn
):
301 '''check if a DN exists'''
303 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
, attrs
=[])
304 except ldb
.LdbError
, (enum
, estr
):
305 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
310 def add_krbtgt_account(ctx
):
311 '''RODCs need a special krbtgt account'''
312 print "Adding %s" % ctx
.krbtgt_dn
314 "dn" : ctx
.krbtgt_dn
,
315 "objectclass" : "user",
316 "useraccountcontrol" : str(samba
.dsdb
.UF_NORMAL_ACCOUNT |
317 samba
.dsdb
.UF_ACCOUNTDISABLE
),
318 "showinadvancedviewonly" : "TRUE",
319 "description" : "krbtgt for %s" % ctx
.samname
}
320 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
322 # now we need to search for the samAccountName attribute on the krbtgt DN,
323 # as this will have been magically set to the krbtgt number
324 res
= ctx
.samdb
.search(base
=ctx
.krbtgt_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["samAccountName"])
325 ctx
.krbtgt_name
= res
[0]["samAccountName"][0]
327 print "Got krbtgt_name=%s" % ctx
.krbtgt_name
330 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
331 m
["msDS-krbTgtLink"] = ldb
.MessageElement(ctx
.krbtgt_dn
,
332 ldb
.FLAG_MOD_REPLACE
, "msDS-krbTgtLink")
335 ctx
.new_krbtgt_dn
= "CN=%s,CN=Users,%s" % (ctx
.krbtgt_name
, ctx
.base_dn
)
336 print "Renaming %s to %s" % (ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
337 ctx
.samdb
.rename(ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
339 def drsuapi_connect(ctx
):
340 '''make a DRSUAPI connection to the naming master'''
341 binding_options
= "seal"
342 if int(ctx
.lp
.get("log level")) >= 4:
343 binding_options
+= ",print"
344 binding_string
= "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
)
345 ctx
.drsuapi
= drsuapi
.drsuapi(binding_string
, ctx
.lp
, ctx
.creds
)
346 (ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drs_DsBind(ctx
.drsuapi
)
348 def create_tmp_samdb(ctx
):
349 '''create a temporary samdb object for schema queries'''
350 ctx
.tmp_schema
= Schema(security
.dom_sid(ctx
.domsid
),
351 schemadn
=ctx
.schema_dn
)
352 ctx
.tmp_samdb
= SamDB(session_info
=system_session(), url
=None, auto_connect
=False,
353 credentials
=ctx
.creds
, lp
=ctx
.lp
, global_schema
=False,
355 ctx
.tmp_samdb
.set_schema(ctx
.tmp_schema
)
357 def build_DsReplicaAttribute(ctx
, attrname
, attrvalue
):
358 '''build a DsReplicaAttributeCtr object'''
359 r
= drsuapi
.DsReplicaAttribute()
360 r
.attid
= ctx
.tmp_samdb
.get_attid_from_lDAPDisplayName(attrname
)
364 def DsAddEntry(ctx
, recs
):
365 '''add a record via the DRSUAPI DsAddEntry call'''
366 if ctx
.drsuapi
is None:
367 ctx
.drsuapi_connect()
368 if ctx
.tmp_samdb
is None:
369 ctx
.create_tmp_samdb()
373 id = drsuapi
.DsReplicaObjectIdentifier()
380 if not isinstance(rec
[a
], list):
384 rattr
= ctx
.tmp_samdb
.dsdb_DsReplicaAttribute(ctx
.tmp_samdb
, a
, v
)
387 attribute_ctr
= drsuapi
.DsReplicaAttributeCtr()
388 attribute_ctr
.num_attributes
= len(attrs
)
389 attribute_ctr
.attributes
= attrs
391 object = drsuapi
.DsReplicaObject()
392 object.identifier
= id
393 object.attribute_ctr
= attribute_ctr
395 list_object
= drsuapi
.DsReplicaObjectListItem()
396 list_object
.object = object
397 objects
.append(list_object
)
399 req2
= drsuapi
.DsAddEntryRequest2()
400 req2
.first_object
= objects
[0]
401 prev
= req2
.first_object
402 for o
in objects
[1:]:
406 (level
, ctr
) = ctx
.drsuapi
.DsAddEntry(ctx
.drsuapi_handle
, 2, req2
)
408 if ctr
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
409 print("DsAddEntry failed with dir_err %u" % ctr
.dir_err
)
410 raise RuntimeError("DsAddEntry failed")
411 if ctr
.extended_err
!= (0, 'WERR_OK'):
412 print("DsAddEntry failed with status %s info %s" % (ctr
.extended_err
))
413 raise RuntimeError("DsAddEntry failed")
416 raise RuntimeError("expected err_ver 1, got %u" % ctr
.err_ver
)
417 if ctr
.err_data
.status
!= (0, 'WERR_OK'):
418 print("DsAddEntry failed with status %s info %s" % (ctr
.err_data
.status
,
419 ctr
.err_data
.info
.extended_err
))
420 raise RuntimeError("DsAddEntry failed")
421 if ctr
.err_data
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
422 print("DsAddEntry failed with dir_err %u" % ctr
.err_data
.dir_err
)
423 raise RuntimeError("DsAddEntry failed")
427 def join_add_ntdsdsa(ctx
):
428 '''add the ntdsdsa object'''
430 print "Adding %s" % ctx
.ntds_dn
433 "objectclass" : "nTDSDSA",
434 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
435 "dMDLocation" : ctx
.schema_dn
}
437 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
439 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
440 rec
["msDS-Behavior-Version"] = str(samba
.dsdb
.DS_DOMAIN_FUNCTION_2008_R2
)
442 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
443 rec
["msDS-HasDomainNCs"] = ctx
.base_dn
446 rec
["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx
.schema_dn
447 rec
["msDS-HasFullReplicaNCs"] = ctx
.nc_list
448 rec
["options"] = "37"
449 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
451 rec
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
452 rec
["HasMasterNCs"] = nc_list
453 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
454 rec
["msDS-HasMasterNCs"] = ctx
.nc_list
456 rec
["invocationId"] = ndr_pack(ctx
.invocation_id
)
457 ctx
.DsAddEntry([rec
])
459 # find the GUID of our NTDS DN
460 res
= ctx
.samdb
.search(base
=ctx
.ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["objectGUID"])
461 ctx
.ntds_guid
= misc
.GUID(ctx
.samdb
.schema_format_value("objectGUID", res
[0]["objectGUID"][0]))
463 def join_add_objects(ctx
):
464 '''add the various objects needed for the join'''
466 print "Adding %s" % ctx
.acct_dn
469 "objectClass": "computer",
470 "displayname": ctx
.samname
,
471 "samaccountname" : ctx
.samname
,
472 "userAccountControl" : str(ctx
.userAccountControl | samba
.dsdb
.UF_ACCOUNTDISABLE
),
473 "dnshostname" : ctx
.dnshostname
}
474 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2008
:
475 rec
['msDS-SupportedEncryptionTypes'] = str(samba
.dsdb
.ENC_ALL_TYPES
)
476 elif ctx
.promote_existing
:
477 rec
['msDS-SupportedEncryptionTypes'] = []
479 rec
["managedby"] = ctx
.managedby
480 elif ctx
.promote_existing
:
481 rec
["managedby"] = []
483 if ctx
.never_reveal_sid
:
484 rec
["msDS-NeverRevealGroup"] = ctx
.never_reveal_sid
485 elif ctx
.promote_existing
:
486 rec
["msDS-NeverRevealGroup"] = []
489 rec
["msDS-RevealOnDemandGroup"] = ctx
.reveal_sid
490 elif ctx
.promote_existing
:
491 rec
["msDS-RevealOnDemandGroup"] = []
493 if ctx
.promote_existing
:
494 if ctx
.promote_from_dn
!= ctx
.acct_dn
:
495 ctx
.samdb
.rename(ctx
.promote_from_dn
, ctx
.acct_dn
)
496 ctx
.samdb
.modify(ldb
.Message
.from_dict(ctx
.samdb
, rec
, ldb
.FLAG_MOD_REPLACE
))
501 ctx
.add_krbtgt_account()
503 print "Adding %s" % ctx
.server_dn
506 "objectclass" : "server",
507 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
508 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
509 samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
510 samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
511 # windows seems to add the dnsHostName later
512 "dnsHostName" : ctx
.dnshostname
}
515 rec
["serverReference"] = ctx
.acct_dn
520 # the rest is done after replication
524 ctx
.join_add_ntdsdsa()
526 if ctx
.connection_dn
is not None:
527 print "Adding %s" % ctx
.connection_dn
529 "dn" : ctx
.connection_dn
,
530 "objectclass" : "nTDSConnection",
531 "enabledconnection" : "TRUE",
533 "fromServer" : ctx
.dc_ntds_dn
}
537 print "Adding SPNs to %s" % ctx
.acct_dn
539 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
540 for i
in range(len(ctx
.SPNs
)):
541 ctx
.SPNs
[i
] = ctx
.SPNs
[i
].replace("$NTDSGUID", str(ctx
.ntds_guid
))
542 m
["servicePrincipalName"] = ldb
.MessageElement(ctx
.SPNs
,
543 ldb
.FLAG_MOD_REPLACE
,
544 "servicePrincipalName")
547 # The account password set operation should normally be done over
548 # LDAP. Windows 2000 DCs however allow this only with SSL
549 # connections which are hard to set up and otherwise refuse with
550 # ERR_UNWILLING_TO_PERFORM. In this case we fall back to libnet
552 print "Setting account password for %s" % ctx
.samname
554 ctx
.samdb
.setpassword("(&(objectClass=user)(sAMAccountName=%s))"
555 % ldb
.binary_encode(ctx
.samname
),
557 force_change_at_next_login
=False,
558 username
=ctx
.samname
)
559 except ldb
.LdbError
, (num
, _
):
560 if num
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
562 ctx
.net
.set_password(account_name
=ctx
.samname
,
563 domain_name
=ctx
.domain_name
,
564 newpassword
=ctx
.acct_pass
)
566 res
= ctx
.samdb
.search(base
=ctx
.acct_dn
, scope
=ldb
.SCOPE_BASE
,
567 attrs
=["msDS-KeyVersionNumber"])
568 if "msDS-KeyVersionNumber" in res
[0]:
569 ctx
.key_version_number
= int(res
[0]["msDS-KeyVersionNumber"][0])
571 ctx
.key_version_number
= None
573 print("Enabling account")
575 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
576 m
["userAccountControl"] = ldb
.MessageElement(str(ctx
.userAccountControl
),
577 ldb
.FLAG_MOD_REPLACE
,
578 "userAccountControl")
581 def join_add_objects2(ctx
):
582 """add the various objects needed for the join, for subdomains post replication"""
584 print "Adding %s" % ctx
.partition_dn
585 # NOTE: windows sends a ntSecurityDescriptor here, we
588 "dn" : ctx
.partition_dn
,
589 "objectclass" : "crossRef",
590 "objectCategory" : "CN=Cross-Ref,%s" % ctx
.schema_dn
,
591 "nCName" : ctx
.base_dn
,
592 "nETBIOSName" : ctx
.domain_name
,
593 "dnsRoot": ctx
.dnsdomain
,
594 "trustParent" : ctx
.parent_partition_dn
,
595 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_NC|samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
)}
596 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
597 rec
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
601 "objectclass" : "nTDSDSA",
602 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
603 "dMDLocation" : ctx
.schema_dn
}
605 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
607 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
608 rec2
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
610 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
611 rec2
["msDS-HasDomainNCs"] = ctx
.base_dn
613 rec2
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
614 rec2
["HasMasterNCs"] = nc_list
615 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
616 rec2
["msDS-HasMasterNCs"] = ctx
.nc_list
617 rec2
["options"] = "1"
618 rec2
["invocationId"] = ndr_pack(ctx
.invocation_id
)
620 objects
= ctx
.DsAddEntry([rec
, rec2
])
621 if len(objects
) != 2:
622 raise DCJoinException("Expected 2 objects from DsAddEntry")
624 ctx
.ntds_guid
= objects
[1].guid
626 print("Replicating partition DN")
627 ctx
.repl
.replicate(ctx
.partition_dn
,
628 misc
.GUID("00000000-0000-0000-0000-000000000000"),
630 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
631 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
633 print("Replicating NTDS DN")
634 ctx
.repl
.replicate(ctx
.ntds_dn
,
635 misc
.GUID("00000000-0000-0000-0000-000000000000"),
637 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
638 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
640 def join_provision(ctx
):
641 """Provision the local SAM."""
643 print "Calling bare provision"
645 logger
= logging
.getLogger("provision")
646 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
647 smbconf
= ctx
.lp
.configfile
649 presult
= provision(logger
, system_session(), None, smbconf
=smbconf
,
650 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_DRS
, realm
=ctx
.realm
,
651 rootdn
=ctx
.root_dn
, domaindn
=ctx
.base_dn
,
652 schemadn
=ctx
.schema_dn
, configdn
=ctx
.config_dn
,
653 serverdn
=ctx
.server_dn
, domain
=ctx
.domain_name
,
654 hostname
=ctx
.myname
, domainsid
=ctx
.domsid
,
655 machinepass
=ctx
.acct_pass
, serverrole
="domain controller",
656 sitename
=ctx
.site
, lp
=ctx
.lp
, ntdsguid
=ctx
.ntds_guid
,
657 use_ntvfs
=ctx
.use_ntvfs
, dns_backend
=ctx
.dns_backend
)
658 print "Provision OK for domain DN %s" % presult
.domaindn
659 ctx
.local_samdb
= presult
.samdb
661 ctx
.paths
= presult
.paths
662 ctx
.names
= presult
.names
664 def join_provision_own_domain(ctx
):
665 """Provision the local SAM."""
667 # we now operate exclusively on the local database, which
668 # we need to reopen in order to get the newly created schema
669 print("Reconnecting to local samdb")
670 ctx
.samdb
= SamDB(url
=ctx
.local_samdb
.url
,
671 session_info
=system_session(),
672 lp
=ctx
.local_samdb
.lp
,
674 ctx
.samdb
.set_invocation_id(str(ctx
.invocation_id
))
675 ctx
.local_samdb
= ctx
.samdb
677 print("Finding domain GUID from ncName")
678 res
= ctx
.local_samdb
.search(base
=ctx
.partition_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['ncName'],
679 controls
=["extended_dn:1:1"])
680 domguid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['ncName'][0]).get_extended_component('GUID')))
681 print("Got domain GUID %s" % domguid
)
683 print("Calling own domain provision")
685 logger
= logging
.getLogger("provision")
686 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
688 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
690 presult
= provision_fill(ctx
.local_samdb
, secrets_ldb
,
691 logger
, ctx
.names
, ctx
.paths
, domainsid
=security
.dom_sid(ctx
.domsid
),
693 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_SUBDOMAIN
,
694 machinepass
=ctx
.acct_pass
, serverrole
="domain controller",
695 lp
=ctx
.lp
, hostip
=ctx
.names
.hostip
, hostip6
=ctx
.names
.hostip6
,
696 dns_backend
=ctx
.dns_backend
)
697 print("Provision OK for domain %s" % ctx
.names
.dnsdomain
)
699 def join_replicate(ctx
):
700 """Replicate the SAM."""
702 print "Starting replication"
703 ctx
.local_samdb
.transaction_start()
705 source_dsa_invocation_id
= misc
.GUID(ctx
.samdb
.get_invocation_id())
706 if ctx
.ntds_guid
is None:
707 print("Using DS_BIND_GUID_W2K3")
708 destination_dsa_guid
= misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID_W2K3
)
710 destination_dsa_guid
= ctx
.ntds_guid
713 repl_creds
= Credentials()
714 repl_creds
.guess(ctx
.lp
)
715 repl_creds
.set_kerberos_state(DONT_USE_KERBEROS
)
716 repl_creds
.set_username(ctx
.samname
)
717 repl_creds
.set_password(ctx
.acct_pass
)
719 repl_creds
= ctx
.creds
721 binding_options
= "seal"
722 if int(ctx
.lp
.get("log level")) >= 5:
723 binding_options
+= ",print"
724 repl
= drs_utils
.drs_Replicate(
725 "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
726 ctx
.lp
, repl_creds
, ctx
.local_samdb
)
728 repl
.replicate(ctx
.schema_dn
, source_dsa_invocation_id
,
729 destination_dsa_guid
, schema
=True, rodc
=ctx
.RODC
,
730 replica_flags
=ctx
.replica_flags
)
731 repl
.replicate(ctx
.config_dn
, source_dsa_invocation_id
,
732 destination_dsa_guid
, rodc
=ctx
.RODC
,
733 replica_flags
=ctx
.replica_flags
)
734 if not ctx
.subdomain
:
735 # Replicate first the critical object for the basedn
736 if not ctx
.domain_replica_flags
& drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
:
737 print "Replicating critical objects from the base DN of the domain"
738 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi
.DRSUAPI_DRS_GET_ANC
739 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
740 destination_dsa_guid
, rodc
=ctx
.RODC
,
741 replica_flags
=ctx
.domain_replica_flags
)
742 ctx
.domain_replica_flags ^
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY | drsuapi
.DRSUAPI_DRS_GET_ANC
744 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_GET_ANC
745 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
746 destination_dsa_guid
, rodc
=ctx
.RODC
,
747 replica_flags
=ctx
.domain_replica_flags
)
749 if ctx
.domaindns_zone
in ctx
.nc_list
:
750 repl
.replicate(ctx
.domaindns_zone
, source_dsa_invocation_id
,
751 destination_dsa_guid
, rodc
=ctx
.RODC
,
752 replica_flags
=ctx
.replica_flags
)
754 if 'DC=ForestDnsZones,%s' % ctx
.root_dn
in ctx
.nc_list
:
755 repl
.replicate('DC=ForestDnsZones,%s' % ctx
.root_dn
, source_dsa_invocation_id
,
756 destination_dsa_guid
, rodc
=ctx
.RODC
,
757 replica_flags
=ctx
.replica_flags
)
758 # FIXME At this point we should add an entry in the forestdns and domaindns NC
759 # (those under CN=Partions,DC=...)
760 # in order to indicate that we hold a replica for this NC
763 repl
.replicate(ctx
.acct_dn
, source_dsa_invocation_id
,
764 destination_dsa_guid
,
765 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
766 repl
.replicate(ctx
.new_krbtgt_dn
, source_dsa_invocation_id
,
767 destination_dsa_guid
,
768 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
770 ctx
.source_dsa_invocation_id
= source_dsa_invocation_id
771 ctx
.destination_dsa_guid
= destination_dsa_guid
773 print "Committing SAM database"
775 ctx
.local_samdb
.transaction_cancel()
778 ctx
.local_samdb
.transaction_commit()
780 def send_DsReplicaUpdateRefs(ctx
, dn
):
781 r
= drsuapi
.DsReplicaUpdateRefsRequest1()
782 r
.naming_context
= drsuapi
.DsReplicaObjectIdentifier()
783 r
.naming_context
.dn
= str(dn
)
784 r
.naming_context
.guid
= misc
.GUID("00000000-0000-0000-0000-000000000000")
785 r
.naming_context
.sid
= security
.dom_sid("S-0-0")
786 r
.dest_dsa_guid
= ctx
.ntds_guid
787 r
.dest_dsa_dns_name
= "%s._msdcs.%s" % (str(ctx
.ntds_guid
), ctx
.dnsforest
)
788 r
.options
= drsuapi
.DRSUAPI_DRS_ADD_REF | drsuapi
.DRSUAPI_DRS_DEL_REF
790 r
.options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
793 ctx
.drsuapi
.DsReplicaUpdateRefs(ctx
.drsuapi_handle
, 1, r
)
795 def join_finalise(ctx
):
796 """Finalise the join, mark us synchronised and setup secrets db."""
798 logger
= logging
.getLogger("provision")
799 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
801 # FIXME we shouldn't do this in all cases
802 # If for some reasons we joined in another site than the one of
803 # DC we just replicated from then we don't need to send the updatereplicateref
804 # as replication between sites is time based and on the initiative of the
806 print "Sending DsReplicateUpdateRefs for all the partitions"
807 for nc
in ctx
.full_nc_list
:
808 ctx
.send_DsReplicaUpdateRefs(nc
)
811 print "Setting RODC invocationId"
812 ctx
.local_samdb
.set_invocation_id(str(ctx
.invocation_id
))
813 ctx
.local_samdb
.set_opaque_integer("domainFunctionality",
814 ctx
.behavior_version
)
816 m
.dn
= ldb
.Dn(ctx
.local_samdb
, "%s" % ctx
.ntds_dn
)
817 m
["invocationId"] = ldb
.MessageElement(ndr_pack(ctx
.invocation_id
),
818 ldb
.FLAG_MOD_REPLACE
,
820 ctx
.local_samdb
.modify(m
)
822 # Note: as RODC the invocationId is only stored
823 # on the RODC itself, the other DCs never see it.
825 # Thats is why we fix up the replPropertyMetaData stamp
826 # for the 'invocationId' attribute, we need to change
827 # the 'version' to '0', this is what windows 2008r2 does as RODC
829 # This means if the object on a RWDC ever gets a invocationId
830 # attribute, it will have version '1' (or higher), which will
831 # will overwrite the RODC local value.
832 ctx
.local_samdb
.set_attribute_replmetadata_version(m
.dn
,
836 print "Setting isSynchronized and dsServiceName"
838 m
.dn
= ldb
.Dn(ctx
.local_samdb
, '@ROOTDSE')
839 m
["isSynchronized"] = ldb
.MessageElement("TRUE", ldb
.FLAG_MOD_REPLACE
, "isSynchronized")
840 m
["dsServiceName"] = ldb
.MessageElement("<GUID=%s>" % str(ctx
.ntds_guid
),
841 ldb
.FLAG_MOD_REPLACE
, "dsServiceName")
842 ctx
.local_samdb
.modify(m
)
847 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
849 print "Setting up secrets database"
850 secretsdb_self_join(secrets_ldb
, domain
=ctx
.domain_name
,
852 dnsdomain
=ctx
.dnsdomain
,
853 netbiosname
=ctx
.myname
,
854 domainsid
=security
.dom_sid(ctx
.domsid
),
855 machinepass
=ctx
.acct_pass
,
856 secure_channel_type
=ctx
.secure_channel_type
,
857 key_version_number
=ctx
.key_version_number
)
859 if ctx
.dns_backend
.startswith("BIND9_"):
860 dnspass
= samba
.generate_random_password(128, 255)
862 setup_bind9_dns(ctx
.local_samdb
, secrets_ldb
, security
.dom_sid(ctx
.domsid
),
863 ctx
.names
, ctx
.paths
, ctx
.lp
, logger
,
864 dns_backend
=ctx
.dns_backend
,
865 dnspass
=dnspass
, os_level
=ctx
.behavior_version
,
866 targetdir
=ctx
.targetdir
)
868 def join_setup_trusts(ctx
):
869 """provision the local SAM."""
871 def arcfour_encrypt(key
, data
):
872 from Crypto
.Cipher
import ARC4
874 return c
.encrypt(data
)
876 def string_to_array(string
):
877 blob
= [0] * len(string
)
879 for i
in range(len(string
)):
880 blob
[i
] = ord(string
[i
])
884 print "Setup domain trusts with server %s" % ctx
.server
885 binding_options
= "" # why doesn't signing work here? w2k8r2 claims no session key
886 lsaconn
= lsa
.lsarpc("ncacn_np:%s[%s]" % (ctx
.server
, binding_options
),
889 objectAttr
= lsa
.ObjectAttribute()
890 objectAttr
.sec_qos
= lsa
.QosInfo()
892 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
893 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
895 info
= lsa
.TrustDomainInfoInfoEx()
896 info
.domain_name
.string
= ctx
.dnsdomain
897 info
.netbios_name
.string
= ctx
.domain_name
898 info
.sid
= security
.dom_sid(ctx
.domsid
)
899 info
.trust_direction
= lsa
.LSA_TRUST_DIRECTION_INBOUND | lsa
.LSA_TRUST_DIRECTION_OUTBOUND
900 info
.trust_type
= lsa
.LSA_TRUST_TYPE_UPLEVEL
901 info
.trust_attributes
= lsa
.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
904 oldname
= lsa
.String()
905 oldname
.string
= ctx
.dnsdomain
906 oldinfo
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, oldname
,
907 lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
908 print("Removing old trust record for %s (SID %s)" % (ctx
.dnsdomain
, oldinfo
.info_ex
.sid
))
909 lsaconn
.DeleteTrustedDomain(pol_handle
, oldinfo
.info_ex
.sid
)
913 password_blob
= string_to_array(ctx
.trustdom_pass
.encode('utf-16-le'))
915 clear_value
= drsblobs
.AuthInfoClear()
916 clear_value
.size
= len(password_blob
)
917 clear_value
.password
= password_blob
919 clear_authentication_information
= drsblobs
.AuthenticationInformation()
920 clear_authentication_information
.LastUpdateTime
= samba
.unix2nttime(int(time
.time()))
921 clear_authentication_information
.AuthType
= lsa
.TRUST_AUTH_TYPE_CLEAR
922 clear_authentication_information
.AuthInfo
= clear_value
924 authentication_information_array
= drsblobs
.AuthenticationInformationArray()
925 authentication_information_array
.count
= 1
926 authentication_information_array
.array
= [clear_authentication_information
]
928 outgoing
= drsblobs
.trustAuthInOutBlob()
930 outgoing
.current
= authentication_information_array
932 trustpass
= drsblobs
.trustDomainPasswords()
933 confounder
= [3] * 512
936 confounder
[i
] = random
.randint(0, 255)
938 trustpass
.confounder
= confounder
940 trustpass
.outgoing
= outgoing
941 trustpass
.incoming
= outgoing
943 trustpass_blob
= ndr_pack(trustpass
)
945 encrypted_trustpass
= arcfour_encrypt(lsaconn
.session_key
, trustpass_blob
)
947 auth_blob
= lsa
.DATA_BUF2()
948 auth_blob
.size
= len(encrypted_trustpass
)
949 auth_blob
.data
= string_to_array(encrypted_trustpass
)
951 auth_info
= lsa
.TrustDomainInfoAuthInfoInternal()
952 auth_info
.auth_blob
= auth_blob
954 trustdom_handle
= lsaconn
.CreateTrustedDomainEx2(pol_handle
,
957 security
.SEC_STD_DELETE
)
960 "dn" : "cn=%s,cn=system,%s" % (ctx
.dnsforest
, ctx
.base_dn
),
961 "objectclass" : "trustedDomain",
962 "trustType" : str(info
.trust_type
),
963 "trustAttributes" : str(info
.trust_attributes
),
964 "trustDirection" : str(info
.trust_direction
),
965 "flatname" : ctx
.forest_domain_name
,
966 "trustPartner" : ctx
.dnsforest
,
967 "trustAuthIncoming" : ndr_pack(outgoing
),
968 "trustAuthOutgoing" : ndr_pack(outgoing
)
970 ctx
.local_samdb
.add(rec
)
973 "dn" : "cn=%s$,cn=users,%s" % (ctx
.forest_domain_name
, ctx
.base_dn
),
974 "objectclass" : "user",
975 "userAccountControl" : str(samba
.dsdb
.UF_INTERDOMAIN_TRUST_ACCOUNT
),
976 "clearTextPassword" : ctx
.trustdom_pass
.encode('utf-16-le')
978 ctx
.local_samdb
.add(rec
)
982 # full_nc_list is the list of naming context (NC) for which we will
983 # send a updateRef command to the partner DC
984 ctx
.nc_list
= [ ctx
.config_dn
, ctx
.schema_dn
]
985 ctx
.full_nc_list
= [ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
987 if not ctx
.subdomain
:
988 ctx
.nc_list
+= [ctx
.base_dn
]
989 if ctx
.dns_backend
!= "NONE":
990 ctx
.nc_list
+= [ctx
.domaindns_zone
]
992 if ctx
.dns_backend
!= "NONE":
993 ctx
.full_nc_list
+= ['DC=DomainDnsZones,%s' % ctx
.base_dn
]
994 ctx
.full_nc_list
+= ['DC=ForestDnsZones,%s' % ctx
.root_dn
]
995 ctx
.nc_list
+= ['DC=ForestDnsZones,%s' % ctx
.root_dn
]
997 if ctx
.promote_existing
:
998 ctx
.promote_possible()
1000 ctx
.cleanup_old_join()
1003 ctx
.join_add_objects()
1004 ctx
.join_provision()
1005 ctx
.join_replicate()
1007 ctx
.join_add_objects2()
1008 ctx
.join_provision_own_domain()
1009 ctx
.join_setup_trusts()
1012 print "Join failed - cleaning up"
1013 ctx
.cleanup_old_join()
1017 def join_RODC(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
1018 targetdir
=None, domain
=None, domain_critical_only
=False,
1019 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
1020 promote_existing
=False):
1021 """Join as a RODC."""
1023 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
,
1024 machinepass
, use_ntvfs
, dns_backend
, promote_existing
)
1026 lp
.set("workgroup", ctx
.domain_name
)
1027 print("workgroup is %s" % ctx
.domain_name
)
1029 lp
.set("realm", ctx
.realm
)
1030 print("realm is %s" % ctx
.realm
)
1032 ctx
.krbtgt_dn
= "CN=krbtgt_%s,CN=Users,%s" % (ctx
.myname
, ctx
.base_dn
)
1034 # setup some defaults for accounts that should be replicated to this RODC
1035 ctx
.never_reveal_sid
= [
1036 "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_DENY
),
1037 "<SID=%s>" % security
.SID_BUILTIN_ADMINISTRATORS
,
1038 "<SID=%s>" % security
.SID_BUILTIN_SERVER_OPERATORS
,
1039 "<SID=%s>" % security
.SID_BUILTIN_BACKUP_OPERATORS
,
1040 "<SID=%s>" % security
.SID_BUILTIN_ACCOUNT_OPERATORS
]
1041 ctx
.reveal_sid
= "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_ALLOW
)
1043 mysid
= ctx
.get_mysid()
1044 admin_dn
= "<SID=%s>" % mysid
1045 ctx
.managedby
= admin_dn
1047 ctx
.userAccountControl
= (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
1048 samba
.dsdb
.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
1049 samba
.dsdb
.UF_PARTIAL_SECRETS_ACCOUNT
)
1051 ctx
.SPNs
.extend([ "RestrictedKrbHost/%s" % ctx
.myname
,
1052 "RestrictedKrbHost/%s" % ctx
.dnshostname
])
1054 ctx
.connection_dn
= "CN=RODC Connection (FRS),%s" % ctx
.ntds_dn
1055 ctx
.secure_channel_type
= misc
.SEC_CHAN_RODC
1057 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1058 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1059 drsuapi
.DRSUAPI_DRS_GET_ANC |
1060 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED |
1061 drsuapi
.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
1062 drsuapi
.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP
)
1063 ctx
.domain_replica_flags
= ctx
.replica_flags
1064 if domain_critical_only
:
1065 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
1069 print "Joined domain %s (SID %s) as an RODC" % (ctx
.domain_name
, ctx
.domsid
)
1072 def join_DC(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
1073 targetdir
=None, domain
=None, domain_critical_only
=False,
1074 machinepass
=None, use_ntvfs
=False, dns_backend
=None,
1075 promote_existing
=False):
1077 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
,
1078 machinepass
, use_ntvfs
, dns_backend
, promote_existing
)
1080 lp
.set("workgroup", ctx
.domain_name
)
1081 print("workgroup is %s" % ctx
.domain_name
)
1083 lp
.set("realm", ctx
.realm
)
1084 print("realm is %s" % ctx
.realm
)
1086 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
1088 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
1089 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
1091 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
1092 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1093 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1094 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1095 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
1096 ctx
.domain_replica_flags
= ctx
.replica_flags
1097 if domain_critical_only
:
1098 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
1101 print "Joined domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
)
1103 def join_subdomain(server
=None, creds
=None, lp
=None, site
=None,
1104 netbios_name
=None, targetdir
=None, parent_domain
=None, dnsdomain
=None,
1105 netbios_domain
=None, machinepass
=None, use_ntvfs
=False,
1108 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, parent_domain
,
1109 machinepass
, use_ntvfs
, dns_backend
)
1110 ctx
.subdomain
= True
1111 ctx
.parent_domain_name
= ctx
.domain_name
1112 ctx
.domain_name
= netbios_domain
1113 ctx
.realm
= dnsdomain
1114 ctx
.parent_dnsdomain
= ctx
.dnsdomain
1115 ctx
.parent_partition_dn
= ctx
.get_parent_partition_dn()
1116 ctx
.dnsdomain
= dnsdomain
1117 ctx
.partition_dn
= "CN=%s,CN=Partitions,%s" % (ctx
.domain_name
, ctx
.config_dn
)
1118 ctx
.naming_master
= ctx
.get_naming_master()
1119 if ctx
.naming_master
!= ctx
.server
:
1120 print("Reconnecting to naming master %s" % ctx
.naming_master
)
1121 ctx
.server
= ctx
.naming_master
1122 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
1123 session_info
=system_session(),
1124 credentials
=ctx
.creds
, lp
=ctx
.lp
)
1126 ctx
.base_dn
= samba
.dn_from_dns_name(dnsdomain
)
1127 ctx
.domsid
= str(security
.random_sid())
1129 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
, ctx
.dnsdomain
)
1130 ctx
.trustdom_pass
= samba
.generate_random_password(128, 128)
1132 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
1134 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
1135 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
1137 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
1138 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
1139 drsuapi
.DRSUAPI_DRS_PER_SYNC |
1140 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
1141 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
1142 ctx
.domain_replica_flags
= ctx
.replica_flags
1145 print "Created domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
)