1 # rodc related commands
3 # Copyright Andrew Tridgell 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 from samba.netcmd import Command, CommandError, Option, SuperCommand
20 import samba.getopt as options
21 from samba.samdb import SamDB
22 from samba.auth import system_session
24 from samba.dcerpc import misc, drsuapi
25 from samba.drs_utils import drs_Replicate
29 class RODCException(Exception):
30 def __init__(self, value):
34 return "%s: %s" % (self.__class__.__name__, self.value)
37 class NamingError(RODCException):
41 class ReplicationError(RODCException):
45 class cmd_rodc_preload(Command):
46 """Preload accounts for an RODC. Multiple accounts may be requested."""
48 synopsis = "%prog (<SID>|<DN>|<accountname>)+ ... [options]"
50 takes_optiongroups = {
51 "sambaopts": options.SambaOptions,
52 "versionopts": options.VersionOptions,
53 "credopts": options.CredentialsOptions,
57 Option("--server", help="DC to use", type=str),
58 Option("--file", help="Read account list from a file, or - for stdin (one per line)", type=str),
59 Option("--ignore-errors", help="When preloading multiple accounts, skip any failing accounts", action="store_true"),
62 takes_args = ["account*"]
64 def get_dn(self, samdb, account):
65 '''work out what DN they meant'''
67 # we accept the account in SID, accountname or DN form
68 if account[0:2] == 'S-':
69 res = samdb.search(base="<SID=%s>" % account,
70 expression="objectclass=user",
71 scope=ldb.SCOPE_BASE, attrs=[])
72 elif account.find('=') >= 0:
73 res = samdb.search(base=account,
74 expression="objectclass=user",
75 scope=ldb.SCOPE_BASE, attrs=[])
77 res = samdb.search(expression="(&(samAccountName=%s)(objectclass=user))" % ldb.binary_encode(account),
78 scope=ldb.SCOPE_SUBTREE, attrs=[])
80 raise NamingError("Failed to find account '%s'" % account)
81 return str(res[0]["dn"])
83 def run(self, *accounts, **kwargs):
84 sambaopts = kwargs.get("sambaopts")
85 credopts = kwargs.get("credopts")
86 versionpts = kwargs.get("versionopts")
87 server = kwargs.get("server")
88 accounts_file = kwargs.get("file")
89 ignore_errors = kwargs.get("ignore_errors")
92 raise Exception("You must supply a server")
94 if accounts_file is not None:
96 if accounts_file == "-":
97 for line in sys.stdin:
98 accounts.append(line.strip())
100 for line in open(accounts_file, 'r'):
101 accounts.append(line.strip())
103 lp = sambaopts.get_loadparm()
105 creds = credopts.get_credentials(lp, fallback_machine=True)
107 # connect to the remote and local SAMs
108 samdb = SamDB(url="ldap://%s" % server,
109 session_info=system_session(),
110 credentials=creds, lp=lp)
112 local_samdb = SamDB(url=None, session_info=system_session(),
113 credentials=creds, lp=lp)
115 destination_dsa_guid = misc.GUID(local_samdb.get_ntds_GUID())
117 binding_options = "seal"
118 if lp.log_level() >= 9:
119 binding_options += ",print"
120 repl = drs_Replicate("ncacn_ip_tcp:%s[%s]" % (server, binding_options),
122 local_samdb, destination_dsa_guid)
125 for account in accounts:
126 # work out the source and destination GUIDs
127 dc_ntds_dn = samdb.get_dsServiceName()
128 res = samdb.search(base=dc_ntds_dn, scope=ldb.SCOPE_BASE, attrs=["invocationId"])
129 source_dsa_invocation_id = misc.GUID(local_samdb.schema_format_value("objectGUID", res[0]["invocationId"][0]))
132 dn = self.get_dn(samdb, account)
133 except RODCException as e:
134 if not ignore_errors:
135 raise CommandError(str(e))
139 self.outf.write("Replicating DN %s\n" % dn)
141 local_samdb.transaction_start()
143 repl.replicate(dn, source_dsa_invocation_id, destination_dsa_guid,
144 exop=drsuapi.DRSUAPI_EXOP_REPL_SECRET, rodc=True)
145 except Exception as e:
146 local_samdb.transaction_cancel()
147 if not ignore_errors:
148 raise CommandError("Error replicating DN %s" % dn)
149 errors.append(ReplicationError("Error replicating DN %s" % dn))
152 local_samdb.transaction_commit()
155 self.message("\nPreload encountered problematic users:")
157 self.message(" %s" % error)
160 class cmd_rodc(SuperCommand):
161 """Read-Only Domain Controller (RODC) management."""
164 subcommands["preload"] = cmd_rodc_preload()