4 # Copyright Andrew Tridgell 2010
5 # Copyright Andrew Bartlett 2010
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 """Joining a domain."""
23 from samba
.auth
import system_session
24 from samba
.samdb
import SamDB
25 from samba
import gensec
, Ldb
, drs_utils
26 import ldb
, samba
, sys
, os
, uuid
27 from samba
.ndr
import ndr_pack
28 from samba
.dcerpc
import security
, drsuapi
, misc
, nbt
, lsa
, drsblobs
29 from samba
.credentials
import Credentials
, DONT_USE_KERBEROS
30 from samba
.provision
import secretsdb_self_join
, provision
, provision_fill
, FILL_DRS
, FILL_SUBDOMAIN
31 from samba
.schema
import Schema
32 from samba
.net
import Net
38 # this makes debugging easier
39 talloc
.enable_null_tracking()
41 class DCJoinException(Exception):
43 def __init__(self
, msg
):
44 super(DCJoinException
, self
).__init
__("Can't join, error: %s" % msg
)
47 class dc_join(object):
48 '''perform a DC join'''
50 def __init__(ctx
, server
=None, creds
=None, lp
=None, site
=None,
51 netbios_name
=None, targetdir
=None, domain
=None):
55 ctx
.netbios_name
= netbios_name
56 ctx
.targetdir
= targetdir
58 ctx
.creds
.set_gensec_features(creds
.get_gensec_features() | gensec
.FEATURE_SEAL
)
59 ctx
.net
= Net(creds
=ctx
.creds
, lp
=ctx
.lp
)
61 if server
is not None:
64 print("Finding a writeable DC for domain '%s'" % domain
)
65 ctx
.server
= ctx
.find_dc(domain
)
66 print("Found DC %s" % ctx
.server
)
68 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
69 session_info
=system_session(),
70 credentials
=ctx
.creds
, lp
=ctx
.lp
)
73 ctx
.samdb
.search(scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
74 except ldb
.LdbError
, (enum
, estr
):
75 raise DCJoinException(estr
)
78 ctx
.myname
= netbios_name
79 ctx
.samname
= "%s$" % ctx
.myname
80 ctx
.base_dn
= str(ctx
.samdb
.get_default_basedn())
81 ctx
.root_dn
= str(ctx
.samdb
.get_root_basedn())
82 ctx
.schema_dn
= str(ctx
.samdb
.get_schema_basedn())
83 ctx
.config_dn
= str(ctx
.samdb
.get_config_basedn())
84 ctx
.domsid
= ctx
.samdb
.get_domain_sid()
85 ctx
.domain_name
= ctx
.get_domain_name()
86 ctx
.forest_domain_name
= ctx
.get_forest_domain_name()
87 ctx
.invocation_id
= misc
.GUID(str(uuid
.uuid4()))
89 ctx
.dc_ntds_dn
= ctx
.get_dsServiceName()
90 ctx
.dc_dnsHostName
= ctx
.get_dnsHostName()
91 ctx
.behavior_version
= ctx
.get_behavior_version()
93 ctx
.acct_pass
= samba
.generate_random_password(32, 40)
95 # work out the DNs of all the objects we will be adding
96 ctx
.server_dn
= "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx
.myname
, ctx
.site
, ctx
.config_dn
)
97 ctx
.ntds_dn
= "CN=NTDS Settings,%s" % ctx
.server_dn
98 topology_base
= "CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % ctx
.base_dn
99 if ctx
.dn_exists(topology_base
):
100 ctx
.topology_dn
= "CN=%s,%s" % (ctx
.myname
, topology_base
)
102 ctx
.topology_dn
= None
104 ctx
.dnsdomain
= ctx
.samdb
.domain_dns_name()
105 ctx
.dnsforest
= ctx
.samdb
.forest_dns_name()
106 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
, ctx
.dnsdomain
)
108 ctx
.realm
= ctx
.dnsdomain
110 ctx
.acct_dn
= "CN=%s,OU=Domain Controllers,%s" % (ctx
.myname
, ctx
.base_dn
)
114 ctx
.SPNs
= [ "HOST/%s" % ctx
.myname
,
115 "HOST/%s" % ctx
.dnshostname
,
116 "GC/%s/%s" % (ctx
.dnshostname
, ctx
.dnsforest
) ]
118 # these elements are optional
119 ctx
.never_reveal_sid
= None
120 ctx
.reveal_sid
= None
121 ctx
.connection_dn
= None
126 ctx
.subdomain
= False
129 def del_noerror(ctx
, dn
, recursive
=False):
132 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["dn"])
136 ctx
.del_noerror(r
.dn
, recursive
=True)
139 print "Deleted %s" % dn
143 def cleanup_old_join(ctx
):
144 '''remove any DNs from a previous join'''
146 # find the krbtgt link
147 print("checking samaccountname")
151 res
= ctx
.samdb
.search(base
=ctx
.samdb
.get_default_basedn(),
152 expression
='samAccountName=%s' % ldb
.binary_encode(ctx
.samname
),
153 attrs
=["msDS-krbTgtLink"])
155 ctx
.del_noerror(res
[0].dn
, recursive
=True)
156 if ctx
.connection_dn
is not None:
157 ctx
.del_noerror(ctx
.connection_dn
)
158 if ctx
.krbtgt_dn
is not None:
159 ctx
.del_noerror(ctx
.krbtgt_dn
)
160 ctx
.del_noerror(ctx
.ntds_dn
)
161 ctx
.del_noerror(ctx
.server_dn
, recursive
=True)
163 ctx
.del_noerror(ctx
.topology_dn
)
165 ctx
.del_noerror(ctx
.partition_dn
)
167 ctx
.new_krbtgt_dn
= res
[0]["msDS-Krbtgtlink"][0]
168 ctx
.del_noerror(ctx
.new_krbtgt_dn
)
171 binding_options
= "sign"
172 lsaconn
= lsa
.lsarpc("ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
175 objectAttr
= lsa
.ObjectAttribute()
176 objectAttr
.sec_qos
= lsa
.QosInfo()
178 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
179 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
182 name
.string
= ctx
.realm
183 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
185 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
188 name
.string
= ctx
.forest_domain_name
189 info
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, name
, lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
191 lsaconn
.DeleteTrustedDomain(pol_handle
, info
.info_ex
.sid
)
196 def find_dc(ctx
, domain
):
197 '''find a writeable DC for the given domain'''
199 ctx
.cldap_ret
= ctx
.net
.finddc(domain
, nbt
.NBT_SERVER_LDAP | nbt
.NBT_SERVER_DS | nbt
.NBT_SERVER_WRITABLE
)
201 raise Exception("Failed to find a writeable DC for domain '%s'" % domain
)
202 if ctx
.cldap_ret
.client_site
is not None and ctx
.cldap_ret
.client_site
!= "":
203 ctx
.site
= ctx
.cldap_ret
.client_site
204 return ctx
.cldap_ret
.pdc_dns_name
207 def get_dsServiceName(ctx
):
208 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
209 return res
[0]["dsServiceName"][0]
211 def get_behavior_version(ctx
):
212 res
= ctx
.samdb
.search(base
=ctx
.base_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["msDS-Behavior-Version"])
213 if "msDS-Behavior-Version" in res
[0]:
214 return int(res
[0]["msDS-Behavior-Version"][0])
216 return samba
.dsdb
.DS_DOMAIN_FUNCTION_2000
218 def get_dnsHostName(ctx
):
219 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])
220 return res
[0]["dnsHostName"][0]
222 def get_domain_name(ctx
):
223 '''get netbios name of the domain from the partitions record'''
224 partitions_dn
= ctx
.samdb
.get_partitions_dn()
225 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
226 expression
='ncName=%s' % ctx
.samdb
.get_default_basedn())
227 return res
[0]["nETBIOSName"][0]
229 def get_forest_domain_name(ctx
):
230 '''get netbios name of the domain from the partitions record'''
231 partitions_dn
= ctx
.samdb
.get_partitions_dn()
232 res
= ctx
.samdb
.search(base
=partitions_dn
, scope
=ldb
.SCOPE_ONELEVEL
, attrs
=["nETBIOSName"],
233 expression
='ncName=%s' % ctx
.samdb
.get_root_basedn())
234 return res
[0]["nETBIOSName"][0]
236 def get_parent_partition_dn(ctx
):
237 '''get the parent domain partition DN from parent DNS name'''
238 res
= ctx
.samdb
.search(base
=ctx
.config_dn
, attrs
=[],
239 expression
='(&(objectclass=crossRef)(dnsRoot=%s)(systemFlags:%s:=%u))' %
240 (ctx
.parent_dnsdomain
, ldb
.OID_COMPARATOR_AND
, samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
))
241 return str(res
[0].dn
)
243 def get_naming_master(ctx
):
244 '''get the parent domain partition DN from parent DNS name'''
245 res
= ctx
.samdb
.search(base
='CN=Partitions,%s' % ctx
.config_dn
, attrs
=['fSMORoleOwner'],
246 scope
=ldb
.SCOPE_BASE
, controls
=["extended_dn:1:1"])
247 if not 'fSMORoleOwner' in res
[0]:
248 raise DCJoinException("Can't find naming master on partition DN %s" % ctx
.partition_dn
)
249 master_guid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
250 master_host
= '%s._msdcs.%s' % (master_guid
, ctx
.dnsforest
)
254 '''get the SID of the connected user. Only works with w2k8 and later,
255 so only used for RODC join'''
256 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["tokenGroups"])
257 binsid
= res
[0]["tokenGroups"][0]
258 return ctx
.samdb
.schema_format_value("objectSID", binsid
)
260 def dn_exists(ctx
, dn
):
261 '''check if a DN exists'''
263 res
= ctx
.samdb
.search(base
=dn
, scope
=ldb
.SCOPE_BASE
, attrs
=[])
264 except ldb
.LdbError
, (enum
, estr
):
265 if enum
== ldb
.ERR_NO_SUCH_OBJECT
:
270 def add_krbtgt_account(ctx
):
271 '''RODCs need a special krbtgt account'''
272 print "Adding %s" % ctx
.krbtgt_dn
274 "dn" : ctx
.krbtgt_dn
,
275 "objectclass" : "user",
276 "useraccountcontrol" : str(samba
.dsdb
.UF_NORMAL_ACCOUNT |
277 samba
.dsdb
.UF_ACCOUNTDISABLE
),
278 "showinadvancedviewonly" : "TRUE",
279 "description" : "krbtgt for %s" % ctx
.samname
}
280 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
282 # now we need to search for the samAccountName attribute on the krbtgt DN,
283 # as this will have been magically set to the krbtgt number
284 res
= ctx
.samdb
.search(base
=ctx
.krbtgt_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["samAccountName"])
285 ctx
.krbtgt_name
= res
[0]["samAccountName"][0]
287 print "Got krbtgt_name=%s" % ctx
.krbtgt_name
290 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
291 m
["msDS-krbTgtLink"] = ldb
.MessageElement(ctx
.krbtgt_dn
,
292 ldb
.FLAG_MOD_REPLACE
, "msDS-krbTgtLink")
295 ctx
.new_krbtgt_dn
= "CN=%s,CN=Users,%s" % (ctx
.krbtgt_name
, ctx
.base_dn
)
296 print "Renaming %s to %s" % (ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
297 ctx
.samdb
.rename(ctx
.krbtgt_dn
, ctx
.new_krbtgt_dn
)
299 def drsuapi_connect(ctx
):
300 '''make a DRSUAPI connection to the naming master'''
301 binding_options
= "seal"
302 if int(ctx
.lp
.get("log level")) >= 4:
303 binding_options
+= ",print"
304 binding_string
= "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
)
305 ctx
.drsuapi
= drsuapi
.drsuapi(binding_string
, ctx
.lp
, ctx
.creds
)
306 (ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drs_DsBind(ctx
.drsuapi
)
308 def create_tmp_samdb(ctx
):
309 '''create a temporary samdb object for schema queries'''
310 ctx
.tmp_schema
= Schema(security
.dom_sid(ctx
.domsid
),
311 schemadn
=ctx
.schema_dn
)
312 ctx
.tmp_samdb
= SamDB(session_info
=system_session(), url
=None, auto_connect
=False,
313 credentials
=ctx
.creds
, lp
=ctx
.lp
, global_schema
=False,
315 ctx
.tmp_samdb
.set_schema(ctx
.tmp_schema
)
317 def build_DsReplicaAttribute(ctx
, attrname
, attrvalue
):
318 '''build a DsReplicaAttributeCtr object'''
319 r
= drsuapi
.DsReplicaAttribute()
320 r
.attid
= ctx
.tmp_samdb
.get_attid_from_lDAPDisplayName(attrname
)
324 def DsAddEntry(ctx
, recs
):
325 '''add a record via the DRSUAPI DsAddEntry call'''
326 if ctx
.drsuapi
is None:
327 ctx
.drsuapi_connect()
328 if ctx
.tmp_samdb
is None:
329 ctx
.create_tmp_samdb()
333 id = drsuapi
.DsReplicaObjectIdentifier()
340 if not isinstance(rec
[a
], list):
344 rattr
= ctx
.tmp_samdb
.dsdb_DsReplicaAttribute(ctx
.tmp_samdb
, a
, v
)
347 attribute_ctr
= drsuapi
.DsReplicaAttributeCtr()
348 attribute_ctr
.num_attributes
= len(attrs
)
349 attribute_ctr
.attributes
= attrs
351 object = drsuapi
.DsReplicaObject()
352 object.identifier
= id
353 object.attribute_ctr
= attribute_ctr
355 list_object
= drsuapi
.DsReplicaObjectListItem()
356 list_object
.object = object
357 objects
.append(list_object
)
359 req2
= drsuapi
.DsAddEntryRequest2()
360 req2
.first_object
= objects
[0]
361 prev
= req2
.first_object
362 for o
in objects
[1:]:
366 (level
, ctr
) = ctx
.drsuapi
.DsAddEntry(ctx
.drsuapi_handle
, 2, req2
)
368 raise RuntimeError("expected err_ver 1, got %u" % ctr
.err_ver
)
369 if ctr
.err_data
.status
!= (0, 'WERR_OK'):
370 print("DsAddEntry failed with status %s info %s" % (ctr
.err_data
.status
,
371 ctr
.err_data
.info
.extended_err
))
372 raise RuntimeError("DsAddEntry failed")
373 if ctr
.err_data
.dir_err
!= drsuapi
.DRSUAPI_DIRERR_OK
:
374 print("DsAddEntry failed with dir_err %u" % ctr
.err_data
.dir_err
)
375 raise RuntimeError("DsAddEntry failed")
379 def join_add_ntdsdsa(ctx
):
380 '''add the ntdsdsa object'''
381 # FIXME: the partition (NC) assignment has to be made dynamic
382 print "Adding %s" % ctx
.ntds_dn
385 "objectclass" : "nTDSDSA",
386 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
387 "dMDLocation" : ctx
.schema_dn
}
389 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
391 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
392 rec
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
394 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
395 rec
["msDS-HasDomainNCs"] = ctx
.base_dn
398 rec
["objectCategory"] = "CN=NTDS-DSA-RO,%s" % ctx
.schema_dn
399 rec
["msDS-HasFullReplicaNCs"] = nc_list
400 rec
["options"] = "37"
401 ctx
.samdb
.add(rec
, ["rodc_join:1:1"])
403 rec
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
404 rec
["HasMasterNCs"] = nc_list
405 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
406 rec
["msDS-HasMasterNCs"] = nc_list
408 rec
["invocationId"] = ndr_pack(ctx
.invocation_id
)
409 ctx
.DsAddEntry([rec
])
411 # find the GUID of our NTDS DN
412 res
= ctx
.samdb
.search(base
=ctx
.ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["objectGUID"])
413 ctx
.ntds_guid
= misc
.GUID(ctx
.samdb
.schema_format_value("objectGUID", res
[0]["objectGUID"][0]))
416 def join_add_objects(ctx
):
417 '''add the various objects needed for the join'''
419 print "Adding %s" % ctx
.acct_dn
422 "objectClass": "computer",
423 "displayname": ctx
.samname
,
424 "samaccountname" : ctx
.samname
,
425 "userAccountControl" : str(ctx
.userAccountControl | samba
.dsdb
.UF_ACCOUNTDISABLE
),
426 "dnshostname" : ctx
.dnshostname
}
427 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2008
:
428 rec
['msDS-SupportedEncryptionTypes'] = str(samba
.dsdb
.ENC_ALL_TYPES
)
430 rec
["managedby"] = ctx
.managedby
431 if ctx
.never_reveal_sid
:
432 rec
["msDS-NeverRevealGroup"] = ctx
.never_reveal_sid
434 rec
["msDS-RevealOnDemandGroup"] = ctx
.reveal_sid
438 ctx
.add_krbtgt_account()
440 print "Adding %s" % ctx
.server_dn
443 "objectclass" : "server",
444 # windows uses 50000000 decimal for systemFlags. A windows hex/decimal mixup bug?
445 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
446 samba
.dsdb
.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
447 samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
448 # windows seems to add the dnsHostName later
449 "dnsHostName" : ctx
.dnshostname
}
452 rec
["serverReference"] = ctx
.acct_dn
457 # the rest is done after replication
461 ctx
.join_add_ntdsdsa()
463 if ctx
.connection_dn
is not None:
464 print "Adding %s" % ctx
.connection_dn
466 "dn" : ctx
.connection_dn
,
467 "objectclass" : "nTDSConnection",
468 "enabledconnection" : "TRUE",
470 "fromServer" : ctx
.dc_ntds_dn
}
474 print "Adding SPNs to %s" % ctx
.acct_dn
476 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
477 for i
in range(len(ctx
.SPNs
)):
478 ctx
.SPNs
[i
] = ctx
.SPNs
[i
].replace("$NTDSGUID", str(ctx
.ntds_guid
))
479 m
["servicePrincipalName"] = ldb
.MessageElement(ctx
.SPNs
,
481 "servicePrincipalName")
484 print "Setting account password for %s" % ctx
.samname
485 ctx
.samdb
.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ldb
.binary_encode(ctx
.samname
),
487 force_change_at_next_login
=False,
488 username
=ctx
.samname
)
489 res
= ctx
.samdb
.search(base
=ctx
.acct_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["msDS-keyVersionNumber"])
490 ctx
.key_version_number
= int(res
[0]["msDS-keyVersionNumber"][0])
492 print("Enabling account")
494 m
.dn
= ldb
.Dn(ctx
.samdb
, ctx
.acct_dn
)
495 m
["userAccountControl"] = ldb
.MessageElement(str(ctx
.userAccountControl
),
496 ldb
.FLAG_MOD_REPLACE
,
497 "userAccountControl")
501 def join_add_objects2(ctx
):
502 '''add the various objects needed for the join, for subdomains post replication'''
504 print "Adding %s" % ctx
.partition_dn
505 # NOTE: windows sends a ntSecurityDescriptor here, we
508 "dn" : ctx
.partition_dn
,
509 "objectclass" : "crossRef",
510 "objectCategory" : "CN=Cross-Ref,%s" % ctx
.schema_dn
,
511 "nCName" : ctx
.base_dn
,
512 "nETBIOSName" : ctx
.domain_name
,
513 "dnsRoot": ctx
.dnsdomain
,
514 "trustParent" : ctx
.parent_partition_dn
,
515 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_NC|samba
.dsdb
.SYSTEM_FLAG_CR_NTDS_DOMAIN
)}
516 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
517 rec
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
521 "objectclass" : "nTDSDSA",
522 "systemFlags" : str(samba
.dsdb
.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE
),
523 "dMDLocation" : ctx
.schema_dn
}
525 nc_list
= [ ctx
.base_dn
, ctx
.config_dn
, ctx
.schema_dn
]
527 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
528 rec2
["msDS-Behavior-Version"] = str(ctx
.behavior_version
)
530 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
531 rec2
["msDS-HasDomainNCs"] = ctx
.base_dn
533 rec2
["objectCategory"] = "CN=NTDS-DSA,%s" % ctx
.schema_dn
534 rec2
["HasMasterNCs"] = nc_list
535 if ctx
.behavior_version
>= samba
.dsdb
.DS_DOMAIN_FUNCTION_2003
:
536 rec2
["msDS-HasMasterNCs"] = nc_list
537 rec2
["options"] = "1"
538 rec2
["invocationId"] = ndr_pack(ctx
.invocation_id
)
540 objects
= ctx
.DsAddEntry([rec
, rec2
])
541 if len(objects
) != 2:
542 raise DCJoinException("Expected 2 objects from DsAddEntry")
544 ctx
.ntds_guid
= objects
[1].guid
546 print("Replicating partition DN")
547 ctx
.repl
.replicate(ctx
.partition_dn
,
548 misc
.GUID("00000000-0000-0000-0000-000000000000"),
550 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
551 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
553 print("Replicating NTDS DN")
554 ctx
.repl
.replicate(ctx
.ntds_dn
,
555 misc
.GUID("00000000-0000-0000-0000-000000000000"),
557 exop
=drsuapi
.DRSUAPI_EXOP_REPL_OBJ
,
558 replica_flags
=drsuapi
.DRSUAPI_DRS_WRIT_REP
)
560 def join_provision(ctx
):
561 '''provision the local SAM'''
563 print "Calling bare provision"
565 logger
= logging
.getLogger("provision")
566 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
567 smbconf
= ctx
.lp
.configfile
569 presult
= provision(logger
, system_session(), None,
570 smbconf
=smbconf
, targetdir
=ctx
.targetdir
, samdb_fill
=FILL_DRS
,
571 realm
=ctx
.realm
, rootdn
=ctx
.root_dn
, domaindn
=ctx
.base_dn
,
572 schemadn
=ctx
.schema_dn
,
573 configdn
=ctx
.config_dn
,
574 serverdn
=ctx
.server_dn
, domain
=ctx
.domain_name
,
575 hostname
=ctx
.myname
, domainsid
=ctx
.domsid
,
576 machinepass
=ctx
.acct_pass
, serverrole
="domain controller",
577 sitename
=ctx
.site
, lp
=ctx
.lp
, ntdsguid
=ctx
.ntds_guid
,
579 print "Provision OK for domain DN %s" % presult
.domaindn
580 ctx
.local_samdb
= presult
.samdb
582 ctx
.paths
= presult
.paths
583 ctx
.names
= presult
.names
585 def join_provision_own_domain(ctx
):
586 '''provision the local SAM'''
588 # we now operate exclusively on the local database, which
589 # we need to reopen in order to get the newly created schema
590 print("Reconnecting to local samdb")
591 ctx
.samdb
= SamDB(url
=ctx
.local_samdb
.url
,
592 session_info
=system_session(),
593 lp
=ctx
.local_samdb
.lp
,
595 ctx
.samdb
.set_invocation_id(str(ctx
.invocation_id
))
596 ctx
.local_samdb
= ctx
.samdb
598 print("Finding domain GUID from ncName")
599 res
= ctx
.local_samdb
.search(base
=ctx
.partition_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['ncName'],
600 controls
=["extended_dn:1:1"])
601 domguid
= str(misc
.GUID(ldb
.Dn(ctx
.samdb
, res
[0]['ncName'][0]).get_extended_component('GUID')))
602 print("Got domain GUID %s" % domguid
)
604 print("Calling own domain provision")
606 logger
= logging
.getLogger("provision")
607 logger
.addHandler(logging
.StreamHandler(sys
.stdout
))
609 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
611 presult
= provision_fill(ctx
.local_samdb
, secrets_ldb
,
612 logger
, ctx
.names
, ctx
.paths
, domainsid
=security
.dom_sid(ctx
.domsid
),
614 targetdir
=ctx
.targetdir
, samdb_fill
=FILL_SUBDOMAIN
,
615 machinepass
=ctx
.acct_pass
, serverrole
="domain controller",
616 lp
=ctx
.lp
, hostip
=ctx
.names
.hostip
, hostip6
=ctx
.names
.hostip6
,
617 dns_backend
="BIND9_FLATFILE")
618 print("Provision OK for domain %s" % ctx
.names
.dnsdomain
)
621 def join_replicate(ctx
):
622 '''replicate the SAM'''
624 print "Starting replication"
625 ctx
.local_samdb
.transaction_start()
627 source_dsa_invocation_id
= misc
.GUID(ctx
.samdb
.get_invocation_id())
628 if ctx
.ntds_guid
is None:
629 print("Using DS_BIND_GUID_W2K3")
630 destination_dsa_guid
= misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID_W2K3
)
632 destination_dsa_guid
= ctx
.ntds_guid
635 repl_creds
= Credentials()
636 repl_creds
.guess(ctx
.lp
)
637 repl_creds
.set_kerberos_state(DONT_USE_KERBEROS
)
638 repl_creds
.set_username(ctx
.samname
)
639 repl_creds
.set_password(ctx
.acct_pass
)
641 repl_creds
= ctx
.creds
643 binding_options
= "seal"
644 if int(ctx
.lp
.get("log level")) >= 5:
645 binding_options
+= ",print"
646 repl
= drs_utils
.drs_Replicate(
647 "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
),
648 ctx
.lp
, repl_creds
, ctx
.local_samdb
)
650 repl
.replicate(ctx
.schema_dn
, source_dsa_invocation_id
,
651 destination_dsa_guid
, schema
=True, rodc
=ctx
.RODC
,
652 replica_flags
=ctx
.replica_flags
)
653 repl
.replicate(ctx
.config_dn
, source_dsa_invocation_id
,
654 destination_dsa_guid
, rodc
=ctx
.RODC
,
655 replica_flags
=ctx
.replica_flags
)
656 if not ctx
.subdomain
:
657 repl
.replicate(ctx
.base_dn
, source_dsa_invocation_id
,
658 destination_dsa_guid
, rodc
=ctx
.RODC
,
659 replica_flags
=ctx
.domain_replica_flags
)
661 repl
.replicate(ctx
.acct_dn
, source_dsa_invocation_id
,
662 destination_dsa_guid
,
663 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
664 repl
.replicate(ctx
.new_krbtgt_dn
, source_dsa_invocation_id
,
665 destination_dsa_guid
,
666 exop
=drsuapi
.DRSUAPI_EXOP_REPL_SECRET
, rodc
=True)
668 ctx
.source_dsa_invocation_id
= source_dsa_invocation_id
669 ctx
.destination_dsa_guid
= destination_dsa_guid
671 print "Committing SAM database"
673 ctx
.local_samdb
.transaction_cancel()
676 ctx
.local_samdb
.transaction_commit()
678 def send_DsReplicaUpdateRefs(ctx
, dn
):
679 r
= drsuapi
.DsReplicaUpdateRefsRequest1()
680 r
.naming_context
= drsuapi
.DsReplicaObjectIdentifier()
681 r
.naming_context
.dn
= str(dn
)
682 r
.naming_context
.guid
= misc
.GUID("00000000-0000-0000-0000-000000000000")
683 r
.naming_context
.sid
= security
.dom_sid("S-0-0")
684 r
.dest_dsa_guid
= ctx
.ntds_guid
685 r
.dest_dsa_dns_name
= "%s._msdcs.%s" % (str(ctx
.ntds_guid
), ctx
.dnsforest
)
686 r
.options
= drsuapi
.DRSUAPI_DRS_ADD_REF | drsuapi
.DRSUAPI_DRS_DEL_REF
688 r
.options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
691 ctx
.drsuapi
.DsReplicaUpdateRefs(ctx
.drsuapi_handle
, 1, r
)
693 def join_finalise(ctx
):
694 '''finalise the join, mark us synchronised and setup secrets db'''
696 print "Sending DsReplicateUpdateRefs for all the partitions"
697 ctx
.send_DsReplicaUpdateRefs(ctx
.schema_dn
)
698 ctx
.send_DsReplicaUpdateRefs(ctx
.config_dn
)
699 ctx
.send_DsReplicaUpdateRefs(ctx
.base_dn
)
701 print "Setting isSynchronized and dsServiceName"
703 m
.dn
= ldb
.Dn(ctx
.local_samdb
, '@ROOTDSE')
704 m
["isSynchronized"] = ldb
.MessageElement("TRUE", ldb
.FLAG_MOD_REPLACE
, "isSynchronized")
705 m
["dsServiceName"] = ldb
.MessageElement("<GUID=%s>" % str(ctx
.ntds_guid
),
706 ldb
.FLAG_MOD_REPLACE
, "dsServiceName")
707 ctx
.local_samdb
.modify(m
)
712 secrets_ldb
= Ldb(ctx
.paths
.secrets
, session_info
=system_session(), lp
=ctx
.lp
)
714 print "Setting up secrets database"
715 secretsdb_self_join(secrets_ldb
, domain
=ctx
.domain_name
,
717 dnsdomain
=ctx
.dnsdomain
,
718 netbiosname
=ctx
.myname
,
719 domainsid
=security
.dom_sid(ctx
.domsid
),
720 machinepass
=ctx
.acct_pass
,
721 secure_channel_type
=ctx
.secure_channel_type
,
722 key_version_number
=ctx
.key_version_number
)
724 def join_setup_trusts(ctx
):
725 '''provision the local SAM'''
727 def arcfour_encrypt(key
, data
):
728 from Crypto
.Cipher
import ARC4
730 return c
.encrypt(data
)
732 def string_to_array(string
):
733 blob
= [0] * len(string
)
735 for i
in range(len(string
)):
736 blob
[i
] = ord(string
[i
])
740 print "Setup domain trusts with server %s" % ctx
.server
741 binding_options
= "" # why doesn't signing work gere? w2k8r2 claims no session key
742 lsaconn
= lsa
.lsarpc("ncacn_np:%s[%s]" % (ctx
.server
, binding_options
),
745 objectAttr
= lsa
.ObjectAttribute()
746 objectAttr
.sec_qos
= lsa
.QosInfo()
748 pol_handle
= lsaconn
.OpenPolicy2(''.decode('utf-8'),
749 objectAttr
, security
.SEC_FLAG_MAXIMUM_ALLOWED
)
751 info
= lsa
.TrustDomainInfoInfoEx()
752 info
.domain_name
.string
= ctx
.dnsdomain
753 info
.netbios_name
.string
= ctx
.domain_name
754 info
.sid
= security
.dom_sid(ctx
.domsid
)
755 info
.trust_direction
= lsa
.LSA_TRUST_DIRECTION_INBOUND | lsa
.LSA_TRUST_DIRECTION_OUTBOUND
756 info
.trust_type
= lsa
.LSA_TRUST_TYPE_UPLEVEL
757 info
.trust_attributes
= lsa
.LSA_TRUST_ATTRIBUTE_WITHIN_FOREST
760 oldname
= lsa
.String()
761 oldname
.string
= ctx
.dnsdomain
762 oldinfo
= lsaconn
.QueryTrustedDomainInfoByName(pol_handle
, oldname
,
763 lsa
.LSA_TRUSTED_DOMAIN_INFO_FULL_INFO
)
764 print("Removing old trust record for %s (SID %s)" % (ctx
.dnsdomain
, oldinfo
.info_ex
.sid
))
765 lsaconn
.DeleteTrustedDomain(pol_handle
, oldinfo
.info_ex
.sid
)
769 password_blob
= string_to_array(ctx
.trustdom_pass
.encode('utf-16-le'))
771 clear_value
= drsblobs
.AuthInfoClear()
772 clear_value
.size
= len(password_blob
)
773 clear_value
.password
= password_blob
775 clear_authentication_information
= drsblobs
.AuthenticationInformation()
776 clear_authentication_information
.LastUpdateTime
= samba
.unix2nttime(int(time
.time()))
777 clear_authentication_information
.AuthType
= lsa
.TRUST_AUTH_TYPE_CLEAR
778 clear_authentication_information
.AuthInfo
= clear_value
780 authentication_information_array
= drsblobs
.AuthenticationInformationArray()
781 authentication_information_array
.count
= 1
782 authentication_information_array
.array
= [clear_authentication_information
]
784 outgoing
= drsblobs
.trustAuthInOutBlob()
786 outgoing
.current
= authentication_information_array
788 trustpass
= drsblobs
.trustDomainPasswords()
789 confounder
= [3] * 512
792 confounder
[i
] = random
.randint(0, 255)
794 trustpass
.confounder
= confounder
796 trustpass
.outgoing
= outgoing
797 trustpass
.incoming
= outgoing
799 trustpass_blob
= ndr_pack(trustpass
)
801 encrypted_trustpass
= arcfour_encrypt(lsaconn
.session_key
, trustpass_blob
)
803 auth_blob
= lsa
.DATA_BUF2()
804 auth_blob
.size
= len(encrypted_trustpass
)
805 auth_blob
.data
= string_to_array(encrypted_trustpass
)
807 auth_info
= lsa
.TrustDomainInfoAuthInfoInternal()
808 auth_info
.auth_blob
= auth_blob
810 trustdom_handle
= lsaconn
.CreateTrustedDomainEx2(pol_handle
,
813 security
.SEC_STD_DELETE
)
816 "dn" : "cn=%s,cn=system,%s" % (ctx
.dnsforest
, ctx
.base_dn
),
817 "objectclass" : "trustedDomain",
818 "trustType" : str(info
.trust_type
),
819 "trustAttributes" : str(info
.trust_attributes
),
820 "trustDirection" : str(info
.trust_direction
),
821 "flatname" : ctx
.forest_domain_name
,
822 "trustPartner" : ctx
.dnsforest
,
823 "trustAuthIncoming" : ndr_pack(outgoing
),
824 "trustAuthOutgoing" : ndr_pack(outgoing
)
826 ctx
.local_samdb
.add(rec
)
829 "dn" : "cn=%s$,cn=users,%s" % (ctx
.forest_domain_name
, ctx
.base_dn
),
830 "objectclass" : "user",
831 "userAccountControl" : str(samba
.dsdb
.UF_INTERDOMAIN_TRUST_ACCOUNT
),
832 "clearTextPassword" : ctx
.trustdom_pass
.encode('utf-16-le')
834 ctx
.local_samdb
.add(rec
)
838 ctx
.cleanup_old_join()
840 ctx
.join_add_objects()
844 ctx
.join_add_objects2()
845 ctx
.join_provision_own_domain()
846 ctx
.join_setup_trusts()
849 print "Join failed - cleaning up"
850 ctx
.cleanup_old_join()
854 def join_RODC(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
855 targetdir
=None, domain
=None, domain_critical_only
=False):
858 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
)
860 lp
.set("workgroup", ctx
.domain_name
)
861 print("workgroup is %s" % ctx
.domain_name
)
863 lp
.set("realm", ctx
.realm
)
864 print("realm is %s" % ctx
.realm
)
866 ctx
.krbtgt_dn
= "CN=krbtgt_%s,CN=Users,%s" % (ctx
.myname
, ctx
.base_dn
)
868 # setup some defaults for accounts that should be replicated to this RODC
869 ctx
.never_reveal_sid
= [ "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_DENY
),
870 "<SID=%s>" % security
.SID_BUILTIN_ADMINISTRATORS
,
871 "<SID=%s>" % security
.SID_BUILTIN_SERVER_OPERATORS
,
872 "<SID=%s>" % security
.SID_BUILTIN_BACKUP_OPERATORS
,
873 "<SID=%s>" % security
.SID_BUILTIN_ACCOUNT_OPERATORS
]
874 ctx
.reveal_sid
= "<SID=%s-%s>" % (ctx
.domsid
, security
.DOMAIN_RID_RODC_ALLOW
)
876 mysid
= ctx
.get_mysid()
877 admin_dn
= "<SID=%s>" % mysid
878 ctx
.managedby
= admin_dn
880 ctx
.userAccountControl
= (samba
.dsdb
.UF_WORKSTATION_TRUST_ACCOUNT |
881 samba
.dsdb
.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
882 samba
.dsdb
.UF_PARTIAL_SECRETS_ACCOUNT
)
884 ctx
.SPNs
.extend([ "RestrictedKrbHost/%s" % ctx
.myname
,
885 "RestrictedKrbHost/%s" % ctx
.dnshostname
])
887 ctx
.connection_dn
= "CN=RODC Connection (FRS),%s" % ctx
.ntds_dn
888 ctx
.secure_channel_type
= misc
.SEC_CHAN_RODC
890 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_INIT_SYNC |
891 drsuapi
.DRSUAPI_DRS_PER_SYNC |
892 drsuapi
.DRSUAPI_DRS_GET_ANC |
893 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED |
894 drsuapi
.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING |
895 drsuapi
.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP
)
896 ctx
.domain_replica_flags
= ctx
.replica_flags
897 if domain_critical_only
:
898 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
903 print "Joined domain %s (SID %s) as an RODC" % (ctx
.domain_name
, ctx
.domsid
)
906 def join_DC(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
907 targetdir
=None, domain
=None, domain_critical_only
=False):
909 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, domain
)
911 lp
.set("workgroup", ctx
.domain_name
)
912 print("workgroup is %s" % ctx
.domain_name
)
914 lp
.set("realm", ctx
.realm
)
915 print("realm is %s" % ctx
.realm
)
917 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
919 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
920 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
922 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
923 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
924 drsuapi
.DRSUAPI_DRS_PER_SYNC |
925 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
926 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
927 ctx
.domain_replica_flags
= ctx
.replica_flags
928 if domain_critical_only
:
929 ctx
.domain_replica_flags |
= drsuapi
.DRSUAPI_DRS_CRITICAL_ONLY
932 print "Joined domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
)
934 def join_subdomain(server
=None, creds
=None, lp
=None, site
=None, netbios_name
=None,
935 targetdir
=None, parent_domain
=None, dnsdomain
=None, netbios_domain
=None):
937 ctx
= dc_join(server
, creds
, lp
, site
, netbios_name
, targetdir
, parent_domain
)
939 ctx
.parent_domain_name
= ctx
.domain_name
940 ctx
.domain_name
= netbios_domain
941 ctx
.realm
= dnsdomain
942 ctx
.parent_dnsdomain
= ctx
.dnsdomain
943 ctx
.parent_partition_dn
= ctx
.get_parent_partition_dn()
944 ctx
.dnsdomain
= dnsdomain
945 ctx
.partition_dn
= "CN=%s,CN=Partitions,%s" % (ctx
.domain_name
, ctx
.config_dn
)
946 ctx
.naming_master
= ctx
.get_naming_master()
947 if ctx
.naming_master
!= ctx
.server
:
948 print("Reconnecting to naming master %s" % ctx
.naming_master
)
949 ctx
.server
= ctx
.naming_master
950 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
951 session_info
=system_session(),
952 credentials
=ctx
.creds
, lp
=ctx
.lp
)
954 ctx
.base_dn
= samba
.dn_from_dns_name(dnsdomain
)
955 ctx
.domsid
= str(security
.random_sid())
957 ctx
.dnshostname
= "%s.%s" % (ctx
.myname
, ctx
.dnsdomain
)
958 ctx
.trustdom_pass
= samba
.generate_random_password(128, 128)
960 ctx
.userAccountControl
= samba
.dsdb
.UF_SERVER_TRUST_ACCOUNT | samba
.dsdb
.UF_TRUSTED_FOR_DELEGATION
962 ctx
.SPNs
.append('E3514235-4B06-11D1-AB04-00C04FC2DCD2/$NTDSGUID/%s' % ctx
.dnsdomain
)
963 ctx
.secure_channel_type
= misc
.SEC_CHAN_BDC
965 ctx
.replica_flags
= (drsuapi
.DRSUAPI_DRS_WRIT_REP |
966 drsuapi
.DRSUAPI_DRS_INIT_SYNC |
967 drsuapi
.DRSUAPI_DRS_PER_SYNC |
968 drsuapi
.DRSUAPI_DRS_FULL_SYNC_IN_PROGRESS |
969 drsuapi
.DRSUAPI_DRS_NEVER_SYNCED
)
970 ctx
.domain_replica_flags
= ctx
.replica_flags
973 print "Created domain %s (SID %s) as a DC" % (ctx
.domain_name
, ctx
.domsid
)