python/samba.tests: Ensure samba-tool is called with correct python ver.
[samba.git] / python / samba / tests / pso.py
1 #
2 # Helper classes for testing Password Settings Objects.
3 #
4 # This also tests the default password complexity (i.e. pwdProperties),
5 # minPwdLength, pwdHistoryLength settings as a side-effect.
6 #
7 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2018
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 import ldb
24 from ldb import FLAG_MOD_DELETE, FLAG_MOD_ADD, FLAG_MOD_REPLACE
25 from samba.dcerpc.samr import (DOMAIN_PASSWORD_COMPLEX,
26                                DOMAIN_PASSWORD_STORE_CLEARTEXT)
27
28
29 class TestUser:
30     def __init__(self, username, samdb, userou=None):
31         initial_password = "Initial12#"
32         self.name = username
33         self.ldb = samdb
34         self.dn = "CN=%s,%s,%s" % (username, (userou or "CN=Users"),
35                                    self.ldb.domain_dn())
36
37         # store all passwords that have ever been used for this user, as well
38         # as a pwd_history that more closely resembles the history on the DC
39         self.all_old_passwords = [initial_password]
40         self.pwd_history = [initial_password]
41         self.ldb.newuser(username, initial_password, userou=userou)
42         self.ldb.enable_account("(sAMAccountName=%s)" % username)
43         self.last_pso = None
44
45     def old_invalid_passwords(self, hist_len):
46         """Returns the expected password history for the DC"""
47         if hist_len == 0:
48             return []
49
50         # return the last n items in the list
51         return self.pwd_history[-hist_len:]
52
53     def old_valid_passwords(self, hist_len):
54         """Returns old passwords that fall outside the DC's expected history"""
55         # if PasswordHistoryLength is zero, any previous password can be valid
56         if hist_len == 0:
57             return self.all_old_passwords[:]
58
59         # just exclude our pwd_history if there's not much in it. This can
60         # happen if we've been using a lower PasswordHistoryLength setting
61         # previously
62         hist_len = min(len(self.pwd_history), hist_len)
63
64         # return any passwords up to the nth-from-last item
65         return self.all_old_passwords[:-hist_len]
66
67     def update_pwd_history(self, new_password):
68         """Updates the user's password history to reflect a password change"""
69         # we maintain 2 lists: all passwords the user has ever had, and an
70         # effective password-history that should roughly mirror the DC.
71         # pwd_history_change() handles the corner-case where we need to
72         # truncate password-history due to PasswordHistoryLength settings
73         # changes
74         if new_password in self.all_old_passwords:
75             self.all_old_passwords.remove(new_password)
76         self.all_old_passwords.append(new_password)
77
78         if new_password in self.pwd_history:
79             self.pwd_history.remove(new_password)
80         self.pwd_history.append(new_password)
81
82     def get_resultant_PSO(self):
83         """Returns the DN of the applicable PSO, or None if none applies"""
84         res = self.ldb.search(self.dn, attrs=['msDS-ResultantPSO'])
85
86         if 'msDS-ResultantPSO' in res[0]:
87             return str(res[0]['msDS-ResultantPSO'][0])
88         else:
89             return None
90
91     def get_password(self):
92         """Returns the user's current password"""
93         # current password in the last item in the list
94         return self.all_old_passwords[-1]
95
96     def set_password(self, new_password):
97         """Attempts to change a user's password"""
98         ldif = """
99 dn: %s
100 changetype: modify
101 delete: userPassword
102 userPassword: %s
103 add: userPassword
104 userPassword: %s
105 """ % (self.dn, self.get_password(), new_password)
106         # this modify will throw an exception if new_password doesn't meet the
107         # PSO constraints (which the test code catches if it's expected to
108         # fail)
109         self.ldb.modify_ldif(ldif)
110         self.update_pwd_history(new_password)
111
112     def pwd_history_change(self, old_hist_len, new_hist_len):
113         """
114         Updates the effective password history, to reflect changes on the DC.
115         When the PasswordHistoryLength applied to a user changes from a low
116         setting (e.g. 2) to a higher setting (e.g. 4), passwords #3 and #4
117         won't actually have been stored on the DC, so we need to make sure they
118         are removed them from our mirror pwd_history list.
119         """
120
121         # our list may have been tracking more passwords than the DC actually
122         # stores. Truncate the list now to match what the DC currently has
123         hist_len = min(new_hist_len, old_hist_len)
124         if hist_len == 0:
125             self.pwd_history = []
126         elif hist_len < len(self.pwd_history):
127             self.pwd_history = self.pwd_history[-hist_len:]
128
129         # corner-case where history-length goes from zero to non-zero. Windows
130         # counts the current password as being in the history even before it
131         # changes (Samba only counts it from the next change onwards). We don't
132         # exercise this in the PSO tests due to this discrepancy, but the
133         # following check will support the Windows behaviour
134         if old_hist_len == 0 and new_hist_len > 0:
135             self.pwd_history = [self.get_password()]
136
137     def set_primary_group(self, group_dn):
138         """Sets a user's primaryGroupID to be that of the specified group"""
139
140         # get the primaryGroupToken of the group
141         res = self.ldb.search(base=group_dn, attrs=["primaryGroupToken"],
142                               scope=ldb.SCOPE_BASE)
143         group_id = res[0]["primaryGroupToken"]
144
145         # set primaryGroupID attribute of the user to that group
146         m = ldb.Message()
147         m.dn = ldb.Dn(self.ldb, self.dn)
148         m["primaryGroupID"] = ldb.MessageElement(group_id, FLAG_MOD_REPLACE,
149                                                  "primaryGroupID")
150         self.ldb.modify(m)
151
152
153 class PasswordSettings:
154     def default_settings(self, samdb):
155         """
156         Returns a object representing the default password settings that will
157         take effect (i.e. when no other Fine-Grained Password Policy applies)
158         """
159         pw_attrs = ["minPwdAge", "lockoutDuration", "lockOutObservationWindow",
160                     "lockoutThreshold", "maxPwdAge", "minPwdAge",
161                     "minPwdLength", "pwdHistoryLength", "pwdProperties"]
162         res = samdb.search(samdb.domain_dn(), scope=ldb.SCOPE_BASE,
163                            attrs=pw_attrs)
164
165         self.name = "Defaults"
166         self.dn = None
167         self.ldb = samdb
168         self.precedence = 0
169         self.complexity = \
170             int(res[0]["pwdProperties"][0]) & DOMAIN_PASSWORD_COMPLEX
171         self.store_plaintext = \
172             int(res[0]["pwdProperties"][0]) & DOMAIN_PASSWORD_STORE_CLEARTEXT
173         self.password_len = int(res[0]["minPwdLength"][0])
174         self.lockout_attempts = int(res[0]["lockoutThreshold"][0])
175         self.history_len = int(res[0]["pwdHistoryLength"][0])
176         # convert to time in secs
177         self.lockout_duration = int(res[0]["lockoutDuration"][0]) / -int(1e7)
178         self.lockout_window =\
179             int(res[0]["lockOutObservationWindow"][0]) / -int(1e7)
180         self.password_age_min = int(res[0]["minPwdAge"][0]) / -int(1e7)
181         self.password_age_max = int(res[0]["maxPwdAge"][0]) / -int(1e7)
182
183     def __init__(self, name, samdb, precedence=10, complexity=True,
184                  password_len=10, lockout_attempts=0, lockout_duration=5,
185                  password_age_min=0, password_age_max=60 * 60 * 24 * 30,
186                  history_len=2, store_plaintext=False, container=None):
187
188         # if no PSO was specified, return an object representing the global
189         # password settings (i.e. the default settings, if no PSO trumps them)
190         if name is None:
191             return self.default_settings(samdb)
192
193         # only PSOs in the Password Settings Container are considered. You can
194         # create PSOs outside of this container, but it's not recommended
195         if container is None:
196             base_dn = samdb.domain_dn()
197             container = "CN=Password Settings Container,CN=System,%s" % base_dn
198
199         self.name = name
200         self.dn = "CN=%s,%s" % (name, container)
201         self.ldb = samdb
202         self.precedence = precedence
203         self.complexity = complexity
204         self.store_plaintext = store_plaintext
205         self.password_len = password_len
206         self.lockout_attempts = lockout_attempts
207         self.history_len = history_len
208         # times in secs
209         self.lockout_duration = lockout_duration
210         # lockout observation-window must be <= lockout-duration (the existing
211         # lockout tests just use the same value for both settings)
212         self.lockout_window = lockout_duration
213         self.password_age_min = password_age_min
214         self.password_age_max = password_age_max
215
216         # add the PSO to the DB
217         self.ldb.add_ldif(self.get_ldif())
218
219     def get_ldif(self):
220         complexity_str = "TRUE" if self.complexity else "FALSE"
221         plaintext_str = "TRUE" if self.store_plaintext else "FALSE"
222
223         # timestamps here are in units of -100 nano-seconds
224         lockout_duration = -int(self.lockout_duration * (1e7))
225         lockout_window = -int(self.lockout_window * (1e7))
226         min_age = -int(self.password_age_min * (1e7))
227         max_age = -int(self.password_age_max * (1e7))
228
229         # all the following fields are mandatory for the PSO object
230         ldif = """
231 dn: {0}
232 objectClass: msDS-PasswordSettings
233 msDS-PasswordSettingsPrecedence: {1}
234 msDS-PasswordReversibleEncryptionEnabled: {2}
235 msDS-PasswordHistoryLength: {3}
236 msDS-PasswordComplexityEnabled: {4}
237 msDS-MinimumPasswordLength: {5}
238 msDS-MinimumPasswordAge: {6}
239 msDS-MaximumPasswordAge: {7}
240 msDS-LockoutThreshold: {8}
241 msDS-LockoutObservationWindow: {9}
242 msDS-LockoutDuration: {10}
243 """.format(self.dn, self.precedence, plaintext_str, self.history_len,
244            complexity_str, self.password_len, min_age, max_age,
245            self.lockout_attempts, lockout_window, lockout_duration)
246
247         return ldif
248
249     def apply_to(self, user_group, operation=FLAG_MOD_ADD):
250         """Updates this Password Settings Object to apply to a user or group"""
251         m = ldb.Message()
252         m.dn = ldb.Dn(self.ldb, self.dn)
253         m["msDS-PSOAppliesTo"] = ldb.MessageElement(user_group, operation,
254                                                     "msDS-PSOAppliesTo")
255         self.ldb.modify(m)
256
257     def unapply(self, user_group):
258         """Updates this PSO to no longer apply to a user or group"""
259         # just delete the msDS-PSOAppliesTo attribute (instead of adding it)
260         self.apply_to(user_group, operation=FLAG_MOD_DELETE)
261
262     def set_precedence(self, new_precedence, samdb=None):
263         if samdb is None:
264             samdb = self.ldb
265         ldif = """
266 dn: %s
267 changetype: modify
268 replace: msDS-PasswordSettingsPrecedence
269 msDS-PasswordSettingsPrecedence: %u
270 """ % (self.dn, new_precedence)
271         samdb.modify_ldif(ldif)
272         self.precedence = new_precedence