pytests: heed assertEquals deprecation warning en-masse
[samba.git] / python / samba / tests / auth_log_samlogon.py
1 # Unix SMB/CIFS implementation.
2 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2017
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #
17
18 """
19     Tests auth logging tests that exercise SamLogon
20 """
21
22 import samba.tests
23 import os
24 from samba.samdb import SamDB
25 import samba.tests.auth_log_base
26 from samba.credentials import (
27     Credentials,
28     DONT_USE_KERBEROS,
29     CLI_CRED_NTLMv2_AUTH
30 )
31 from samba.dcerpc import ntlmssp, netlogon
32 from samba.dcerpc.dcerpc import AS_SYSTEM_MAGIC_PATH_TOKEN
33 from samba.ndr import ndr_pack
34 from samba.auth import system_session
35 from samba.tests import delete_force
36 from samba.dsdb import UF_WORKSTATION_TRUST_ACCOUNT, UF_PASSWD_NOTREQD
37 from samba.dcerpc.misc import SEC_CHAN_WKSTA
38 from samba.compat import text_type
39 from samba.dcerpc.windows_event_ids import (
40     EVT_ID_SUCCESSFUL_LOGON,
41     EVT_LOGON_NETWORK
42 )
43
44
45 class AuthLogTestsSamLogon(samba.tests.auth_log_base.AuthLogTestBase):
46
47     def setUp(self):
48         super(AuthLogTestsSamLogon, self).setUp()
49         self.lp = samba.tests.env_loadparm()
50         self.session = system_session()
51         self.ldb = SamDB(
52             session_info=self.session,
53             lp=self.lp)
54
55         self.domain = os.environ["DOMAIN"]
56         self.netbios_name = "SamLogonTest"
57         self.machinepass = "abcdefghij"
58         self.remoteAddress = AS_SYSTEM_MAGIC_PATH_TOKEN
59         self.base_dn = self.ldb.domain_dn()
60         self.samlogon_dn = ("cn=%s,cn=users,%s" %
61                            (self.netbios_name, self.base_dn))
62
63     def tearDown(self):
64         super(AuthLogTestsSamLogon, self).tearDown()
65         delete_force(self.ldb, self.samlogon_dn)
66
67     def _test_samlogon(self, binding, creds, checkFunction):
68
69         def isLastExpectedMessage(msg):
70             return (
71                 msg["type"] == "Authentication" and
72                 msg["Authentication"]["serviceDescription"] == "SamLogon" and
73                 msg["Authentication"]["authDescription"] == "network" and
74                 msg["Authentication"]["passwordType"] == "NTLMv2" and
75                 (msg["Authentication"]["eventId"] ==
76                     EVT_ID_SUCCESSFUL_LOGON) and
77                 (msg["Authentication"]["logonType"] == EVT_LOGON_NETWORK))
78
79         if binding:
80             binding = "[schannel,%s]" % binding
81         else:
82             binding = "[schannel]"
83
84         utf16pw = text_type('"' + self.machinepass + '"').encode('utf-16-le')
85         self.ldb.add({
86             "dn": self.samlogon_dn,
87             "objectclass": "computer",
88             "sAMAccountName": "%s$" % self.netbios_name,
89             "userAccountControl":
90                 str(UF_WORKSTATION_TRUST_ACCOUNT | UF_PASSWD_NOTREQD),
91             "unicodePwd": utf16pw})
92
93         machine_creds = Credentials()
94         machine_creds.guess(self.get_loadparm())
95         machine_creds.set_secure_channel_type(SEC_CHAN_WKSTA)
96         machine_creds.set_password(self.machinepass)
97         machine_creds.set_username(self.netbios_name + "$")
98
99         netlogon_conn = netlogon.netlogon("ncalrpc:%s" % binding,
100                                           self.get_loadparm(),
101                                           machine_creds)
102         challenge = b"abcdefgh"
103
104         target_info = ntlmssp.AV_PAIR_LIST()
105         target_info.count = 3
106
107         domainname = ntlmssp.AV_PAIR()
108         domainname.AvId = ntlmssp.MsvAvNbDomainName
109         domainname.Value = self.domain
110
111         computername = ntlmssp.AV_PAIR()
112         computername.AvId = ntlmssp.MsvAvNbComputerName
113         computername.Value = self.netbios_name
114
115         eol = ntlmssp.AV_PAIR()
116         eol.AvId = ntlmssp.MsvAvEOL
117         target_info.pair = [domainname, computername, eol]
118
119         target_info_blob = ndr_pack(target_info)
120
121         response = creds.get_ntlm_response(flags=CLI_CRED_NTLMv2_AUTH,
122                                            challenge=challenge,
123                                            target_info=target_info_blob)
124
125         netr_flags = 0
126
127         logon_level = netlogon.NetlogonNetworkTransitiveInformation
128         logon = samba.dcerpc.netlogon.netr_NetworkInfo()
129
130         logon.challenge = [
131             x if isinstance(x, int) else ord(x) for x in challenge]
132         logon.nt = netlogon.netr_ChallengeResponse()
133         logon.nt.length = len(response["nt_response"])
134         logon.nt.data = [
135             x if isinstance(x, int) else ord(x) for
136             x in response["nt_response"]
137         ]
138         logon.identity_info = samba.dcerpc.netlogon.netr_IdentityInfo()
139         (username, domain) = creds.get_ntlm_username_domain()
140
141         logon.identity_info.domain_name.string = domain
142         logon.identity_info.account_name.string = username
143         logon.identity_info.workstation.string = creds.get_workstation()
144
145         validation_level = samba.dcerpc.netlogon.NetlogonValidationSamInfo4
146
147         result = netlogon_conn.netr_LogonSamLogonEx(
148             os.environ["SERVER"],
149             machine_creds.get_workstation(),
150             logon_level, logon,
151             validation_level, netr_flags)
152
153         (validation, authoritative, netr_flags_out) = result
154
155         messages = self.waitForMessages(isLastExpectedMessage, netlogon_conn)
156         checkFunction(messages)
157
158     def samlogon_check(self, messages):
159
160         messages = self.remove_netlogon_messages(messages)
161         expected_messages = 5
162         self.assertEqual(expected_messages,
163                           len(messages),
164                           "Did not receive the expected number of messages")
165
166         # Check the first message it should be an Authorization
167         msg = messages[0]
168         self.assertEqual("Authorization", msg["type"])
169         self.assertEqual("DCE/RPC",
170                           msg["Authorization"]["serviceDescription"])
171         self.assertEqual("ncalrpc", msg["Authorization"]["authType"])
172         self.assertEqual("NONE", msg["Authorization"]["transportProtection"])
173         self.assertTrue(self.is_guid(msg["Authorization"]["sessionId"]))
174
175     def test_ncalrpc_samlogon(self):
176
177         creds = self.insta_creds(template=self.get_credentials(),
178                                  kerberos_state=DONT_USE_KERBEROS)
179         try:
180             self._test_samlogon("SEAL", creds, self.samlogon_check)
181         except Exception as e:
182             self.fail("Unexpected exception: " + str(e))