4006a41eb0d3b2a76e0e9dcc30ca9d60b932e9c7
[ira/wip.git] / source4 / scripting / python / samba / netcmd / domain.py
1 #!/usr/bin/env python
2 #
3 # domain management
4 #
5 # Copyright Matthias Dieter Wallnoefer 2009
6 # Copyright Andrew Kroeger 2009
7 # Copyright Jelmer Vernooij 2009
8 # Copyright Giampaolo Lauria 2011
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23
24
25
26 import samba.getopt as options
27 import ldb
28 import os
29 import tempfile
30 import logging
31 from samba import Ldb
32 from samba.net import Net, LIBNET_JOIN_AUTOMATIC
33 import samba.ntacls
34 from samba.join import join_RODC, join_DC, join_subdomain
35 from samba.auth import system_session
36 from samba.samdb import SamDB
37 from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX, DOMAIN_PASSWORD_STORE_CLEARTEXT
38 from samba.netcmd import (
39     Command,
40     CommandError,
41     SuperCommand,
42     Option
43     )
44 from samba.netcmd.common import netcmd_get_domain_infos_via_cldap
45 from samba.samba3 import Samba3
46 from samba.samba3 import param as s3param
47 from samba.upgrade import upgrade_from_samba3
48
49 from samba.dsdb import (
50     DS_DOMAIN_FUNCTION_2000,
51     DS_DOMAIN_FUNCTION_2003,
52     DS_DOMAIN_FUNCTION_2003_MIXED,
53     DS_DOMAIN_FUNCTION_2008,
54     DS_DOMAIN_FUNCTION_2008_R2,
55     )
56
57 def get_testparm_var(testparm, smbconf, varname):
58     cmd = "%s -s -l --parameter-name='%s' %s 2>/dev/null" % (testparm, varname, smbconf)
59     output = os.popen(cmd, 'r').readline()
60     return output.strip()
61
62
63 class cmd_domain_export_keytab(Command):
64     """Dumps kerberos keys of the domain into a keytab"""
65
66     synopsis = "%prog <keytab> [options]"
67
68     takes_options = [
69         ]
70
71     takes_args = ["keytab"]
72
73     def run(self, keytab, credopts=None, sambaopts=None, versionopts=None):
74         lp = sambaopts.get_loadparm()
75         net = Net(None, lp, server=credopts.ipaddress)
76         net.export_keytab(keytab=keytab)
77
78 class cmd_domain_info(Command):
79     """Print basic info about a domain and the DC passed as parameter"""
80
81     synopsis = "%prog domain info <ip_address> [options]"
82
83     takes_options = [
84         ]
85
86     takes_args = ["address"]
87
88     def run(self, address, credopts=None, sambaopts=None, versionopts=None):
89         lp = sambaopts.get_loadparm()
90         res = netcmd_get_domain_infos_via_cldap(lp, None, address)
91         if res:
92             print "Forest           : %s" % res.forest
93             print "Domain           : %s" % res.dns_domain
94             print "Netbios domain   : %s" % res.domain_name
95             print "DC name          : %s" % res.pdc_dns_name
96             print "DC netbios name  : %s" % res.pdc_name
97             print "Server site      : %s" % res.server_site
98             print "Client site      : %s" % res.client_site
99
100
101
102 class cmd_domain_join(Command):
103     """Joins domain as either member or backup domain controller"""
104
105     synopsis = "%prog <dnsdomain> [DC|RODC|MEMBER|SUBDOMAIN] [options]"
106
107     takes_options = [
108         Option("--server", help="DC to join", type=str),
109         Option("--site", help="site to join", type=str),
110         Option("--targetdir", help="where to store provision", type=str),
111         Option("--parent-domain", help="parent domain to create subdomain under", type=str),
112         Option("--domain-critical-only",
113                help="only replicate critical domain objects",
114                action="store_true"),
115         ]
116
117     takes_args = ["domain", "role?"]
118
119     def run(self, domain, role=None, sambaopts=None, credopts=None,
120             versionopts=None, server=None, site=None, targetdir=None,
121             domain_critical_only=False, parent_domain=None):
122         lp = sambaopts.get_loadparm()
123         creds = credopts.get_credentials(lp)
124         net = Net(creds, lp, server=credopts.ipaddress)
125
126         if site is None:
127             site = "Default-First-Site-Name"
128
129         netbios_name = lp.get("netbios name")
130
131         if not role is None:
132             role = role.upper()
133
134         if role is None or role == "MEMBER":
135             (join_password, sid, domain_name) = net.join_member(domain,
136                                                                 netbios_name,
137                                                                 LIBNET_JOIN_AUTOMATIC)
138
139             self.outf.write("Joined domain %s (%s)\n" % (domain_name, sid))
140             return
141         elif role == "DC":
142             join_DC(server=server, creds=creds, lp=lp, domain=domain,
143                     site=site, netbios_name=netbios_name, targetdir=targetdir,
144                     domain_critical_only=domain_critical_only)
145             return
146         elif role == "RODC":
147             join_RODC(server=server, creds=creds, lp=lp, domain=domain,
148                       site=site, netbios_name=netbios_name, targetdir=targetdir,
149                       domain_critical_only=domain_critical_only)
150             return
151         elif role == "SUBDOMAIN":
152             netbios_domain = lp.get("workgroup")
153             if parent_domain is None:
154                 parent_domain = ".".join(domain.split(".")[1:])
155             join_subdomain(server=server, creds=creds, lp=lp, dnsdomain=domain, parent_domain=parent_domain,
156                            site=site, netbios_name=netbios_name, netbios_domain=netbios_domain, targetdir=targetdir)
157             return
158         else:
159             raise CommandError("Invalid role '%s' (possible values: MEMBER, DC, RODC, SUBDOMAIN)" % role)
160
161
162
163 class cmd_domain_level(Command):
164     """Raises domain and forest function levels"""
165
166     synopsis = "%prog (show|raise <options>) [options]"
167
168     takes_options = [
169         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
170                metavar="URL", dest="H"),
171         Option("--quiet", help="Be quiet", action="store_true"),
172         Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2"],
173             help="The forest function level (2003 | 2008 | 2008_R2)"),
174         Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2"],
175             help="The domain function level (2003 | 2008 | 2008_R2)")
176             ]
177
178     takes_args = ["subcommand"]
179
180     def run(self, subcommand, H=None, forest_level=None, domain_level=None,
181             quiet=False, credopts=None, sambaopts=None, versionopts=None):
182         lp = sambaopts.get_loadparm()
183         creds = credopts.get_credentials(lp, fallback_machine=True)
184
185         samdb = SamDB(url=H, session_info=system_session(),
186             credentials=creds, lp=lp)
187
188         domain_dn = samdb.domain_dn()
189
190         res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
191           scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
192         assert len(res_forest) == 1
193
194         res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
195           attrs=["msDS-Behavior-Version", "nTMixedDomain"])
196         assert len(res_domain) == 1
197
198         res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
199           scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
200           attrs=["msDS-Behavior-Version"])
201         assert len(res_dc_s) >= 1
202
203         try:
204             level_forest = int(res_forest[0]["msDS-Behavior-Version"][0])
205             level_domain = int(res_domain[0]["msDS-Behavior-Version"][0])
206             level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0])
207
208             min_level_dc = int(res_dc_s[0]["msDS-Behavior-Version"][0]) # Init value
209             for msg in res_dc_s:
210                 if int(msg["msDS-Behavior-Version"][0]) < min_level_dc:
211                     min_level_dc = int(msg["msDS-Behavior-Version"][0])
212
213             if level_forest < 0 or level_domain < 0:
214                 raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!")
215             if min_level_dc < 0:
216                 raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!")
217             if level_forest > level_domain:
218                 raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!")
219             if level_domain > min_level_dc:
220                 raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!")
221
222         except KeyError:
223             raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!")
224
225         if subcommand == "show":
226             self.message("Domain and forest function level for domain '%s'" % domain_dn)
227             if level_forest == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
228                 self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
229             if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
230                 self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
231             if min_level_dc == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
232                 self.message("\nATTENTION: You run SAMBA 4 on a lowest function level of a DC lower than Windows 2003. This isn't supported! Please step-up or upgrade the concerning DC(s)!")
233
234             self.message("")
235
236             if level_forest == DS_DOMAIN_FUNCTION_2000:
237                 outstr = "2000"
238             elif level_forest == DS_DOMAIN_FUNCTION_2003_MIXED:
239                 outstr = "2003 with mixed domains/interim (NT4 DC support)"
240             elif level_forest == DS_DOMAIN_FUNCTION_2003:
241                 outstr = "2003"
242             elif level_forest == DS_DOMAIN_FUNCTION_2008:
243                 outstr = "2008"
244             elif level_forest == DS_DOMAIN_FUNCTION_2008_R2:
245                 outstr = "2008 R2"
246             else:
247                 outstr = "higher than 2008 R2"
248             self.message("Forest function level: (Windows) " + outstr)
249
250             if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
251                 outstr = "2000 mixed (NT4 DC support)"
252             elif level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed == 0:
253                 outstr = "2000"
254             elif level_domain == DS_DOMAIN_FUNCTION_2003_MIXED:
255                 outstr = "2003 with mixed domains/interim (NT4 DC support)"
256             elif level_domain == DS_DOMAIN_FUNCTION_2003:
257                 outstr = "2003"
258             elif level_domain == DS_DOMAIN_FUNCTION_2008:
259                 outstr = "2008"
260             elif level_domain == DS_DOMAIN_FUNCTION_2008_R2:
261                 outstr = "2008 R2"
262             else:
263                 outstr = "higher than 2008 R2"
264             self.message("Domain function level: (Windows) " + outstr)
265
266             if min_level_dc == DS_DOMAIN_FUNCTION_2000:
267                 outstr = "2000"
268             elif min_level_dc == DS_DOMAIN_FUNCTION_2003:
269                 outstr = "2003"
270             elif min_level_dc == DS_DOMAIN_FUNCTION_2008:
271                 outstr = "2008"
272             elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2:
273                 outstr = "2008 R2"
274             else:
275                 outstr = "higher than 2008 R2"
276             self.message("Lowest function level of a DC: (Windows) " + outstr)
277
278         elif subcommand == "raise":
279             msgs = []
280
281             if domain_level is not None:
282                 if domain_level == "2003":
283                     new_level_domain = DS_DOMAIN_FUNCTION_2003
284                 elif domain_level == "2008":
285                     new_level_domain = DS_DOMAIN_FUNCTION_2008
286                 elif domain_level == "2008_R2":
287                     new_level_domain = DS_DOMAIN_FUNCTION_2008_R2
288
289                 if new_level_domain <= level_domain and level_domain_mixed == 0:
290                     raise CommandError("Domain function level can't be smaller than or equal to the actual one!")
291
292                 if new_level_domain > min_level_dc:
293                     raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")
294
295                 # Deactivate mixed/interim domain support
296                 if level_domain_mixed != 0:
297                     # Directly on the base DN
298                     m = ldb.Message()
299                     m.dn = ldb.Dn(samdb, domain_dn)
300                     m["nTMixedDomain"] = ldb.MessageElement("0",
301                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
302                     samdb.modify(m)
303                     # Under partitions
304                     m = ldb.Message()
305                     m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % ldb.get_config_basedn())
306                     m["nTMixedDomain"] = ldb.MessageElement("0",
307                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
308                     try:
309                         samdb.modify(m)
310                     except ldb.LdbError, (enum, emsg):
311                         if enum != ldb.ERR_UNWILLING_TO_PERFORM:
312                             raise
313
314                 # Directly on the base DN
315                 m = ldb.Message()
316                 m.dn = ldb.Dn(samdb, domain_dn)
317                 m["msDS-Behavior-Version"]= ldb.MessageElement(
318                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
319                             "msDS-Behavior-Version")
320                 samdb.modify(m)
321                 # Under partitions
322                 m = ldb.Message()
323                 m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
324                   + ",CN=Partitions,%s" % ldb.get_config_basedn())
325                 m["msDS-Behavior-Version"]= ldb.MessageElement(
326                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
327                           "msDS-Behavior-Version")
328                 try:
329                     samdb.modify(m)
330                 except ldb.LdbError, (enum, emsg):
331                     if enum != ldb.ERR_UNWILLING_TO_PERFORM:
332                         raise
333
334                 level_domain = new_level_domain
335                 msgs.append("Domain function level changed!")
336
337             if forest_level is not None:
338                 if forest_level == "2003":
339                     new_level_forest = DS_DOMAIN_FUNCTION_2003
340                 elif forest_level == "2008":
341                     new_level_forest = DS_DOMAIN_FUNCTION_2008
342                 elif forest_level == "2008_R2":
343                     new_level_forest = DS_DOMAIN_FUNCTION_2008_R2
344                 if new_level_forest <= level_forest:
345                     raise CommandError("Forest function level can't be smaller than or equal to the actual one!")
346                 if new_level_forest > level_domain:
347                     raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
348                 m = ldb.Message()
349                 m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % ldb.get_config_basedn())
350                 m["msDS-Behavior-Version"]= ldb.MessageElement(
351                   str(new_level_forest), ldb.FLAG_MOD_REPLACE,
352                           "msDS-Behavior-Version")
353                 samdb.modify(m)
354                 msgs.append("Forest function level changed!")
355             msgs.append("All changes applied successfully!")
356             self.message("\n".join(msgs))
357         else:
358             raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand)
359
360
361
362 class cmd_domain_passwordsettings(Command):
363     """Sets password settings
364
365     Password complexity, history length, minimum password length, the minimum
366     and maximum password age) on a Samba4 server.
367     """
368
369     synopsis = "%prog (show|set <options>) [options]"
370
371     takes_options = [
372         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
373                metavar="URL", dest="H"),
374         Option("--quiet", help="Be quiet", action="store_true"),
375         Option("--complexity", type="choice", choices=["on","off","default"],
376           help="The password complexity (on | off | default). Default is 'on'"),
377         Option("--store-plaintext", type="choice", choices=["on","off","default"],
378           help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
379         Option("--history-length",
380           help="The password history length (<integer> | default).  Default is 24.", type=str),
381         Option("--min-pwd-length",
382           help="The minimum password length (<integer> | default).  Default is 7.", type=str),
383         Option("--min-pwd-age",
384           help="The minimum password age (<integer in days> | default).  Default is 1.", type=str),
385         Option("--max-pwd-age",
386           help="The maximum password age (<integer in days> | default).  Default is 43.", type=str),
387           ]
388
389     takes_args = ["subcommand"]
390
391     def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None,
392             quiet=False, complexity=None, store_plaintext=None, history_length=None,
393             min_pwd_length=None, credopts=None, sambaopts=None,
394             versionopts=None):
395         lp = sambaopts.get_loadparm()
396         creds = credopts.get_credentials(lp)
397
398         samdb = SamDB(url=H, session_info=system_session(),
399             credentials=creds, lp=lp)
400
401         domain_dn = samdb.domain_dn()
402         res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
403           attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
404                  "minPwdAge", "maxPwdAge"])
405         assert(len(res) == 1)
406         try:
407             pwd_props = int(res[0]["pwdProperties"][0])
408             pwd_hist_len = int(res[0]["pwdHistoryLength"][0])
409             cur_min_pwd_len = int(res[0]["minPwdLength"][0])
410             # ticks -> days
411             cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
412             if int(res[0]["maxPwdAge"][0]) == -0x8000000000000000:
413                 cur_max_pwd_age = 0
414             else:
415                 cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
416         except Exception, e:
417             raise CommandError("Could not retrieve password properties!", e)
418
419         if subcommand == "show":
420             self.message("Password informations for domain '%s'" % domain_dn)
421             self.message("")
422             if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
423                 self.message("Password complexity: on")
424             else:
425                 self.message("Password complexity: off")
426             if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0:
427                 self.message("Store plaintext passwords: on")
428             else:
429                 self.message("Store plaintext passwords: off")
430             self.message("Password history length: %d" % pwd_hist_len)
431             self.message("Minimum password length: %d" % cur_min_pwd_len)
432             self.message("Minimum password age (days): %d" % cur_min_pwd_age)
433             self.message("Maximum password age (days): %d" % cur_max_pwd_age)
434         elif subcommand == "set":
435             msgs = []
436             m = ldb.Message()
437             m.dn = ldb.Dn(samdb, domain_dn)
438
439             if complexity is not None:
440                 if complexity == "on" or complexity == "default":
441                     pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
442                     msgs.append("Password complexity activated!")
443                 elif complexity == "off":
444                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
445                     msgs.append("Password complexity deactivated!")
446
447             if store_plaintext is not None:
448                 if store_plaintext == "on" or store_plaintext == "default":
449                     pwd_props = pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT
450                     msgs.append("Plaintext password storage for changed passwords activated!")
451                 elif store_plaintext == "off":
452                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_STORE_CLEARTEXT)
453                     msgs.append("Plaintext password storage for changed passwords deactivated!")
454
455             if complexity is not None or store_plaintext is not None:
456                 m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
457                   ldb.FLAG_MOD_REPLACE, "pwdProperties")
458
459             if history_length is not None:
460                 if history_length == "default":
461                     pwd_hist_len = 24
462                 else:
463                     pwd_hist_len = int(history_length)
464
465                 if pwd_hist_len < 0 or pwd_hist_len > 24:
466                     raise CommandError("Password history length must be in the range of 0 to 24!")
467
468                 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
469                   ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
470                 msgs.append("Password history length changed!")
471
472             if min_pwd_length is not None:
473                 if min_pwd_length == "default":
474                     min_pwd_len = 7
475                 else:
476                     min_pwd_len = int(min_pwd_length)
477
478                 if min_pwd_len < 0 or min_pwd_len > 14:
479                     raise CommandError("Minimum password length must be in the range of 0 to 14!")
480
481                 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
482                   ldb.FLAG_MOD_REPLACE, "minPwdLength")
483                 msgs.append("Minimum password length changed!")
484
485             if min_pwd_age is not None:
486                 if min_pwd_age == "default":
487                     min_pwd_age = 1
488                 else:
489                     min_pwd_age = int(min_pwd_age)
490
491                 if min_pwd_age < 0 or min_pwd_age > 998:
492                     raise CommandError("Minimum password age must be in the range of 0 to 998!")
493
494                 # days -> ticks
495                 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
496
497                 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
498                   ldb.FLAG_MOD_REPLACE, "minPwdAge")
499                 msgs.append("Minimum password age changed!")
500
501             if max_pwd_age is not None:
502                 if max_pwd_age == "default":
503                     max_pwd_age = 43
504                 else:
505                     max_pwd_age = int(max_pwd_age)
506
507                 if max_pwd_age < 0 or max_pwd_age > 999:
508                     raise CommandError("Maximum password age must be in the range of 0 to 999!")
509
510                 # days -> ticks
511                 if max_pwd_age == 0:
512                     max_pwd_age_ticks = -0x8000000000000000
513                 else:
514                     max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
515
516                 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
517                   ldb.FLAG_MOD_REPLACE, "maxPwdAge")
518                 msgs.append("Maximum password age changed!")
519
520             if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
521                 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
522
523             if len(m) == 0:
524                 raise CommandError("You must specify at least one option to set. Try --help")
525             samdb.modify(m)
526             msgs.append("All changes applied successfully!")
527             self.message("\n".join(msgs))
528         else:
529             raise CommandError("Wrong argument '%s'!" % subcommand)
530
531
532 class cmd_domain_samba3upgrade(Command):
533     """Upgrade from Samba3 database to Samba4 AD database.
534
535     Specify either a directory with all samba3 databases and state files (with --dbdir) or
536     samba3 testparm utility (with --testparm).
537     """
538
539     synopsis = "%prog [options] <samba3_smb_conf>"
540
541     takes_optiongroups = {
542         "sambaopts": options.SambaOptions,
543         "versionopts": options.VersionOptions
544     }
545
546     takes_options = [
547         Option("--dbdir", type="string", metavar="DIR",
548                   help="Path to samba3 database directory"),
549         Option("--testparm", type="string", metavar="PATH",
550                   help="Path to samba3 testparm utility from the previous installation.  This allows the default paths of the previous installation to be followed"),
551         Option("--targetdir", type="string", metavar="DIR",
552                   help="Path prefix where the new Samba 4.0 AD domain should be initialised"),
553         Option("--quiet", help="Be quiet", action="store_true"),
554         Option("--verbose", help="Be verbose", action="store_true"),
555         Option("--use-xattrs", type="choice", choices=["yes","no","auto"], metavar="[yes|no|auto]",
556                    help="Define if we should use the native fs capabilities or a tdb file for storing attributes likes ntacl, auto tries to make an inteligent guess based on the user rights and system capabilities", default="auto"),
557     ]
558
559     takes_args = ["smbconf"]
560
561     def run(self, smbconf=None, targetdir=None, dbdir=None, testparm=None, 
562             quiet=False, verbose=False, use_xattrs=None, sambaopts=None, versionopts=None):
563
564         if not os.path.exists(smbconf):
565             raise CommandError("File %s does not exist" % smbconf)
566         
567         if testparm and not os.path.exists(testparm):
568             raise CommandError("Testparm utility %s does not exist" % testparm)
569
570         if dbdir and not os.path.exists(dbdir):
571             raise CommandError("Directory %s does not exist" % dbdir)
572
573         if not dbdir and not testparm:
574             raise CommandError("Please specify either dbdir or testparm")
575
576         logger = self.get_logger()
577         if verbose:
578             logger.setLevel(logging.DEBUG)
579         elif quiet:
580             logger.setLevel(logging.WARNING)
581         else:
582             logger.setLevel(logging.INFO)
583
584         if dbdir and testparm:
585             logger.warning("both dbdir and testparm specified, ignoring dbdir.")
586             dbdir = None
587
588         lp = sambaopts.get_loadparm()
589
590         s3conf = s3param.get_context()
591
592         if sambaopts.realm:
593             s3conf.set("realm", sambaopts.realm)
594
595         eadb = True
596         if use_xattrs == "yes":
597             eadb = False
598         elif use_xattrs == "auto" and not s3conf.get("posix:eadb"):
599             if targetdir:
600                 tmpfile = tempfile.NamedTemporaryFile(prefix=os.path.abspath(targetdir))
601             else:
602                 tmpfile = tempfile.NamedTemporaryFile(prefix=os.path.abspath(os.path.dirname(lp.get("private dir"))))
603             try:
604                 samba.ntacls.setntacl(lp, tmpfile.name,
605                             "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native")
606                 eadb = False
607             except:
608                 # FIXME: Don't catch all exceptions here
609                 logger.info("You are not root or your system do not support xattr, using tdb backend for attributes. "
610                             "If you intend to use this provision in production, rerun the script as root on a system supporting xattrs.")
611             tmpfile.close()
612
613         # Set correct default values from dbdir or testparm
614         paths = {}
615         if dbdir:
616             paths["state directory"] = dbdir
617             paths["private dir"] = dbdir
618             paths["lock directory"] = dbdir
619         else:
620             paths["state directory"] = get_testparm_var(testparm, smbconf, "state directory")
621             paths["private dir"] = get_testparm_var(testparm, smbconf, "private dir")
622             paths["lock directory"] = get_testparm_var(testparm, smbconf, "lock directory")
623             # "testparm" from Samba 3 < 3.4.x is not aware of the parameter
624             # "state directory", instead make use of "lock directory"
625             if len(paths["state directory"]) == 0:
626                 paths["state directory"] = paths["lock directory"]
627
628         for p in paths:
629             s3conf.set(p, paths[p])
630     
631         # load smb.conf parameters
632         logger.info("Reading smb.conf")
633         s3conf.load(smbconf)
634         samba3 = Samba3(smbconf, s3conf)
635     
636         logger.info("Provisioning")
637         upgrade_from_samba3(samba3, logger, targetdir, session_info=system_session(), 
638                             useeadb=eadb)
639
640 class cmd_domain(SuperCommand):
641     """Domain management"""
642
643     subcommands = {}
644     subcommands["exportkeytab"] = cmd_domain_export_keytab()
645     subcommands["info"] = cmd_domain_info()
646     subcommands["join"] = cmd_domain_join()
647     subcommands["level"] = cmd_domain_level()
648     subcommands["passwordsettings"] = cmd_domain_passwordsettings()
649     subcommands["samba3upgrade"] = cmd_domain_samba3upgrade()