tests py_credentials: Fix encrypt_netr_crypt_password test
[metze/samba/wip.git] / python / samba / tests / py_credentials.py
1 # Integration tests for pycredentials
2 #
3 # Copyright (C) Catalyst IT Ltd. 2017
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 from samba.tests import TestCase, delete_force
19 import os
20
21 import samba
22 from samba.auth import system_session
23 from samba.credentials import Credentials, CLI_CRED_NTLMv2_AUTH
24 from samba.dcerpc import netlogon, ntlmssp, srvsvc
25 from samba.dcerpc.netlogon import netr_Authenticator, netr_WorkstationInformation
26 from samba.dcerpc.misc import SEC_CHAN_WKSTA
27 from samba.dsdb import (
28     UF_WORKSTATION_TRUST_ACCOUNT,
29     UF_PASSWD_NOTREQD,
30     UF_NORMAL_ACCOUNT)
31 from samba.ndr import ndr_pack
32 from samba.samdb import SamDB
33 """
34 Integration tests for pycredentials
35 """
36
37 MACHINE_NAME = "PCTM"
38 USER_NAME    = "PCTU"
39
40 class PyCredentialsTests(TestCase):
41
42     def setUp(self):
43         super(PyCredentialsTests, self).setUp()
44
45         self.server      = os.environ["SERVER"]
46         self.domain      = os.environ["DOMAIN"]
47         self.host        = os.environ["SERVER_IP"]
48         self.lp          = self.get_loadparm()
49
50         self.credentials = self.get_credentials()
51
52         self.session     = system_session()
53         self.ldb = SamDB(url="ldap://%s" % self.host,
54                          session_info=self.session,
55                          credentials=self.credentials,
56                          lp=self.lp)
57
58         self.create_machine_account()
59         self.create_user_account()
60
61
62     def tearDown(self):
63         super(PyCredentialsTests, self).tearDown()
64         delete_force(self.ldb, self.machine_dn)
65         delete_force(self.ldb, self.user_dn)
66
67     # Until a successful netlogon connection has been established there will
68     # not be a valid authenticator associated with the credentials
69     # and new_client_authenticator should throw a ValueError
70     def test_no_netlogon_connection(self):
71         self.assertRaises(ValueError,
72                           self.machine_creds.new_client_authenticator)
73
74     # Once a netlogon connection has been established,
75     # new_client_authenticator should return a value
76     #
77     def test_have_netlogon_connection(self):
78         c = self.get_netlogon_connection()
79         a = self.machine_creds.new_client_authenticator()
80         self.assertIsNotNone(a)
81
82     # Get an authenticator and use it on a sequence of operations requiring
83     # an authenticator
84     def test_client_authenticator(self):
85         c = self.get_netlogon_connection()
86         (authenticator, subsequent) = self.get_authenticator(c)
87         self.do_NetrLogonSamLogonWithFlags(c, authenticator, subsequent)
88         (authenticator, subsequent) = self.get_authenticator(c)
89         self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
90         (authenticator, subsequent) = self.get_authenticator(c)
91         self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
92         (authenticator, subsequent) = self.get_authenticator(c)
93         self.do_NetrLogonGetDomainInfo(c, authenticator, subsequent)
94
95     # Test Credentials.encrypt_netr_crypt_password
96     # By performing a NetrServerPasswordSet2
97     # And the logging on using the new password.
98     def test_encrypt_netr_password(self):
99         # Change the password
100         self.do_Netr_ServerPasswordSet2()
101         # Now use the new password to perform an operation
102         srvsvc.srvsvc("ncacn_np:%s" % (self.server),
103                       self.lp,
104                       self.machine_creds)
105
106
107    # Change the current machine account password with a
108    # netr_ServerPasswordSet2 call.
109
110     def do_Netr_ServerPasswordSet2(self):
111         c = self.get_netlogon_connection()
112         (authenticator, subsequent) = self.get_authenticator(c)
113         PWD_LEN  = 32
114         DATA_LEN = 512
115         newpass = samba.generate_random_password(PWD_LEN, PWD_LEN)
116         encoded = newpass.encode('utf-16-le')
117         pwd_len = len(encoded)
118         filler  = [ord(x) for x in os.urandom(DATA_LEN-pwd_len)]
119         pwd = netlogon.netr_CryptPassword()
120         pwd.length = pwd_len
121         pwd.data = filler + [ord(x) for x in encoded]
122         self.machine_creds.encrypt_netr_crypt_password(pwd)
123         c.netr_ServerPasswordSet2(self.server,
124                                   self.machine_creds.get_workstation(),
125                                   SEC_CHAN_WKSTA,
126                                   self.machine_name,
127                                   authenticator,
128                                   pwd)
129
130         self.machine_pass = newpass
131         self.machine_creds.set_password(newpass)
132
133     # Establish sealed schannel netlogon connection over TCP/IP
134     #
135     def get_netlogon_connection(self):
136         return netlogon.netlogon("ncacn_ip_tcp:%s[schannel,seal]" % self.server,
137                                  self.lp,
138                                  self.machine_creds)
139
140     #
141     # Create the machine account
142     def create_machine_account(self):
143         self.machine_pass = samba.generate_random_password(32, 32)
144         self.machine_name = MACHINE_NAME
145         self.machine_dn = "cn=%s,%s" % (self.machine_name, self.ldb.domain_dn())
146
147         # remove the account if it exists, this will happen if a previous test
148         # run failed
149         delete_force(self.ldb, self.machine_dn)
150
151         utf16pw = unicode(
152             '"' + self.machine_pass.encode('utf-8') + '"', 'utf-8'
153         ).encode('utf-16-le')
154         self.ldb.add({
155             "dn": self.machine_dn,
156             "objectclass": "computer",
157             "sAMAccountName": "%s$" % self.machine_name,
158             "userAccountControl":
159                 str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
160             "unicodePwd": utf16pw})
161
162         self.machine_creds = Credentials()
163         self.machine_creds.guess(self.get_loadparm())
164         self.machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
165         self.machine_creds.set_password(self.machine_pass)
166         self.machine_creds.set_username(self.machine_name + "$")
167         self.machine_creds.set_workstation(self.machine_name)
168
169     #
170     # Create a test user account
171     def create_user_account(self):
172         self.user_pass = samba.generate_random_password(32, 32)
173         self.user_name = USER_NAME
174         self.user_dn = "cn=%s,%s" % (self.user_name, self.ldb.domain_dn())
175
176         # remove the account if it exists, this will happen if a previous test
177         # run failed
178         delete_force(self.ldb, self.user_dn)
179
180         utf16pw = unicode(
181             '"' + self.user_pass.encode('utf-8') + '"', 'utf-8'
182         ).encode('utf-16-le')
183         self.ldb.add({
184             "dn": self.user_dn,
185             "objectclass": "user",
186             "sAMAccountName": "%s" % self.user_name,
187             "userAccountControl": str(UF_NORMAL_ACCOUNT),
188             "unicodePwd": utf16pw})
189
190         self.user_creds = Credentials()
191         self.user_creds.guess(self.get_loadparm())
192         self.user_creds.set_password(self.user_pass)
193         self.user_creds.set_username(self.user_name)
194         self.user_creds.set_workstation(self.machine_name)
195         pass
196
197     #
198     # Get the authenticator from the machine creds.
199     def get_authenticator(self, c):
200         auth = self.machine_creds.new_client_authenticator();
201         current  = netr_Authenticator()
202         current.cred.data = [ord(x) for x in auth["credential"]]
203         current.timestamp = auth["timestamp"]
204
205         subsequent = netr_Authenticator()
206         return (current, subsequent)
207
208     def do_NetrLogonSamLogonWithFlags(self, c, current, subsequent):
209         logon = samlogon_logon_info(self.domain,
210                                     self.machine_name,
211                                     self.user_creds)
212
213         logon_level = netlogon.NetlogonNetworkTransitiveInformation
214         validation_level = netlogon.NetlogonValidationSamInfo4
215         netr_flags = 0
216         c.netr_LogonSamLogonWithFlags(self.server,
217                                       self.user_creds.get_workstation(),
218                                       current,
219                                       subsequent,
220                                       logon_level,
221                                       logon,
222                                       validation_level,
223                                       netr_flags)
224
225     def do_NetrLogonGetDomainInfo(self, c, current, subsequent):
226         query = netr_WorkstationInformation()
227
228         c.netr_LogonGetDomainInfo(self.server,
229                                   self.user_creds.get_workstation(),
230                                   current,
231                                   subsequent,
232                                   2,
233                                   query)
234
235 #
236 # Build the logon data required by NetrLogonSamLogonWithFlags
237 def samlogon_logon_info(domain_name, computer_name, creds):
238
239     target_info_blob = samlogon_target(domain_name, computer_name)
240
241     challenge = b"abcdefgh"
242     # User account under test
243     response = creds.get_ntlm_response(flags=CLI_CRED_NTLMv2_AUTH,
244                                        challenge=challenge,
245                                        target_info=target_info_blob)
246
247     logon = netlogon.netr_NetworkInfo()
248
249     logon.challenge     = [ord(x) for x in challenge]
250     logon.nt            = netlogon.netr_ChallengeResponse()
251     logon.nt.length     = len(response["nt_response"])
252     logon.nt.data       = [ord(x) for x in response["nt_response"]]
253     logon.identity_info = netlogon.netr_IdentityInfo()
254
255     (username, domain)  = creds.get_ntlm_username_domain()
256     logon.identity_info.domain_name.string  = domain
257     logon.identity_info.account_name.string = username
258     logon.identity_info.workstation.string  = creds.get_workstation()
259
260     return logon
261
262 #
263 # Build the samlogon target info.
264 def samlogon_target(domain_name, computer_name):
265     target_info = ntlmssp.AV_PAIR_LIST()
266     target_info.count = 3
267     computername = ntlmssp.AV_PAIR()
268     computername.AvId = ntlmssp.MsvAvNbComputerName
269     computername.Value = computer_name
270
271     domainname = ntlmssp.AV_PAIR()
272     domainname.AvId = ntlmssp.MsvAvNbDomainName
273     domainname.Value = domain_name
274
275     eol = ntlmssp.AV_PAIR()
276     eol.AvId = ntlmssp.MsvAvEOL
277     target_info.pair = [domainname, computername, eol]
278
279     return ndr_pack(target_info)