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 import samba.getopt as options
22 from samba.auth import system_session
23 from samba.samdb import SamDB
24 from samba import gensec, Ldb
25 import ldb, samba, sys
26 from samba.ndr import ndr_pack, ndr_unpack, ndr_print
27 from samba.dcerpc import security
28 from samba.dcerpc import drsuapi, misc, netlogon
29 from samba.credentials import Credentials, DONT_USE_KERBEROS
30 from samba.provision import secretsdb_self_join, provision, FILL_DRS, find_setup_dir
31 from samba.net import Net
34 # this makes debugging easier
35 samba.talloc_enable_null_tracking()
38 '''hold join context variables'''
41 def join_rodc(server=None, creds=None, lp=None, site=None, netbios_name=None,
46 raise Exception("You must supply a server for a RODC join")
48 def del_noerror(samdb, dn):
51 print "Deleted %s" % dn
55 def cleanup_old_join(ctx):
56 '''remove any DNs from a previous join'''
58 # find the krbtgt link
59 res = ctx.samdb.search(base=ctx.acct_dn, scope=ldb.SCOPE_BASE, attrs=["msDS-krbTgtLink"])
60 del_noerror(ctx.samdb, ctx.acct_dn)
61 del_noerror(ctx.samdb, ctx.connection_dn)
62 del_noerror(ctx.samdb, ctx.krbtgt_dn)
63 del_noerror(ctx.samdb, ctx.ntds_dn)
64 del_noerror(ctx.samdb, ctx.server_dn)
65 del_noerror(ctx.samdb, ctx.topology_dn)
66 ctx.new_krbtgt_dn = res[0]["msDS-Krbtgtlink"][0]
67 del_noerror(ctx.samdb, ctx.new_krbtgt_dn)
71 def get_dsServiceName(samdb):
72 res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
73 return res[0]["dsServiceName"][0]
75 def get_dnsHostName(samdb):
76 res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
77 return res[0]["dnsHostName"][0]
80 res = samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["tokenGroups"])
81 binsid = res[0]["tokenGroups"][0]
82 return samdb.schema_format_value("objectSID", binsid)
84 def get_domain_name(samdb):
85 # this should be done via CLDAP
86 res = samdb.search(base=samdb.get_default_basedn(), scope=ldb.SCOPE_BASE, attrs=["name"])
87 return res[0]["name"][0]
90 '''make a DsBind call, returning the binding handle'''
91 bind_info = drsuapi.DsBindInfoCtr()
93 bind_info.info = drsuapi.DsBindInfo28()
94 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_BASE;
95 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION;
96 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI;
97 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2;
98 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS;
99 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1;
100 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION;
101 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE;
102 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2;
103 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION;
104 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2;
105 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD;
106 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND;
107 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO;
108 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION;
109 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01;
110 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP;
111 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY;
112 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3;
113 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2;
114 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6;
115 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS;
116 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8;
117 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5;
118 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6;
119 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3;
120 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7;
121 bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT;
122 (info, handle) = drs.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
125 def get_rodc_partial_attribute_set(ctx):
126 '''get a list of attributes for RODC replication'''
127 partial_attribute_set = drsuapi.DsPartialAttributeSet()
128 partial_attribute_set.version = 1
132 # the exact list of attids we send is quite critical. Note that
133 # we do ask for the secret attributes, but set set SPECIAL_SECRET_PROCESSING
135 res = ctx.local_samdb.search(base=ctx.schema_dn, scope=ldb.SCOPE_SUBTREE,
136 expression="objectClass=attributeSchema",
137 attrs=["lDAPDisplayName", "systemFlags",
141 ldap_display_name = r["lDAPDisplayName"][0]
142 if "systemFlags" in r:
143 system_flags = r["systemFlags"][0]
144 if (int(system_flags) & (samba.dsdb.DS_FLAG_ATTR_NOT_REPLICATED |
145 samba.dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED)):
147 search_flags = r["searchFlags"][0]
148 if (int(search_flags) & samba.dsdb.SEARCH_FLAG_RODC_ATTRIBUTE):
150 attid = ctx.local_samdb.get_attid_from_lDAPDisplayName(ldap_display_name)
151 ctx.attids.append(int(attid))
153 # the attids do need to be sorted, or windows doesn't return
154 # all the attributes we need
156 partial_attribute_set.attids = ctx.attids
157 partial_attribute_set.num_attids = len(ctx.attids)
158 return partial_attribute_set
161 def replicate_partition(ctx, dn, schema=False, exop=drsuapi.DRSUAPI_EXOP_NONE):
162 '''replicate a partition'''
164 # setup for a GetNCChanges call
165 req8 = drsuapi.DsGetNCChangesRequest8()
167 req8.destination_dsa_guid = ctx.ntds_guid
168 req8.source_dsa_invocation_id = misc.GUID(ctx.samdb.get_invocation_id())
169 req8.naming_context = drsuapi.DsReplicaObjectIdentifier()
170 req8.naming_context.dn = dn.decode("utf-8")
171 req8.highwatermark = drsuapi.DsReplicaHighWaterMark()
172 req8.highwatermark.tmp_highest_usn = 0
173 req8.highwatermark.reserved_usn = 0
174 req8.highwatermark.highest_usn = 0
175 req8.uptodateness_vector = None
176 if exop == drsuapi.DRSUAPI_EXOP_REPL_SECRET:
177 req8.replica_flags = 0
179 req8.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
180 drsuapi.DRSUAPI_DRS_PER_SYNC |
181 drsuapi.DRSUAPI_DRS_GET_ANC |
182 drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
183 drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING)
184 req8.max_object_count = 402
185 req8.max_ndr_size = 402116
186 req8.extended_op = exop
188 req8.partial_attribute_set = None
189 req8.partial_attribute_set_ex = None
190 req8.mapping_ctr.num_mappings = 0
191 req8.mapping_ctr.mappings = None
194 req8.partial_attribute_set = get_rodc_partial_attribute_set(ctx)
197 (level, ctr) = ctx.drs.DsGetNCChanges(ctx.drs_handle, 8, req8)
198 ctx.net.replicate_chunk(ctx.replication_state, level, ctr, schema=schema)
199 if ctr.more_data == 0:
201 req8.highwatermark.tmp_highest_usn = ctr.new_highwatermark.tmp_highest_usn
204 def join_add_objects(ctx):
205 '''add the various objects needed for the join'''
206 print "Adding %s" % ctx.acct_dn
209 "objectClass": "computer",
210 "displayname": ctx.samname,
211 "samaccountname" : ctx.samname,
212 "useraccountcontrol" : str(samba.dsdb.UF_WORKSTATION_TRUST_ACCOUNT |
213 samba.dsdb.UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION |
214 samba.dsdb.UF_PARTIAL_SECRETS_ACCOUNT),
215 "managedby" : ctx.admin_dn,
216 "dnshostname" : ctx.dnshostname,
217 "msDS-NeverRevealGroup" : ctx.never_reveal_sid,
218 "msDS-RevealOnDemandGroup" : ctx.reveal_sid}
221 print "Adding %s" % ctx.krbtgt_dn
223 "dn" : ctx.krbtgt_dn,
224 "objectclass" : "user",
225 "useraccountcontrol" : str(samba.dsdb.UF_NORMAL_ACCOUNT |
226 samba.dsdb.UF_ACCOUNTDISABLE),
227 "showinadvancedviewonly" : "TRUE",
228 "description" : "tricky account"}
229 ctx.samdb.add(rec, ["rodc_join:1:1"])
231 # now we need to search for the samAccountName attribute on the krbtgt DN,
232 # as this will have been magically set to the krbtgt number
233 res = ctx.samdb.search(base=ctx.krbtgt_dn, scope=ldb.SCOPE_BASE, attrs=["samAccountName"])
234 ctx.krbtgt_name = res[0]["samAccountName"][0]
236 print "Got krbtgt_name=%s" % ctx.krbtgt_name
239 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
240 m["msDS-krbTgtLink"] = ldb.MessageElement(ctx.krbtgt_dn,
241 ldb.FLAG_MOD_REPLACE, "msDS-krbTgtLink")
244 ctx.new_krbtgt_dn = "CN=%s,CN=Users,%s" % (ctx.krbtgt_name, ctx.base_dn)
245 print "Renaming %s to %s" % (ctx.krbtgt_dn, ctx.new_krbtgt_dn)
246 ctx.samdb.rename(ctx.krbtgt_dn, ctx.new_krbtgt_dn)
248 print "Adding %s" % ctx.server_dn
251 "objectclass" : "server",
252 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_RENAME |
253 samba.dsdb.SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE |
254 samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
255 "serverReference" : ctx.acct_dn,
256 "dnsHostName" : ctx.dnshostname}
259 print "Adding %s" % ctx.ntds_dn
262 "objectclass" : "nTDSDSA",
263 "objectCategory" : "CN=NTDS-DSA-RO,%s" % ctx.schema_dn,
264 "systemFlags" : str(samba.dsdb.SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE),
265 "dMDLocation" : ctx.schema_dn,
267 "msDS-Behavior-Version" : "4",
268 "msDS-HasDomainNCs" : ctx.base_dn,
269 "msDS-HasFullReplicaNCs" : [ ctx.base_dn, ctx.config_dn, ctx.schema_dn ]}
270 ctx.samdb.add(rec, ["rodc_join:1:1"])
272 # find the GUID of our NTDS DN
273 res = ctx.samdb.search(base=ctx.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
274 ctx.ntds_guid = misc.GUID(ctx.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
276 print "Adding %s" % ctx.connection_dn
278 "dn" : ctx.connection_dn,
279 "objectclass" : "nTDSConnection",
280 "enabledconnection" : "TRUE",
282 "fromServer" : ctx.dc_ntds_dn}
285 print "Adding %s" % ctx.topology_dn
287 "dn" : ctx.topology_dn,
288 "objectclass" : "msDFSR-Member",
289 "msDFSR-ComputerReference" : ctx.acct_dn,
290 "serverReference" : ctx.ntds_dn}
293 print "Adding HOST SPNs to %s" % ctx.acct_dn
295 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
296 SPNs = [ "HOST/%s" % ctx.myname,
297 "HOST/%s" % ctx.dnshostname ]
298 m["servicePrincipalName"] = ldb.MessageElement(SPNs,
300 "servicePrincipalName")
303 print "Adding RestrictedKrbHost SPNs to %s" % ctx.acct_dn
305 m.dn = ldb.Dn(ctx.samdb, ctx.acct_dn)
306 SPNs = [ "RestrictedKrbHost/%s" % ctx.myname,
307 "RestrictedKrbHost/%s" % ctx.dnshostname ]
308 m["servicePrincipalName"] = ldb.MessageElement(SPNs,
310 "servicePrincipalName")
313 print "Setting account password for %s" % ctx.samname
314 ctx.samdb.setpassword("(&(objectClass=user)(sAMAccountName=%s))" % ctx.samname,
316 force_change_at_next_login=False,
317 username=ctx.samname)
320 def join_drs_connect(ctx):
321 '''connect to DRSUAPI'''
322 print "Doing DsBind as %s" % ctx.samname
323 ctx.acct_creds = Credentials()
324 ctx.acct_creds.guess(ctx.lp)
325 ctx.acct_creds.set_kerberos_state(DONT_USE_KERBEROS)
326 ctx.acct_creds.set_username(ctx.samname)
327 ctx.acct_creds.set_password(ctx.acct_pass)
329 ctx.drs = drsuapi.drsuapi("ncacn_ip_tcp:%s[seal,print]" % ctx.server, ctx.lp, ctx.acct_creds)
330 ctx.drs_handle = do_DsBind(ctx.drs)
333 def join_provision(ctx):
334 '''provision the local SAM'''
336 print "Calling bare provision"
338 setup_dir = find_setup_dir()
339 logger = logging.getLogger("provision")
340 logger.addHandler(logging.StreamHandler(sys.stdout))
341 smbconf = lp.configfile
343 presult = provision(setup_dir, logger, system_session(), None,
344 smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS,
345 realm=ctx.realm, rootdn=ctx.root_dn, domaindn=ctx.base_dn,
346 schemadn=ctx.schema_dn,
347 configdn=ctx.config_dn,
348 serverdn=ctx.server_dn, domain=ctx.domain_name,
349 hostname=ctx.myname, hostip="127.0.0.1", domainsid=ctx.domsid,
350 machinepass=ctx.acct_pass, serverrole="domain controller",
352 print "Provision OK for domain DN %s" % presult.domaindn
353 ctx.local_samdb = presult.samdb
355 ctx.paths = presult.paths
358 def join_replicate(ctx):
359 '''replicate the SAM'''
361 print "Starting replication"
362 ctx.local_samdb.transaction_start()
364 ctx.replication_state = ctx.net.replicate_init(ctx.local_samdb, ctx.lp, ctx.drs)
366 replicate_partition(ctx, ctx.schema_dn, schema=True)
367 replicate_partition(ctx, ctx.config_dn)
368 replicate_partition(ctx, ctx.base_dn)
369 replicate_partition(ctx, ctx.acct_dn, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET)
370 replicate_partition(ctx, ctx.new_krbtgt_dn, exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET)
372 print "Committing SAM database"
373 ctx.local_samdb.transaction_commit()
376 def join_finalise(ctx):
377 '''finalise the join, mark us synchronised and setup secrets db'''
379 print "Setting isSynchronized"
381 m.dn = ldb.Dn(ctx.samdb, '@ROOTDSE')
382 m["isSynchronized"] = ldb.MessageElement("TRUE", ldb.FLAG_MOD_REPLACE, "isSynchronized")
385 secrets_ldb = Ldb(ctx.paths.secrets, session_info=system_session(), lp=ctx.lp)
387 print "Setting up secrets database"
388 secretsdb_self_join(secrets_ldb, domain=ctx.domain_name,
390 dnsdomain=ctx.dnsdomain,
391 netbiosname=ctx.myname,
392 domainsid=security.dom_sid(ctx.domsid),
393 machinepass=ctx.acct_pass,
394 secure_channel_type=misc.SEC_CHAN_RODC)
403 ctx.netbios_name = netbios_name
404 ctx.targetdir = targetdir
407 ctx.creds.set_gensec_features(creds.get_gensec_features() | gensec.FEATURE_SEAL)
409 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
410 session_info=system_session(),
411 credentials=ctx.creds, lp=ctx.lp)
412 ctx.net = Net(creds=ctx.creds, lp=ctx.lp)
414 ctx.myname = netbios_name
415 ctx.samname = "%s$" % ctx.myname
416 ctx.base_dn = str(ctx.samdb.get_default_basedn())
417 ctx.root_dn = str(ctx.samdb.get_root_basedn())
418 ctx.schema_dn = str(ctx.samdb.get_schema_basedn())
419 ctx.config_dn = str(ctx.samdb.get_config_basedn())
420 ctx.domsid = ctx.samdb.get_domain_sid()
421 ctx.domain_name = get_domain_name(ctx.samdb)
423 ctx.dc_ntds_dn = get_dsServiceName(ctx.samdb)
424 ctx.dc_dnsHostName = get_dnsHostName(ctx.samdb)
425 ctx.acct_pass = samba.generate_random_password(12, 32)
426 ctx.mysid = get_mysid(ctx.samdb)
428 # work out the DNs of all the objects we will be adding
429 ctx.admin_dn = "<SID=%s>" % ctx.mysid
430 ctx.krbtgt_dn = "CN=krbtgt_%s,CN=Users,%s" % (ctx.myname, ctx.base_dn)
431 ctx.server_dn = "CN=%s,CN=Servers,CN=%s,CN=Sites,%s" % (ctx.myname, ctx.site, ctx.config_dn)
432 ctx.ntds_dn = "CN=NTDS Settings,%s" % ctx.server_dn
433 ctx.connection_dn = "CN=RODC Connection (FRS),%s" % ctx.ntds_dn
434 ctx.topology_dn = "CN=%s,CN=Topology,CN=Domain System Volume,CN=DFSR-GlobalSettings,CN=System,%s" % (ctx.myname, ctx.base_dn)
436 # setup some defaults for accounts that should be replicated to this RODC
437 ctx.never_reveal_sid = [ "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_DENY),
438 "<SID=%s>" % security.SID_BUILTIN_ADMINISTRATORS,
439 "<SID=%s>" % security.SID_BUILTIN_SERVER_OPERATORS,
440 "<SID=%s>" % security.SID_BUILTIN_BACKUP_OPERATORS,
441 "<SID=%s>" % security.SID_BUILTIN_ACCOUNT_OPERATORS ]
442 ctx.reveal_sid = "<SID=%s-%s>" % (ctx.domsid, security.DOMAIN_RID_RODC_ALLOW)
444 ctx.dnsdomain = ldb.Dn(ctx.samdb, ctx.base_dn).canonical_str().split('/')[0]
445 ctx.realm = ctx.dnsdomain
446 ctx.dnshostname = "%s.%s" % (ctx.myname, ctx.dnsdomain)
448 ctx.acct_dn = "CN=%s,OU=Domain Controllers,%s" % (ctx.myname, ctx.base_dn)
450 cleanup_old_join(ctx)
452 join_add_objects(ctx)
453 join_drs_connect(ctx)
458 print "Join failed - cleaning up"
459 cleanup_old_join(ctx)
462 print "Joined domain %s (SID %s) as an RODC" % (ctx.domain_name, ctx.domsid)