ldb: Fix ldb public library header files being unusable
[Samba.git] / python / samba / netcmd / domain / passwordsettings.py
blobd0cf47b1756e2b2fcd57722ee0e26fb517da7c7e
1 # domain management - domain passwordsettings
3 # Copyright Matthias Dieter Wallnoefer 2009
4 # Copyright Andrew Kroeger 2009
5 # Copyright Jelmer Vernooij 2007-2012
6 # Copyright Giampaolo Lauria 2011
7 # Copyright Matthieu Patou <mat@matws.net> 2011
8 # Copyright Andrew Bartlett 2008-2015
9 # Copyright Stefan Metzmacher 2012
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 import ldb
26 import samba.getopt as options
27 from samba.auth import system_session
28 from samba.dcerpc.samr import (DOMAIN_PASSWORD_COMPLEX,
29 DOMAIN_PASSWORD_STORE_CLEARTEXT)
30 from samba.netcmd import Command, CommandError, Option, SuperCommand
31 from samba.netcmd.common import (NEVER_TIMESTAMP, timestamp_to_days,
32 timestamp_to_mins)
33 from samba.netcmd.pso import cmd_domain_passwordsettings_pso
34 from samba.samdb import SamDB
37 class cmd_domain_passwordsettings_show(Command):
38 """Display current password settings for the domain."""
40 synopsis = "%prog [options]"
42 takes_optiongroups = {
43 "sambaopts": options.SambaOptions,
44 "versionopts": options.VersionOptions,
45 "credopts": options.CredentialsOptions,
48 takes_options = [
49 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
50 metavar="URL", dest="H"),
53 def run(self, H=None, credopts=None, sambaopts=None, versionopts=None):
54 lp = sambaopts.get_loadparm()
55 creds = credopts.get_credentials(lp)
57 samdb = SamDB(url=H, session_info=system_session(),
58 credentials=creds, lp=lp)
60 domain_dn = samdb.domain_dn()
61 res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
62 attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
63 "minPwdAge", "maxPwdAge", "lockoutDuration", "lockoutThreshold",
64 "lockOutObservationWindow"])
65 assert(len(res) == 1)
66 try:
67 pwd_props = int(res[0]["pwdProperties"][0])
68 pwd_hist_len = int(res[0]["pwdHistoryLength"][0])
69 cur_min_pwd_len = int(res[0]["minPwdLength"][0])
70 # ticks -> days
71 cur_min_pwd_age = timestamp_to_days(res[0]["minPwdAge"][0])
72 cur_max_pwd_age = timestamp_to_days(res[0]["maxPwdAge"][0])
74 cur_account_lockout_threshold = int(res[0]["lockoutThreshold"][0])
76 # ticks -> mins
77 cur_account_lockout_duration = timestamp_to_mins(res[0]["lockoutDuration"][0])
78 cur_reset_account_lockout_after = timestamp_to_mins(res[0]["lockOutObservationWindow"][0])
79 except Exception as e:
80 raise CommandError("Could not retrieve password properties!", e)
82 self.message("Password information for domain '%s'" % domain_dn)
83 self.message("")
84 if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
85 self.message("Password complexity: on")
86 else:
87 self.message("Password complexity: off")
88 if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0:
89 self.message("Store plaintext passwords: on")
90 else:
91 self.message("Store plaintext passwords: off")
92 self.message("Password history length: %d" % pwd_hist_len)
93 self.message("Minimum password length: %d" % cur_min_pwd_len)
94 self.message("Minimum password age (days): %d" % cur_min_pwd_age)
95 self.message("Maximum password age (days): %d" % cur_max_pwd_age)
96 self.message("Account lockout duration (mins): %d" % cur_account_lockout_duration)
97 self.message("Account lockout threshold (attempts): %d" % cur_account_lockout_threshold)
98 self.message("Reset account lockout after (mins): %d" % cur_reset_account_lockout_after)
101 class cmd_domain_passwordsettings_set(Command):
102 """Set password settings.
104 Password complexity, password lockout policy, history length,
105 minimum password length, the minimum and maximum password age) on
106 a Samba AD DC server.
108 Use against a Windows DC is possible, but group policy will override it.
111 synopsis = "%prog <options> [options]"
113 takes_optiongroups = {
114 "sambaopts": options.SambaOptions,
115 "versionopts": options.VersionOptions,
116 "credopts": options.CredentialsOptions,
119 takes_options = [
120 Option("-H", "--URL", help="LDB URL for database or target server", type=str,
121 metavar="URL", dest="H"),
122 Option("-q", "--quiet", help="Be quiet", action="store_true"), # unused
123 Option("--complexity", type="choice", choices=["on", "off", "default"],
124 help="The password complexity (on | off | default). Default is 'on'"),
125 Option("--store-plaintext", type="choice", choices=["on", "off", "default"],
126 help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
127 Option("--history-length",
128 help="The password history length (<integer> | default). Default is 24.", type=str),
129 Option("--min-pwd-length",
130 help="The minimum password length (<integer> | default). Default is 7.", type=str),
131 Option("--min-pwd-age",
132 help="The minimum password age (<integer in days> | default). Default is 1.", type=str),
133 Option("--max-pwd-age",
134 help="The maximum password age (<integer in days> | default). Default is 43.", type=str),
135 Option("--account-lockout-duration",
136 help="The length of time an account is locked out after exceeding the limit on bad password attempts (<integer in mins> | default). Default is 30 mins.", type=str),
137 Option("--account-lockout-threshold",
138 help="The number of bad password attempts allowed before locking out the account (<integer> | default). Default is 0 (never lock out).", type=str),
139 Option("--reset-account-lockout-after",
140 help="After this time is elapsed, the recorded number of attempts restarts from zero (<integer> | default). Default is 30.", type=str),
143 def run(self, H=None, min_pwd_age=None, max_pwd_age=None,
144 quiet=False, complexity=None, store_plaintext=None, history_length=None,
145 min_pwd_length=None, account_lockout_duration=None, account_lockout_threshold=None,
146 reset_account_lockout_after=None, credopts=None, sambaopts=None,
147 versionopts=None):
148 lp = sambaopts.get_loadparm()
149 creds = credopts.get_credentials(lp)
151 samdb = SamDB(url=H, session_info=system_session(),
152 credentials=creds, lp=lp)
154 domain_dn = samdb.domain_dn()
155 msgs = []
156 m = ldb.Message()
157 m.dn = ldb.Dn(samdb, domain_dn)
158 pwd_props = int(samdb.get_pwdProperties())
160 # get the current password age settings
161 max_pwd_age_ticks = samdb.get_maxPwdAge()
162 min_pwd_age_ticks = samdb.get_minPwdAge()
164 if complexity is not None:
165 if complexity == "on" or complexity == "default":
166 pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
167 msgs.append("Password complexity activated!")
168 elif complexity == "off":
169 pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
170 msgs.append("Password complexity deactivated!")
172 if store_plaintext is not None:
173 if store_plaintext == "on" or store_plaintext == "default":
174 pwd_props = pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT
175 msgs.append("Plaintext password storage for changed passwords activated!")
176 elif store_plaintext == "off":
177 pwd_props = pwd_props & (~DOMAIN_PASSWORD_STORE_CLEARTEXT)
178 msgs.append("Plaintext password storage for changed passwords deactivated!")
180 if complexity is not None or store_plaintext is not None:
181 m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
182 ldb.FLAG_MOD_REPLACE, "pwdProperties")
184 if history_length is not None:
185 if history_length == "default":
186 pwd_hist_len = 24
187 else:
188 pwd_hist_len = int(history_length)
190 if pwd_hist_len < 0 or pwd_hist_len > 24:
191 raise CommandError("Password history length must be in the range of 0 to 24!")
193 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
194 ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
195 msgs.append("Password history length changed!")
197 if min_pwd_length is not None:
198 if min_pwd_length == "default":
199 min_pwd_len = 7
200 else:
201 min_pwd_len = int(min_pwd_length)
203 if min_pwd_len < 0 or min_pwd_len > 14:
204 raise CommandError("Minimum password length must be in the range of 0 to 14!")
206 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
207 ldb.FLAG_MOD_REPLACE, "minPwdLength")
208 msgs.append("Minimum password length changed!")
210 if min_pwd_age is not None:
211 if min_pwd_age == "default":
212 min_pwd_age = 1
213 else:
214 min_pwd_age = int(min_pwd_age)
216 if min_pwd_age < 0 or min_pwd_age > 998:
217 raise CommandError("Minimum password age must be in the range of 0 to 998!")
219 # days -> ticks
220 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
222 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
223 ldb.FLAG_MOD_REPLACE, "minPwdAge")
224 msgs.append("Minimum password age changed!")
226 if max_pwd_age is not None:
227 if max_pwd_age == "default":
228 max_pwd_age = 43
229 else:
230 max_pwd_age = int(max_pwd_age)
232 if max_pwd_age < 0 or max_pwd_age > 999:
233 raise CommandError("Maximum password age must be in the range of 0 to 999!")
235 # days -> ticks
236 if max_pwd_age == 0:
237 max_pwd_age_ticks = NEVER_TIMESTAMP
238 else:
239 max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
241 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
242 ldb.FLAG_MOD_REPLACE, "maxPwdAge")
243 msgs.append("Maximum password age changed!")
245 if account_lockout_duration is not None:
246 if account_lockout_duration == "default":
247 account_lockout_duration = 30
248 else:
249 account_lockout_duration = int(account_lockout_duration)
251 if account_lockout_duration < 0 or account_lockout_duration > 99999:
252 raise CommandError("Account lockout duration "
253 "must be in the range of 0 to 99999!")
255 # minutes -> ticks
256 if account_lockout_duration == 0:
257 account_lockout_duration_ticks = NEVER_TIMESTAMP
258 else:
259 account_lockout_duration_ticks = -int(account_lockout_duration * (60 * 1e7))
261 m["lockoutDuration"] = ldb.MessageElement(str(account_lockout_duration_ticks),
262 ldb.FLAG_MOD_REPLACE, "lockoutDuration")
263 msgs.append("Account lockout duration changed!")
265 if account_lockout_threshold is not None:
266 if account_lockout_threshold == "default":
267 account_lockout_threshold = 0
268 else:
269 account_lockout_threshold = int(account_lockout_threshold)
271 m["lockoutThreshold"] = ldb.MessageElement(str(account_lockout_threshold),
272 ldb.FLAG_MOD_REPLACE, "lockoutThreshold")
273 msgs.append("Account lockout threshold changed!")
275 if reset_account_lockout_after is not None:
276 if reset_account_lockout_after == "default":
277 reset_account_lockout_after = 30
278 else:
279 reset_account_lockout_after = int(reset_account_lockout_after)
281 if reset_account_lockout_after < 0 or reset_account_lockout_after > 99999:
282 raise CommandError("Maximum password age must be in the range of 0 to 99999!")
284 # minutes -> ticks
285 if reset_account_lockout_after == 0:
286 reset_account_lockout_after_ticks = NEVER_TIMESTAMP
287 else:
288 reset_account_lockout_after_ticks = -int(reset_account_lockout_after * (60 * 1e7))
290 m["lockOutObservationWindow"] = ldb.MessageElement(str(reset_account_lockout_after_ticks),
291 ldb.FLAG_MOD_REPLACE, "lockOutObservationWindow")
292 msgs.append("Duration to reset account lockout after changed!")
294 if max_pwd_age or min_pwd_age:
295 # If we're setting either min or max password, make sure the max is
296 # still greater overall. As either setting could be None, we use the
297 # ticks here (which are always set) and work backwards.
298 max_pwd_age = timestamp_to_days(max_pwd_age_ticks)
299 min_pwd_age = timestamp_to_days(min_pwd_age_ticks)
300 if max_pwd_age != 0 and min_pwd_age >= max_pwd_age:
301 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
303 if len(m) == 0:
304 raise CommandError("You must specify at least one option to set. Try --help")
305 samdb.modify(m)
306 msgs.append("All changes applied successfully!")
307 self.message("\n".join(msgs))
310 class cmd_domain_passwordsettings(SuperCommand):
311 """Manage password policy settings."""
313 subcommands = {}
314 subcommands["pso"] = cmd_domain_passwordsettings_pso()
315 subcommands["show"] = cmd_domain_passwordsettings_show()
316 subcommands["set"] = cmd_domain_passwordsettings_set()