3030248e4bd30ff19ec1d9a920e0df69f5fdb886
[idra/samba.git] / source4 / scripting / python / samba / netcmd / pwsettings.py
1 #!/usr/bin/python
2 #
3 # Sets password settings.
4 # (Password complexity, history length, minimum password length, the minimum
5 # and maximum password age) on a Samba4 server
6 #
7 # Copyright Matthias Dieter Wallnoefer 2009
8 # Copyright Andrew Kroeger 2009
9 # Copyright Jelmer Vernooij 2009
10 #
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.
15 #
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.
20 #
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/>.
23 #
24
25 import samba.getopt as options
26 import ldb
27
28 from samba.auth import system_session
29 from samba.samdb import SamDB
30 from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX
31 from samba.netcmd import Command, CommandError, Option
32
33 class cmd_pwsettings(Command):
34     """Sets password settings
35
36     Password complexity, history length, minimum password length, the minimum 
37     and maximum password age) on a Samba4 server.
38     """
39
40     synopsis = "(show | set <options>)"
41
42     takes_optiongroups = {
43         "sambaopts": options.SambaOptions,
44         "versionopts": options.VersionOptions,
45         "credopts": options.CredentialsOptions,
46         }
47
48     takes_options = [
49         Option("-H", help="LDB URL for database or target server", type=str),
50         Option("--quiet", help="Be quiet", action="store_true"),
51         Option("--complexity", type="choice", choices=["on","off","default"],
52           help="The password complexity (on | off | default). Default is 'on'"),
53         Option("--history-length",
54           help="The password history length (<integer> | default).  Default is 24.", type=str),
55         Option("--min-pwd-length",
56           help="The minimum password length (<integer> | default).  Default is 7.", type=str),
57         Option("--min-pwd-age",
58           help="The minimum password age (<integer in days> | default).  Default is 0.", type=str),
59         Option("--max-pwd-age",
60           help="The maximum password age (<integer in days> | default).  Default is 43.", type=str),
61           ]
62
63     takes_args = ["subcommand"]
64
65     def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None,
66             quiet=False, complexity=None, history_length=None,
67             min_pwd_length=None, credopts=None, sambaopts=None,
68             versionopts=None):
69         lp = sambaopts.get_loadparm()
70         creds = credopts.get_credentials(lp)
71
72         samdb = SamDB(url=H, session_info=system_session(),
73             credentials=creds, lp=lp)
74
75         domain_dn = samdb.domain_dn()
76         res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
77           attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
78                  "minPwdAge", "maxPwdAge"])
79         assert(len(res) == 1)
80         try:
81             pwd_props = int(res[0]["pwdProperties"][0])
82             pwd_hist_len = int(res[0]["pwdHistoryLength"][0])
83             cur_min_pwd_len = int(res[0]["minPwdLength"][0])
84             # ticks -> days
85             cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
86             cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
87         except KeyError:
88             raise CommandError("Could not retrieve password properties!")
89
90         if subcommand == "show":
91             self.message("Password informations for domain '%s'" % domain_dn)
92             self.message("")
93             if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
94                 self.message("Password complexity: on")
95             else:
96                 self.message("Password complexity: off")
97             self.message("Password history length: %d" % pwd_hist_len)
98             self.message("Minimum password length: %d" % cur_min_pwd_len)
99             self.message("Minimum password age (days): %d" % cur_min_pwd_age)
100             self.message("Maximum password age (days): %d" % cur_max_pwd_age)
101         elif subcommand == "set":
102             msgs = []
103             m = ldb.Message()
104             m.dn = ldb.Dn(samdb, domain_dn)
105
106             if complexity is not None:
107                 if complexity == "on" or complexity == "default":
108                     pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
109                     msgs.append("Password complexity activated!")
110                 elif complexity == "off":
111                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
112                     msgs.append("Password complexity deactivated!")
113
114                 m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
115                   ldb.FLAG_MOD_REPLACE, "pwdProperties")
116
117             if history_length is not None:
118                 if history_length == "default":
119                     pwd_hist_len = 24
120                 else:
121                     pwd_hist_len = int(history_length)
122
123                 if pwd_hist_len < 0 or pwd_hist_len > 24:
124                     raise CommandError("Password history length must be in the range of 0 to 24!")
125
126                 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
127                   ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
128                 msgs.append("Password history length changed!")
129
130             if min_pwd_length is not None:
131                 if min_pwd_length == "default":
132                     min_pwd_len = 7
133                 else:
134                     min_pwd_len = int(min_pwd_length)
135
136                 if min_pwd_len < 0 or min_pwd_len > 14:
137                     raise CommandError("Minimum password length must be in the range of 0 to 14!")
138
139                 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
140                   ldb.FLAG_MOD_REPLACE, "minPwdLength")
141                 msgs.append("Minimum password length changed!")
142
143             if min_pwd_age is not None:
144                 if min_pwd_age == "default":
145                     min_pwd_age = 0
146                 else:
147                     min_pwd_age = int(min_pwd_age)
148
149                 if min_pwd_age < 0 or min_pwd_age > 998:
150                     raise CommandError("Minimum password age must be in the range of 0 to 998!")
151
152                 # days -> ticks
153                 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
154
155                 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
156                   ldb.FLAG_MOD_REPLACE, "minPwdAge")
157                 msgs.append("Minimum password age changed!")
158
159             if max_pwd_age is not None:
160                 if max_pwd_age == "default":
161                     max_pwd_age = 43
162                 else:
163                     max_pwd_age = int(max_pwd_age)
164
165                 if max_pwd_age < 0 or max_pwd_age > 999:
166                     raise CommandError("Maximum password age must be in the range of 0 to 999!")
167
168                 # days -> ticks
169                 max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
170
171                 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
172                   ldb.FLAG_MOD_REPLACE, "maxPwdAge")
173                 msgs.append("Maximum password age changed!")
174
175             if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
176                 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
177
178             samdb.modify(m)
179             msgs.append("All changes applied successfully!")
180             self.message("\n".join(msgs))
181         else:
182             raise CommandError("Wrong argument '%s'!" % subcommand)