5 # Copyright Matthias Dieter Wallnoefer 2009
6 # Copyright Andrew Kroeger 2009
7 # Copyright Jelmer Vernooij 2009
8 # Copyright Giampaolo Lauria 2011
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.
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.
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/>.
26 import samba
.getopt
as options
30 from samba
.auth
import system_session
31 from samba
.samdb
import SamDB
32 from samba
.dcerpc
.samr
import DOMAIN_PASSWORD_COMPLEX
, DOMAIN_PASSWORD_STORE_CLEARTEXT
33 from samba
.netcmd
import (
40 from samba
.dsdb
import (
41 DS_DOMAIN_FUNCTION_2000
,
42 DS_DOMAIN_FUNCTION_2003
,
43 DS_DOMAIN_FUNCTION_2003_MIXED
,
44 DS_DOMAIN_FUNCTION_2008
,
45 DS_DOMAIN_FUNCTION_2008_R2
,
51 class cmd_domain_level(Command
):
52 """Raises domain and forest function levels"""
54 synopsis
= "%prog domain level (show | raise <options>)"
56 takes_optiongroups
= {
57 "sambaopts": options
.SambaOptions
,
58 "credopts": options
.CredentialsOptions
,
59 "versionopts": options
.VersionOptions
,
63 Option("-H", help="LDB URL for database or target server", type=str),
64 Option("--quiet", help="Be quiet", action
="store_true"),
65 Option("--forest", type="choice", choices
=["2003", "2008", "2008_R2"],
66 help="The forest function level (2003 | 2008 | 2008_R2)"),
69 takes_args
= ["subcommand"]
71 def run(self
, subcommand
, H
=None, forest
=None, domain
=None, quiet
=False,
72 credopts
=None, sambaopts
=None, versionopts
=None):
73 lp
= sambaopts
.get_loadparm()
74 creds
= credopts
.get_credentials(lp
, fallback_machine
=True)
76 samdb
= SamDB(url
=H
, session_info
=system_session(),
77 credentials
=creds
, lp
=lp
)
79 domain_dn
= samdb
.domain_dn()
81 res_forest
= samdb
.search("CN=Partitions,CN=Configuration," + domain_dn
,
82 scope
=ldb
.SCOPE_BASE
, attrs
=["msDS-Behavior-Version"])
83 assert len(res_forest
) == 1
85 res_domain
= samdb
.search(domain_dn
, scope
=ldb
.SCOPE_BASE
,
86 attrs
=["msDS-Behavior-Version", "nTMixedDomain"])
87 assert len(res_domain
) == 1
89 res_dc_s
= samdb
.search("CN=Sites,CN=Configuration," + domain_dn
,
90 scope
=ldb
.SCOPE_SUBTREE
, expression
="(objectClass=nTDSDSA)",
91 attrs
=["msDS-Behavior-Version"])
92 assert len(res_dc_s
) >= 1
95 level_forest
= int(res_forest
[0]["msDS-Behavior-Version"][0])
96 level_domain
= int(res_domain
[0]["msDS-Behavior-Version"][0])
97 level_domain_mixed
= int(res_domain
[0]["nTMixedDomain"][0])
99 min_level_dc
= int(res_dc_s
[0]["msDS-Behavior-Version"][0]) # Init value
101 if int(msg
["msDS-Behavior-Version"][0]) < min_level_dc
:
102 min_level_dc
= int(msg
["msDS-Behavior-Version"][0])
104 if level_forest
< 0 or level_domain
< 0:
105 raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!")
107 raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!")
108 if level_forest
> level_domain
:
109 raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!")
110 if level_domain
> min_level_dc
:
111 raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!")
114 raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!")
116 if subcommand
== "show":
117 self
.message("Domain and forest function level for domain '%s'" % domain_dn
)
118 if level_forest
== DS_DOMAIN_FUNCTION_2000
and level_domain_mixed
!= 0:
119 self
.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
120 if level_domain
== DS_DOMAIN_FUNCTION_2000
and level_domain_mixed
!= 0:
121 self
.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
122 if min_level_dc
== DS_DOMAIN_FUNCTION_2000
and level_domain_mixed
!= 0:
123 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)!")
127 if level_forest
== DS_DOMAIN_FUNCTION_2000
:
129 elif level_forest
== DS_DOMAIN_FUNCTION_2003_MIXED
:
130 outstr
= "2003 with mixed domains/interim (NT4 DC support)"
131 elif level_forest
== DS_DOMAIN_FUNCTION_2003
:
133 elif level_forest
== DS_DOMAIN_FUNCTION_2008
:
135 elif level_forest
== DS_DOMAIN_FUNCTION_2008_R2
:
138 outstr
= "higher than 2008 R2"
139 self
.message("Forest function level: (Windows) " + outstr
)
141 if level_domain
== DS_DOMAIN_FUNCTION_2000
and level_domain_mixed
!= 0:
142 outstr
= "2000 mixed (NT4 DC support)"
143 elif level_domain
== DS_DOMAIN_FUNCTION_2000
and level_domain_mixed
== 0:
145 elif level_domain
== DS_DOMAIN_FUNCTION_2003_MIXED
:
146 outstr
= "2003 with mixed domains/interim (NT4 DC support)"
147 elif level_domain
== DS_DOMAIN_FUNCTION_2003
:
149 elif level_domain
== DS_DOMAIN_FUNCTION_2008
:
151 elif level_domain
== DS_DOMAIN_FUNCTION_2008_R2
:
154 outstr
= "higher than 2008 R2"
155 self
.message("Lowest function level of a DC: (Windows) " + outstr
)
157 elif subcommand
== "raise":
160 if domain
is not None:
162 new_level_domain
= DS_DOMAIN_FUNCTION_2003
163 elif domain
== "2008":
164 new_level_domain
= DS_DOMAIN_FUNCTION_2008
165 elif domain
== "2008_R2":
166 new_level_domain
= DS_DOMAIN_FUNCTION_2008_R2
168 if new_level_domain
<= level_domain
and level_domain_mixed
== 0:
169 raise CommandError("Domain function level can't be smaller equal to the actual one!")
171 if new_level_domain
> min_level_dc
:
172 raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")
174 # Deactivate mixed/interim domain support
175 if level_domain_mixed
!= 0:
176 # Directly on the base DN
178 m
.dn
= ldb
.Dn(samdb
, domain_dn
)
179 m
["nTMixedDomain"] = ldb
.MessageElement("0",
180 ldb
.FLAG_MOD_REPLACE
, "nTMixedDomain")
184 m
.dn
= ldb
.Dn(samdb
, "CN=" + lp
.get("workgroup")
185 + ",CN=Partitions,CN=Configuration," + domain_dn
)
186 m
["nTMixedDomain"] = ldb
.MessageElement("0",
187 ldb
.FLAG_MOD_REPLACE
, "nTMixedDomain")
190 except ldb
.LdbError
, (enum
, emsg
):
191 if enum
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
194 # Directly on the base DN
196 m
.dn
= ldb
.Dn(samdb
, domain_dn
)
197 m
["msDS-Behavior-Version"]= ldb
.MessageElement( str(new_level_domain
), ldb
.FLAG_MOD_REPLACE
,
198 "msDS-Behavior-Version")
202 m
.dn
= ldb
.Dn(samdb
, "CN=" + lp
.get("workgroup")
203 + ",CN=Partitions,CN=Configuration," + domain_dn
)
204 m
["msDS-Behavior-Version"]= ldb
.MessageElement(
205 str(new_level_domain
), ldb
.FLAG_MOD_REPLACE
,
206 "msDS-Behavior-Version")
209 except ldb
.LdbError
, (enum
, emsg
):
210 if enum
!= ldb
.ERR_UNWILLING_TO_PERFORM
:
213 level_domain
= new_level_domain
214 msgs
.append("Domain function level changed!")
216 if forest
is not None:
218 new_level_forest
= DS_DOMAIN_FUNCTION_2003
219 elif forest
== "2008":
220 new_level_forest
= DS_DOMAIN_FUNCTION_2008
221 elif forest
== "2008_R2":
222 new_level_forest
= DS_DOMAIN_FUNCTION_2008_R2
223 if new_level_forest
<= level_forest
:
224 raise CommandError("Forest function level can't be smaller equal to the actual one!")
225 if new_level_forest
> level_domain
:
226 raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
228 m
.dn
= ldb
.Dn(samdb
, "CN=Partitions,CN=Configuration,"
230 m
["msDS-Behavior-Version"]= ldb
.MessageElement(
231 str(new_level_forest
), ldb
.FLAG_MOD_REPLACE
,
232 "msDS-Behavior-Version")
234 msgs
.append("Forest function level changed!")
235 msgs
.append("All changes applied successfully!")
236 self
.message("\n".join(msgs
))
238 raise CommandError("Wrong argument '%s'!" % subcommand
)
242 class cmd_domain_machinepassword(Command
):
243 """Gets a machine password out of our SAM"""
245 synopsis
= "%prog domain machinepassword <accountname>"
247 takes_optiongroups
= {
248 "sambaopts": options
.SambaOptions
,
249 "versionopts": options
.VersionOptions
,
250 "credopts": options
.CredentialsOptions
,
253 takes_args
= ["secret"]
255 def run(self
, secret
, sambaopts
=None, credopts
=None, versionopts
=None):
256 lp
= sambaopts
.get_loadparm()
257 creds
= credopts
.get_credentials(lp
, fallback_machine
=True)
258 name
= lp
.get("secrets database")
259 path
= lp
.get("private dir")
260 url
= os
.path
.join(path
, name
)
261 if not os
.path
.exists(url
):
262 raise CommandError("secret database not found at %s " % url
)
263 secretsdb
= Ldb(url
=url
, session_info
=system_session(),
264 credentials
=creds
, lp
=lp
)
265 result
= secretsdb
.search(attrs
=["secret"],
266 expression
="(&(objectclass=primaryDomain)(samaccountname=%s))" % secret
)
269 raise CommandError("search returned %d records, expected 1" % len(result
))
271 self
.outf
.write("%s\n" % result
[0]["secret"])
275 class cmd_domain_passwordsettings(Command
):
276 """Sets password settings
278 Password complexity, history length, minimum password length, the minimum
279 and maximum password age) on a Samba4 server.
282 synopsis
= "%prog domain passwordsettings (show | set <options>)"
284 takes_optiongroups
= {
285 "sambaopts": options
.SambaOptions
,
286 "versionopts": options
.VersionOptions
,
287 "credopts": options
.CredentialsOptions
,
291 Option("-H", help="LDB URL for database or target server", type=str),
292 Option("--quiet", help="Be quiet", action
="store_true"),
293 Option("--complexity", type="choice", choices
=["on","off","default"],
294 help="The password complexity (on | off | default). Default is 'on'"),
295 Option("--store-plaintext", type="choice", choices
=["on","off","default"],
296 help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
297 Option("--history-length",
298 help="The password history length (<integer> | default). Default is 24.", type=str),
299 Option("--min-pwd-length",
300 help="The minimum password length (<integer> | default). Default is 7.", type=str),
301 Option("--min-pwd-age",
302 help="The minimum password age (<integer in days> | default). Default is 1.", type=str),
303 Option("--max-pwd-age",
304 help="The maximum password age (<integer in days> | default). Default is 43.", type=str),
307 takes_args
= ["subcommand"]
309 def run(self
, subcommand
, H
=None, min_pwd_age
=None, max_pwd_age
=None,
310 quiet
=False, complexity
=None, store_plaintext
=None, history_length
=None,
311 min_pwd_length
=None, credopts
=None, sambaopts
=None,
313 lp
= sambaopts
.get_loadparm()
314 creds
= credopts
.get_credentials(lp
)
316 samdb
= SamDB(url
=H
, session_info
=system_session(),
317 credentials
=creds
, lp
=lp
)
319 domain_dn
= samdb
.domain_dn()
320 res
= samdb
.search(domain_dn
, scope
=ldb
.SCOPE_BASE
,
321 attrs
=["pwdProperties", "pwdHistoryLength", "minPwdLength",
322 "minPwdAge", "maxPwdAge"])
323 assert(len(res
) == 1)
325 pwd_props
= int(res
[0]["pwdProperties"][0])
326 pwd_hist_len
= int(res
[0]["pwdHistoryLength"][0])
327 cur_min_pwd_len
= int(res
[0]["minPwdLength"][0])
329 cur_min_pwd_age
= int(abs(int(res
[0]["minPwdAge"][0])) / (1e7
* 60 * 60 * 24))
330 cur_max_pwd_age
= int(abs(int(res
[0]["maxPwdAge"][0])) / (1e7
* 60 * 60 * 24))
332 raise CommandError("Could not retrieve password properties!", e
)
334 if subcommand
== "show":
335 self
.message("Password informations for domain '%s'" % domain_dn
)
337 if pwd_props
& DOMAIN_PASSWORD_COMPLEX
!= 0:
338 self
.message("Password complexity: on")
340 self
.message("Password complexity: off")
341 if pwd_props
& DOMAIN_PASSWORD_STORE_CLEARTEXT
!= 0:
342 self
.message("Store plaintext passwords: on")
344 self
.message("Store plaintext passwords: off")
345 self
.message("Password history length: %d" % pwd_hist_len
)
346 self
.message("Minimum password length: %d" % cur_min_pwd_len
)
347 self
.message("Minimum password age (days): %d" % cur_min_pwd_age
)
348 self
.message("Maximum password age (days): %d" % cur_max_pwd_age
)
349 elif subcommand
== "set":
352 m
.dn
= ldb
.Dn(samdb
, domain_dn
)
354 if complexity
is not None:
355 if complexity
== "on" or complexity
== "default":
356 pwd_props
= pwd_props | DOMAIN_PASSWORD_COMPLEX
357 msgs
.append("Password complexity activated!")
358 elif complexity
== "off":
359 pwd_props
= pwd_props
& (~DOMAIN_PASSWORD_COMPLEX
)
360 msgs
.append("Password complexity deactivated!")
362 if store_plaintext
is not None:
363 if store_plaintext
== "on" or store_plaintext
== "default":
364 pwd_props
= pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT
365 msgs
.append("Plaintext password storage for changed passwords activated!")
366 elif store_plaintext
== "off":
367 pwd_props
= pwd_props
& (~DOMAIN_PASSWORD_STORE_CLEARTEXT
)
368 msgs
.append("Plaintext password storage for changed passwords deactivated!")
370 if complexity
is not None or store_plaintext
is not None:
371 m
["pwdProperties"] = ldb
.MessageElement(str(pwd_props
),
372 ldb
.FLAG_MOD_REPLACE
, "pwdProperties")
374 if history_length
is not None:
375 if history_length
== "default":
378 pwd_hist_len
= int(history_length
)
380 if pwd_hist_len
< 0 or pwd_hist_len
> 24:
381 raise CommandError("Password history length must be in the range of 0 to 24!")
383 m
["pwdHistoryLength"] = ldb
.MessageElement(str(pwd_hist_len
),
384 ldb
.FLAG_MOD_REPLACE
, "pwdHistoryLength")
385 msgs
.append("Password history length changed!")
387 if min_pwd_length
is not None:
388 if min_pwd_length
== "default":
391 min_pwd_len
= int(min_pwd_length
)
393 if min_pwd_len
< 0 or min_pwd_len
> 14:
394 raise CommandError("Minimum password length must be in the range of 0 to 14!")
396 m
["minPwdLength"] = ldb
.MessageElement(str(min_pwd_len
),
397 ldb
.FLAG_MOD_REPLACE
, "minPwdLength")
398 msgs
.append("Minimum password length changed!")
400 if min_pwd_age
is not None:
401 if min_pwd_age
== "default":
404 min_pwd_age
= int(min_pwd_age
)
406 if min_pwd_age
< 0 or min_pwd_age
> 998:
407 raise CommandError("Minimum password age must be in the range of 0 to 998!")
410 min_pwd_age_ticks
= -int(min_pwd_age
* (24 * 60 * 60 * 1e7
))
412 m
["minPwdAge"] = ldb
.MessageElement(str(min_pwd_age_ticks
),
413 ldb
.FLAG_MOD_REPLACE
, "minPwdAge")
414 msgs
.append("Minimum password age changed!")
416 if max_pwd_age
is not None:
417 if max_pwd_age
== "default":
420 max_pwd_age
= int(max_pwd_age
)
422 if max_pwd_age
< 0 or max_pwd_age
> 999:
423 raise CommandError("Maximum password age must be in the range of 0 to 999!")
426 max_pwd_age_ticks
= -int(max_pwd_age
* (24 * 60 * 60 * 1e7
))
428 m
["maxPwdAge"] = ldb
.MessageElement(str(max_pwd_age_ticks
),
429 ldb
.FLAG_MOD_REPLACE
, "maxPwdAge")
430 msgs
.append("Maximum password age changed!")
432 if max_pwd_age
> 0 and min_pwd_age
>= max_pwd_age
:
433 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age
, min_pwd_age
))
436 msgs
.append("All changes applied successfully!")
437 self
.message("\n".join(msgs
))
439 raise CommandError("Wrong argument '%s'!" % subcommand
)
443 class cmd_domain(SuperCommand
):
444 """Domain management"""
447 subcommands
["level"] = cmd_domain_level()
448 subcommands
["machinepassword"] = cmd_domain_machinepassword()
449 subcommands
["passwordsettings"] = cmd_domain_passwordsettings()