samba-tool: created domain object, moved pwsettings to user passwordsettings
[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
29 from samba.auth import system_session
30 from samba.samdb import SamDB
31 from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX, DOMAIN_PASSWORD_STORE_CLEARTEXT
32 from samba.netcmd import (
33     Command,
34     CommandError,
35     SuperCommand,
36     Option
37     )
38
39
40 class cmd_domain_passwordsettings(Command):
41     """Sets password settings
42
43     Password complexity, history length, minimum password length, the minimum
44     and maximum password age) on a Samba4 server.
45     """
46
47     synopsis = "%prog domain passwordsettings (show | set <options>)"
48
49     takes_optiongroups = {
50         "sambaopts": options.SambaOptions,
51         "versionopts": options.VersionOptions,
52         "credopts": options.CredentialsOptions,
53         }
54
55     takes_options = [
56         Option("-H", help="LDB URL for database or target server", type=str),
57         Option("--quiet", help="Be quiet", action="store_true"),
58         Option("--complexity", type="choice", choices=["on","off","default"],
59           help="The password complexity (on | off | default). Default is 'on'"),
60         Option("--store-plaintext", type="choice", choices=["on","off","default"],
61           help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
62         Option("--history-length",
63           help="The password history length (<integer> | default).  Default is 24.", type=str),
64         Option("--min-pwd-length",
65           help="The minimum password length (<integer> | default).  Default is 7.", type=str),
66         Option("--min-pwd-age",
67           help="The minimum password age (<integer in days> | default).  Default is 1.", type=str),
68         Option("--max-pwd-age",
69           help="The maximum password age (<integer in days> | default).  Default is 43.", type=str),
70           ]
71
72     takes_args = ["subcommand"]
73
74     def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None,
75             quiet=False, complexity=None, store_plaintext=None, history_length=None,
76             min_pwd_length=None, credopts=None, sambaopts=None,
77             versionopts=None):
78         lp = sambaopts.get_loadparm()
79         creds = credopts.get_credentials(lp)
80
81         samdb = SamDB(url=H, session_info=system_session(),
82             credentials=creds, lp=lp)
83
84         domain_dn = samdb.domain_dn()
85         res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
86           attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
87                  "minPwdAge", "maxPwdAge"])
88         assert(len(res) == 1)
89         try:
90             pwd_props = int(res[0]["pwdProperties"][0])
91             pwd_hist_len = int(res[0]["pwdHistoryLength"][0])
92             cur_min_pwd_len = int(res[0]["minPwdLength"][0])
93             # ticks -> days
94             cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
95             cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
96         except Exception, e:
97             raise CommandError("Could not retrieve password properties!", e)
98
99         if subcommand == "show":
100             self.message("Password informations for domain '%s'" % domain_dn)
101             self.message("")
102             if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
103                 self.message("Password complexity: on")
104             else:
105                 self.message("Password complexity: off")
106             if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0:
107                 self.message("Store plaintext passwords: on")
108             else:
109                 self.message("Store plaintext passwords: off")
110             self.message("Password history length: %d" % pwd_hist_len)
111             self.message("Minimum password length: %d" % cur_min_pwd_len)
112             self.message("Minimum password age (days): %d" % cur_min_pwd_age)
113             self.message("Maximum password age (days): %d" % cur_max_pwd_age)
114         elif subcommand == "set":
115             msgs = []
116             m = ldb.Message()
117             m.dn = ldb.Dn(samdb, domain_dn)
118
119             if complexity is not None:
120                 if complexity == "on" or complexity == "default":
121                     pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
122                     msgs.append("Password complexity activated!")
123                 elif complexity == "off":
124                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
125                     msgs.append("Password complexity deactivated!")
126
127             if store_plaintext is not None:
128                 if store_plaintext == "on" or store_plaintext == "default":
129                     pwd_props = pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT
130                     msgs.append("Plaintext password storage for changed passwords activated!")
131                 elif store_plaintext == "off":
132                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_STORE_CLEARTEXT)
133                     msgs.append("Plaintext password storage for changed passwords deactivated!")
134
135             if complexity is not None or store_plaintext is not None:
136                 m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
137                   ldb.FLAG_MOD_REPLACE, "pwdProperties")
138
139             if history_length is not None:
140                 if history_length == "default":
141                     pwd_hist_len = 24
142                 else:
143                     pwd_hist_len = int(history_length)
144
145                 if pwd_hist_len < 0 or pwd_hist_len > 24:
146                     raise CommandError("Password history length must be in the range of 0 to 24!")
147
148                 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
149                   ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
150                 msgs.append("Password history length changed!")
151
152             if min_pwd_length is not None:
153                 if min_pwd_length == "default":
154                     min_pwd_len = 7
155                 else:
156                     min_pwd_len = int(min_pwd_length)
157
158                 if min_pwd_len < 0 or min_pwd_len > 14:
159                     raise CommandError("Minimum password length must be in the range of 0 to 14!")
160
161                 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
162                   ldb.FLAG_MOD_REPLACE, "minPwdLength")
163                 msgs.append("Minimum password length changed!")
164
165             if min_pwd_age is not None:
166                 if min_pwd_age == "default":
167                     min_pwd_age = 1
168                 else:
169                     min_pwd_age = int(min_pwd_age)
170
171                 if min_pwd_age < 0 or min_pwd_age > 998:
172                     raise CommandError("Minimum password age must be in the range of 0 to 998!")
173
174                 # days -> ticks
175                 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
176
177                 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
178                   ldb.FLAG_MOD_REPLACE, "minPwdAge")
179                 msgs.append("Minimum password age changed!")
180
181             if max_pwd_age is not None:
182                 if max_pwd_age == "default":
183                     max_pwd_age = 43
184                 else:
185                     max_pwd_age = int(max_pwd_age)
186
187                 if max_pwd_age < 0 or max_pwd_age > 999:
188                     raise CommandError("Maximum password age must be in the range of 0 to 999!")
189
190                 # days -> ticks
191                 max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
192
193                 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
194                   ldb.FLAG_MOD_REPLACE, "maxPwdAge")
195                 msgs.append("Maximum password age changed!")
196
197             if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
198                 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
199
200             samdb.modify(m)
201             msgs.append("All changes applied successfully!")
202             self.message("\n".join(msgs))
203         else:
204             raise CommandError("Wrong argument '%s'!" % subcommand)
205
206
207
208 class cmd_domain(SuperCommand):
209     """Domain management"""
210
211     subcommands = {}
212     subcommands["passwordsettings"] = cmd_domain_passwordsettings()