Debian Codegraph @

tests/test_auth.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]>
3 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
4
5 import os
6 import socket
7 import ssl
8 import sys
9 import typing
10
11 import pytest
12
13 import spnego
14 import spnego._credssp
15 import spnego._gss
16 import spnego._sspi
17 import spnego.channel_bindings
18 import spnego.iov
19 import spnego.tls
20 from spnego._context import (
21 IOVUnwrapResult,
22 IOVWrapResult,
23 UnwrapResult,
24 WinRMWrapResult,
25 WrapResult,
26 )
27 from spnego._credssp_structures import TSPasswordCreds
28 from spnego._ntlm_raw.crypto import lmowfv1, ntowfv1
29 from spnego._spnego import NegTokenResp, unpack_token
30 from spnego.exceptions import (
31 InvalidCredentialError,
32 InvalidTokenError,
33 NoCredentialError,
34 SpnegoError,
35 )
36
37
38 def _message_test(client: spnego.ContextProxy, server: spnego.ContextProxy) -> None:
39 # Client wrap
40 plaintext = os.urandom(32)
41
42 c_wrap_result = client.wrap(plaintext)
43
44 assert isinstance(c_wrap_result, WrapResult)
45 assert c_wrap_result.encrypted
46 assert c_wrap_result.data != plaintext
47
48 # Server unwrap
49 s_unwrap_result = server.unwrap(c_wrap_result.data)
50
51 assert isinstance(s_unwrap_result, UnwrapResult)
52 assert s_unwrap_result.data == plaintext
53 assert s_unwrap_result.encrypted
54 assert s_unwrap_result.qop == 0
55
56 # Server wrap
57 plaintext = os.urandom(17)
58
59 s_wrap_result = server.wrap(plaintext)
60
61 assert isinstance(s_wrap_result, WrapResult)
62 assert s_wrap_result.encrypted
63 assert s_wrap_result.data != plaintext
64
65 # Client unwrap
66 c_unwrap_result = client.unwrap(s_wrap_result.data)
67
68 assert isinstance(c_unwrap_result, UnwrapResult)
69 assert c_unwrap_result.data == plaintext
70 assert c_unwrap_result.encrypted
71 assert c_unwrap_result.qop == 0
72
73 # CredSSP doesnt' have signature methods
74 if isinstance(client, spnego._credssp.CredSSPProxy):
75 return
76
77 # Client sign, server verify
78 plaintext = os.urandom(3)
79
80 c_sig = client.sign(plaintext)
81 server.verify(plaintext, c_sig)
82
83 # Server sign, client verify
84 plaintext = os.urandom(9)
85
86 s_sig = server.sign(plaintext)
87 client.verify(plaintext, s_sig)
88
89 # Can only continue if we are not testing Kerberos, or we are testing Kerberos and GSSAPI is available.
90 if client.negotiated_protocol == "kerberos" and not client.iov_available():
91 return
92
93 plaintext = os.urandom(16)
94 c_winrm_wrap_result = client.wrap_winrm(plaintext)
95 assert isinstance(c_winrm_wrap_result, WinRMWrapResult)
96 assert isinstance(c_winrm_wrap_result.header, bytes)
97 assert isinstance(c_winrm_wrap_result.data, bytes)
98 assert isinstance(c_winrm_wrap_result.padding_length, int)
99
100 s_winrm_unwrap_result = server.unwrap_winrm(c_winrm_wrap_result.header, c_winrm_wrap_result.data)
101 assert s_winrm_unwrap_result == plaintext
102
103 plaintext = os.urandom(16)
104 s_winrm_wrap_result = server.wrap_winrm(plaintext)
105 assert isinstance(s_winrm_wrap_result, WinRMWrapResult)
106 assert isinstance(s_winrm_wrap_result.header, bytes)
107 assert isinstance(s_winrm_wrap_result.data, bytes)
108 assert isinstance(s_winrm_wrap_result.padding_length, int)
109
110 c_winrm_unwrap_result = client.unwrap_winrm(s_winrm_wrap_result.header, s_winrm_wrap_result.data)
111 assert c_winrm_unwrap_result == plaintext
112
113 # Can only continue if using Kerberos auth and IOV is available
114 if client.negotiated_protocol == "ntlm" or not client.iov_available():
115 return
116
117 plaintext = os.urandom(16)
118 c_iov_wrap_res = client.wrap_iov([spnego.iov.BufferType.header, plaintext, spnego.iov.BufferType.padding])
119 assert isinstance(c_iov_wrap_res, IOVWrapResult)
120 assert c_iov_wrap_res.encrypted
121 assert len(c_iov_wrap_res.buffers) == 3
122 assert c_iov_wrap_res.buffers[1].data != plaintext
123
124 s_iov_unwrap_res = server.unwrap_iov(c_iov_wrap_res.buffers)
125 assert isinstance(s_iov_unwrap_res, IOVUnwrapResult)
126 assert s_iov_unwrap_res.encrypted
127 assert s_iov_unwrap_res.qop == 0
128 assert len(s_iov_unwrap_res.buffers) == 3
129 assert s_iov_unwrap_res.buffers[1].data == plaintext
130
131 plaintext = os.urandom(16)
132 s_iov_wrap_res = server.wrap_iov([spnego.iov.BufferType.header, plaintext, spnego.iov.BufferType.padding])
133 assert isinstance(s_iov_wrap_res, IOVWrapResult)
134 assert s_iov_wrap_res.encrypted
135 assert len(s_iov_wrap_res.buffers) == 3
136 assert s_iov_wrap_res.buffers[1].data != plaintext
137
138 c_iov_unwrap_res = client.unwrap_iov(s_iov_wrap_res.buffers)
139 assert isinstance(c_iov_unwrap_res, IOVUnwrapResult)
140 assert c_iov_unwrap_res.encrypted
141 assert c_iov_unwrap_res.qop == 0
142 assert len(c_iov_unwrap_res.buffers) == 3
143 assert c_iov_unwrap_res.buffers[1].data == plaintext
144
145
146 def _ntlm_test(
147 client: spnego.ContextProxy,
148 server: spnego.ContextProxy,
149 test_session_key: bool = True,
150 channel_bindings: typing.Optional[spnego.channel_bindings.GssChannelBindings] = None,
151 ) -> None:
152 assert not client.complete
153 assert not server.complete
154
155 # Build negotiate msg
156 negotiate = client.step(channel_bindings=channel_bindings)
157
158 assert isinstance(negotiate, bytes)
159 assert not client.complete
160 assert not server.complete
161
162 # Process negotiate msg
163 challenge = server.step(negotiate, channel_bindings=channel_bindings)
164
165 assert isinstance(challenge, bytes)
166 assert not client.complete
167 assert not server.complete
168
169 # Process challenge and build authenticate
170 authenticate = client.step(challenge, channel_bindings=channel_bindings)
171
172 assert isinstance(authenticate, bytes)
173 if test_session_key:
174 assert isinstance(client.session_key, bytes)
175
176 assert client.complete
177 assert not server.complete
178
179 # Process authenticate
180 auth_response = server.step(authenticate, channel_bindings=channel_bindings)
181
182 assert auth_response is None
183 if test_session_key:
184 assert isinstance(client.session_key, bytes)
185 assert isinstance(server.session_key, bytes)
186
187 assert client.complete
188 assert server.complete
189
190 assert client.negotiated_protocol == "ntlm"
191 assert server.negotiated_protocol == "ntlm"
192
193
194 def test_invalid_protocol():
195 expected = "Invalid protocol specified 'fake', must be kerberos, negotiate, or ntlm"
196
197 with pytest.raises(ValueError, match=expected):
198 spnego.client(None, None, protocol="fake")
199
200 with pytest.raises(ValueError, match=expected):
201 spnego.server(protocol="fake")
202
203
204 def test_protocol_not_supported():
205 with pytest.raises(ValueError, match="Protocol kerberos is not available"):
206 spnego.client(None, None, protocol="kerberos", options=spnego.NegotiateOptions.use_ntlm)
207
208
209 def test_no_valid_credential_available_single_available_protocol():
210 credentials: typing.List[spnego.Credential] = [
211 spnego.KerberosCCache("FILE:test"),
212 spnego.KerberosKeytab("principal", "keytab"),
213 ]
214 with pytest.raises(
215 NoCredentialError, match="A credential for ntlm is needed but only found credentials for kerberos"
216 ):
217 spnego.client(credentials, protocol="ntlm", options=spnego.NegotiateOptions.use_ntlm)
218
219
220 def test_no_valid_credential_available_multiple_available_protocol():
221 credentials: typing.List[spnego.Credential] = [
222 spnego.NTLMHash("username", "lm_hash", "nt_hash"),
223 spnego.KerberosKeytab("principal", "keytab"),
224 ]
225 with pytest.raises(
226 NoCredentialError, match="A credential for credssp is needed but only found credentials for kerberos, ntlm"
227 ):
228 spnego.client(credentials, protocol="credssp")
229
230
231 # Negotiate scenarios
232
233
234 def test_negotiate_with_kerberos(kerb_cred):
235 if sys.platform == "darwin":
236 pytest.skip("Environment problem with GSS.Framework - skip")
237
238 c = spnego.client(
239 kerb_cred.user_princ, None, hostname=socket.getfqdn(), options=spnego.NegotiateOptions.use_negotiate
240 )
241 s = spnego.server(options=spnego.NegotiateOptions.use_negotiate)
242
243 assert c.get_extra_info("invalid") is None
244 assert c.get_extra_info("invalid", "default") == "default"
245
246 token1 = c.step()
247 assert isinstance(token1, bytes)
248
249 token2 = s.step(token1)
250 assert isinstance(token2, bytes)
251
252 token3 = c.step(token2)
253 assert token3 is None
254
255 # Make sure it reports the right protocol
256 assert c.negotiated_protocol == "kerberos"
257 assert s.negotiated_protocol == "kerberos"
258
259 assert isinstance(c.session_key, bytes)
260 assert isinstance(s.session_key, bytes)
261 assert c.session_key == s.session_key
262
263 assert c.client_principal is None
264 assert s.client_principal == kerb_cred.user_princ
265
266 assert c.context_attr & spnego.ContextReq.mutual_auth
267 assert s.context_attr & spnego.ContextReq.mutual_auth
268
269 _message_test(c, s)
270
271 c = c.new_context()
272 s = s.new_context()
273
274 token1 = c.step()
275 assert isinstance(token1, bytes)
276
277 token2 = s.step(token1)
278 assert isinstance(token2, bytes)
279
280 token3 = c.step(token2)
281 assert token3 is None
282
283 # Make sure it reports the right protocol
284 assert c.negotiated_protocol == "kerberos"
285 assert s.negotiated_protocol == "kerberos"
286
287 assert isinstance(c.session_key, bytes)
288 assert isinstance(s.session_key, bytes)
289 assert c.session_key == s.session_key
290
291 assert c.client_principal is None
292 assert s.client_principal == kerb_cred.user_princ
293
294 assert c.context_attr & spnego.ContextReq.mutual_auth
295 assert s.context_attr & spnego.ContextReq.mutual_auth
296
297 _message_test(c, s)
298
299
300 def test_negotiate_with_kerberos_no_integrity(kerb_cred):
301 if sys.platform == "darwin":
302 pytest.skip("Environment problem with GSS.Framework - skip")
303
304 c = spnego.client(
305 kerb_cred.user_princ,
306 None,
307 hostname=socket.getfqdn(),
308 options=spnego.NegotiateOptions.use_negotiate,
309 context_req=spnego.ContextReq.mutual_auth | spnego.ContextReq.sequence_detect | spnego.ContextReq.no_integrity,
310 )
311 s = spnego.server(options=spnego.NegotiateOptions.use_negotiate)
312
313 assert c.get_extra_info("invalid") is None
314 assert c.get_extra_info("invalid", "default") == "default"
315
316 token1 = c.step()
317 assert isinstance(token1, bytes)
318
319 token2 = s.step(token1)
320 assert isinstance(token2, bytes)
321
322 token3 = c.step(token2)
323 assert token3 is None
324
325 # Make sure it reports the right protocol
326 assert c.negotiated_protocol == "kerberos"
327 assert s.negotiated_protocol == "kerberos"
328
329 assert isinstance(c.session_key, bytes)
330 assert isinstance(s.session_key, bytes)
331 assert c.session_key == s.session_key
332
333 assert c.client_principal is None
334 assert s.client_principal == kerb_cred.user_princ
335
336 assert c.context_attr == spnego.ContextReq.mutual_auth | spnego.ContextReq.sequence_detect
337 assert s.context_attr == spnego.ContextReq.mutual_auth | spnego.ContextReq.sequence_detect
338
339 _message_test(c, s)
340
341 c = c.new_context()
342 s = s.new_context()
343
344 token1 = c.step()
345 assert isinstance(token1, bytes)
346
347 token2 = s.step(token1)
348 assert isinstance(token2, bytes)
349
350 token3 = c.step(token2)
351 assert token3 is None
352
353 # Make sure it reports the right protocol
354 assert c.negotiated_protocol == "kerberos"
355 assert s.negotiated_protocol == "kerberos"
356
357 assert isinstance(c.session_key, bytes)
358 assert isinstance(s.session_key, bytes)
359 assert c.session_key == s.session_key
360
361 assert c.client_principal is None
362 assert s.client_principal == kerb_cred.user_princ
363
364 assert c.context_attr & spnego.ContextReq.mutual_auth
365 assert s.context_attr & spnego.ContextReq.mutual_auth
366
367 _message_test(c, s)
368
369
370 def test_negotiate_through_python_ntlm(ntlm_cred):
371 # Build the initial context and assert the defaults.
372 c = spnego.client(
373 ntlm_cred[0],
374 ntlm_cred[1],
375 protocol="negotiate",
376 context_req=spnego.ContextReq.delegate | spnego.ContextReq.default,
377 options=spnego.NegotiateOptions.use_negotiate,
378 )
379 s = spnego.server(protocol="negotiate")
380
381 assert c.get_extra_info("invalid") is None
382 assert c.get_extra_info("invalid", "default") == "default"
383
384 assert not c.complete
385 assert not s.complete
386
387 negotiate = c.step()
388
389 assert isinstance(negotiate, bytes)
390 assert not c.complete
391 assert not s.complete
392
393 challenge = s.step(negotiate)
394
395 assert isinstance(challenge, bytes)
396 assert not c.complete
397 assert not s.complete
398
399 authenticate = c.step(challenge)
400
401 assert isinstance(authenticate, bytes)
402 assert not c.complete
403 assert not s.complete
404
405 mech_list_mic = s.step(authenticate)
406
407 assert isinstance(mech_list_mic, bytes)
408 assert not c.complete
409 assert s.complete
410
411 assert c.client_principal is None
412 assert s.client_principal == ntlm_cred[0]
413
414 mech_list_resp = c.step(mech_list_mic)
415
416 assert mech_list_resp is None
417 assert c.complete
418 assert s.complete
419 assert c.negotiated_protocol == "ntlm"
420 assert s.negotiated_protocol == "ntlm"
421
422 _message_test(c, s)
423
424 c = c.new_context()
425 s = s.new_context()
426
427 negotiate = c.step()
428
429 assert isinstance(negotiate, bytes)
430 assert not c.complete
431 assert not s.complete
432
433 challenge = s.step(negotiate)
434
435 assert isinstance(challenge, bytes)
436 assert not c.complete
437 assert not s.complete
438
439 authenticate = c.step(challenge)
440
441 assert isinstance(authenticate, bytes)
442 assert not c.complete
443 assert not s.complete
444
445 mech_list_mic = s.step(authenticate)
446
447 assert isinstance(mech_list_mic, bytes)
448 assert not c.complete
449 assert s.complete
450
451 assert c.client_principal is None
452 assert s.client_principal == ntlm_cred[0]
453
454 mech_list_resp = c.step(mech_list_mic)
455
456 assert mech_list_resp is None
457 assert c.complete
458 assert s.complete
459 assert c.negotiated_protocol == "ntlm"
460 assert s.negotiated_protocol == "ntlm"
461
462 _message_test(c, s)
463
464
465 def test_negotiate_with_raw_ntlm(ntlm_cred):
466 c = spnego.client(ntlm_cred[0], ntlm_cred[1], hostname=socket.gethostname(), protocol="ntlm")
467 s = spnego.server(options=spnego.NegotiateOptions.use_negotiate)
468
469 assert c.get_extra_info("invalid") is None
470 assert c.get_extra_info("invalid", "default") == "default"
471
472 negotiate = c.step()
473 assert negotiate is not None
474 assert negotiate.startswith(b"NTLMSSP\x00\x01")
475 assert not c.complete
476 assert not s.complete
477
478 challenge = s.step(negotiate)
479 assert challenge is not None
480 assert challenge.startswith(b"NTLMSSP\x00\x02")
481 assert not c.complete
482 assert not s.complete
483
484 authenticate = c.step(challenge)
485 assert authenticate is not None
486 assert authenticate.startswith(b"NTLMSSP\x00\x03")
487 assert c.complete
488 assert not s.complete
489
490 final = s.step(authenticate)
491 assert final is None
492 assert c.complete
493 assert s.complete
494
495 _message_test(c, s)
496
497 c = c.new_context()
498 s = s.new_context()
499
500 negotiate = c.step()
501 assert negotiate is not None
502 assert negotiate.startswith(b"NTLMSSP\x00\x01")
503 assert not c.complete
504 assert not s.complete
505
506 challenge = s.step(negotiate)
507 assert challenge is not None
508 assert challenge.startswith(b"NTLMSSP\x00\x02")
509 assert not c.complete
510 assert not s.complete
511
512 authenticate = c.step(challenge)
513 assert authenticate is not None
514 assert authenticate.startswith(b"NTLMSSP\x00\x03")
515 assert c.complete
516 assert not s.complete
517
518 final = s.step(authenticate)
519 assert final is None
520 assert c.complete
521 assert s.complete
522
523 _message_test(c, s)
524
525
526 def test_negotiate_with_ntlm_hash(ntlm_cred):
527 cred = spnego.NTLMHash(username=ntlm_cred[0], nt_hash=ntowfv1(ntlm_cred[1]).hex())
528 c = spnego.client(cred, hostname=socket.gethostname())
529 s = spnego.server()
530
531 negotiate = c.step()
532 assert negotiate is not None
533 assert b"NTLMSSP\x00\x01" in negotiate
534 assert not c.complete
535 assert not s.complete
536
537 challenge = s.step(negotiate)
538 assert challenge is not None
539 assert b"NTLMSSP\x00\x02" in challenge
540 assert not c.complete
541 assert not s.complete
542
543 authenticate = c.step(challenge)
544 assert authenticate is not None
545 assert b"NTLMSSP\x00\x03" in authenticate
546 assert not c.complete
547 assert not s.complete
548
549 mic = s.step(authenticate)
550 assert mic is not None
551 assert not c.complete
552 assert s.complete
553
554 final = c.step(mic)
555 assert final is None
556 assert c.complete
557 assert s.complete
558
559 _message_test(c, s)
560
561 c = c.new_context()
562 s = s.new_context()
563
564 negotiate = c.step()
565 assert negotiate is not None
566 assert b"NTLMSSP\x00\x01" in negotiate
567 assert not c.complete
568 assert not s.complete
569
570 challenge = s.step(negotiate)
571 assert challenge is not None
572 assert b"NTLMSSP\x00\x02" in challenge
573 assert not c.complete
574 assert not s.complete
575
576 authenticate = c.step(challenge)
577 assert authenticate is not None
578 assert b"NTLMSSP\x00\x03" in authenticate
579 assert not c.complete
580 assert not s.complete
581
582 mic = s.step(authenticate)
583 assert mic is not None
584 assert not c.complete
585 assert s.complete
586
587 final = c.step(mic)
588 assert final is None
589 assert c.complete
590 assert s.complete
591
592 _message_test(c, s)
593
594
595 def test_negotiate_with_ntlm_and_duplicate_response_token(ntlm_cred):
596 c = spnego.client(
597 ntlm_cred[0], ntlm_cred[1], hostname=socket.gethostname(), options=spnego.NegotiateOptions.use_negotiate
598 )
599 s = spnego.server(options=spnego.NegotiateOptions.use_negotiate)
600
601 assert c.get_extra_info("invalid") is None
602 assert c.get_extra_info("invalid", "default") == "default"
603
604 negotiate = c.step()
605 assert not c.complete
606 assert not s.complete
607
608 challenge = s.step(negotiate)
609 assert challenge is not None
610
611 # Set the mechListMIC to the same value as responseToken in the challenge to replicate the bug this is testing
612 neg_token_resp = unpack_token(challenge)
613 assert isinstance(neg_token_resp, NegTokenResp)
614 neg_token_resp.mech_list_mic = neg_token_resp.response_token
615 challenge = neg_token_resp.pack()
616
617 assert not c.complete
618 assert not s.complete
619
620 authenticate = c.step(challenge)
621 assert not c.complete
622 assert not s.complete
623
624 mech_list = s.step(authenticate)
625 assert not c.complete
626 assert s.complete
627
628 final = c.step(mech_list)
629 assert final is None
630 assert c.complete
631 assert s.complete
632
633 _message_test(c, s)
634
635
636 # NTLM scenarios
637
638
639 @pytest.mark.parametrize("lm_compat_level", [None, 0, 1, 2])
640 def test_ntlm_auth(lm_compat_level, ntlm_cred, monkeypatch):
641 if lm_compat_level is not None:
642 monkeypatch.setenv("LM_COMPAT_LEVEL", str(lm_compat_level))
643
644 # Build the initial context and assert the defaults.
645 c = spnego.client(ntlm_cred[0], ntlm_cred[1], protocol="ntlm", options=spnego.NegotiateOptions.use_ntlm)
646 s = spnego.server(protocol="ntlm", options=spnego.NegotiateOptions.use_ntlm)
647
648 assert c.get_extra_info("invalid") is None
649 assert c.get_extra_info("invalid", "default") == "default"
650
651 _ntlm_test(c, s)
652
653 assert c.client_principal is None
654 assert s.client_principal == ntlm_cred[0]
655
656 with pytest.warns(DeprecationWarning, match="username is deprecated"):
657 c.username
658
659 with pytest.warns(DeprecationWarning, match="password is deprecated"):
660 c.password
661
662 _message_test(c, s)
663
664 c = c.new_context()
665 s = s.new_context()
666
667 _ntlm_test(c, s)
668
669 assert c.client_principal is None
670 assert s.client_principal == ntlm_cred[0]
671
672 _message_test(c, s)
673
674
675 @pytest.mark.parametrize(
676 "client_opt, server_opt",
677 [
678 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_sspi),
679 (spnego.NegotiateOptions.use_ntlm, spnego.NegotiateOptions.use_sspi),
680 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_ntlm),
681 (spnego.NegotiateOptions.use_ntlm, spnego.NegotiateOptions.use_ntlm),
682 # Cannot test with gssapi as the existing version has a bug with this scenario.
683 ],
684 )
685 def test_sspi_ntlm_auth_no_sign_or_seal(client_opt, server_opt, ntlm_cred):
686 if client_opt & spnego.NegotiateOptions.use_gssapi or server_opt & spnego.NegotiateOptions.use_gssapi:
687 if "ntlm" not in spnego._gss.GSSAPIProxy.available_protocols():
688 pytest.skip("Test requires NTLM to be available through GSSAPI")
689
690 elif client_opt & spnego.NegotiateOptions.use_sspi or server_opt & spnego.NegotiateOptions.use_sspi:
691 if "ntlm" not in spnego._sspi.SSPIProxy.available_protocols():
692 pytest.skip("Test requires NTLM to be available through SSPI")
693
694 # Build the initial context and assert the defaults.
695 c = spnego.client(
696 ntlm_cred[0],
697 ntlm_cred[1],
698 hostname=socket.gethostname(),
699 options=client_opt,
700 protocol="ntlm",
701 context_req=spnego.ContextReq.none,
702 )
703 s = spnego.server(options=server_opt, protocol="ntlm", context_req=spnego.ContextReq.none)
704
705 assert c.get_extra_info("invalid") is None
706 assert c.get_extra_info("invalid", "default") == "default"
707
708 _ntlm_test(c, s)
709
710 assert c.client_principal is None
711 assert s.client_principal == ntlm_cred[0]
712
713 # Client sign, server verify
714 plaintext = os.urandom(3)
715
716 c_sig = c.sign(plaintext)
717 s.verify(plaintext, c_sig)
718
719 # Server sign, client verify
720 plaintext = os.urandom(9)
721
722 s_sig = s.sign(plaintext)
723 c.verify(plaintext, s_sig)
724
725
726 @pytest.mark.skipif(
727 "ntlm" not in spnego._sspi.SSPIProxy.available_protocols(), reason="Test requires NTLM to be available through SSPI"
728 )
729 @pytest.mark.parametrize(
730 "client_opt, server_opt, cbt, cbt_with_step",
731 [
732 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_sspi, False, False),
733 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_sspi, True, False),
734 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_sspi, True, True),
735 (spnego.NegotiateOptions.use_ntlm, spnego.NegotiateOptions.use_sspi, False, False),
736 (spnego.NegotiateOptions.use_ntlm, spnego.NegotiateOptions.use_sspi, True, False),
737 (spnego.NegotiateOptions.use_ntlm, spnego.NegotiateOptions.use_sspi, True, True),
738 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_ntlm, False, False),
739 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_ntlm, True, False),
740 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_ntlm, True, False),
741 (spnego.NegotiateOptions.use_sspi, spnego.NegotiateOptions.use_ntlm, True, True),
742 ],
743 )
744 def test_sspi_ntlm_auth(client_opt, server_opt, cbt, cbt_with_step, ntlm_cred):
745 # Build the initial context and assert the defaults.
746 step_kwargs: typing.Dict[str, typing.Any] = {}
747 client_kwargs: typing.Dict[str, typing.Any] = {}
748 server_kwargs: typing.Dict[str, typing.Any] = {}
749
750 if cbt:
751 bindings = spnego.channel_bindings.GssChannelBindings(application_data=b"test_data:\x00\x01")
752 if cbt_with_step:
753 step_kwargs["channel_bindings"] = bindings
754 client_kwargs["channel_bindings"] = spnego.channel_bindings.GssChannelBindings(
755 application_data=b"test_data:\x00\x02"
756 )
757 server_kwargs["channel_bindings"] = spnego.channel_bindings.GssChannelBindings(
758 application_data=b"test_data:\x00\x03"
759 )
760 else:
761 client_kwargs["channel_bindings"] = bindings
762 server_kwargs["channel_bindings"] = bindings
763
764 c = spnego.client(
765 ntlm_cred[0],
766 ntlm_cred[1],
767 hostname=socket.gethostname(),
768 options=client_opt,
769 protocol="ntlm",
770 **client_kwargs,
771 )
772 s = spnego.server(options=server_opt, protocol="ntlm", **server_kwargs)
773
774 assert c.get_extra_info("invalid") is None
775 assert c.get_extra_info("invalid", "default") == "default"
776
777 _ntlm_test(c, s, **step_kwargs)
778
779 assert c.client_principal is None
780 assert s.client_principal == ntlm_cred[0]
781
782 _message_test(c, s)
783
784 c = c.new_context()
785 s = s.new_context()
786
787 _ntlm_test(c, s, **step_kwargs)
788
789 assert c.client_principal is None
790 assert s.client_principal == ntlm_cred[0]
791
792 _message_test(c, s)
793
794
795 @pytest.mark.skipif(
796 "ntlm" not in spnego._sspi.SSPIProxy.available_protocols(), reason="Test requires NTLM to be available through SSPI"
797 )
798 @pytest.mark.parametrize("lm_compat_level", [1, 2, 3])
799 def test_sspi_ntlm_lm_compat(lm_compat_level, ntlm_cred, monkeypatch):
800 monkeypatch.setenv("LM_COMPAT_LEVEL", str(lm_compat_level))
801 c = spnego.client(
802 ntlm_cred[0],
803 ntlm_cred[1],
804 hostname=socket.gethostname(),
805 protocol="ntlm",
806 options=spnego.NegotiateOptions.use_ntlm,
807 )
808 s = spnego.server(options=spnego.NegotiateOptions.use_sspi, protocol="ntlm")
809
810 assert c.get_extra_info("invalid") is None
811 assert c.get_extra_info("invalid", "default") == "default"
812
813 _ntlm_test(c, s)
814
815 assert c.client_principal is None
816 assert s.client_principal == ntlm_cred[0]
817
818 _message_test(c, s)
819
820 c = c.new_context()
821 s = s.new_context()
822
823 _ntlm_test(c, s)
824
825 assert c.client_principal is None
826 assert s.client_principal == ntlm_cred[0]
827
828 _message_test(c, s)
829
830
831 def test_ntlm_with_explicit_ntlm_hash(ntlm_cred):
832 ntlm_hashes = f"{lmowfv1(ntlm_cred[1]).hex()}:{ntowfv1(ntlm_cred[1]).hex()}"
833 c = spnego.client(
834 ntlm_cred[0], ntlm_hashes, hostname=socket.gethostname(), options=spnego.NegotiateOptions.none, protocol="ntlm"
835 )
836 s = spnego.server(options=spnego.NegotiateOptions.use_ntlm, protocol="ntlm")
837
838 assert c.get_extra_info("invalid") is None
839 assert c.get_extra_info("invalid", "default") == "default"
840
841 _ntlm_test(c, s)
842
843 assert c.client_principal is None
844 assert s.client_principal == ntlm_cred[0]
845
846 _message_test(c, s)
847
848 c = c.new_context()
849 s = s.new_context()
850 _ntlm_test(c, s)
851
852 assert c.client_principal is None
853 assert s.client_principal == ntlm_cred[0]
854
855 _message_test(c, s)
856
857
858 def test_ntlm_with_unsupported_credential():
859 with pytest.raises(
860 InvalidCredentialError, match="Invalid username/credential specified, must be a string or Credential object."
861 ):
862 spnego.client(123, protocol="ntlm") # type: ignore[arg-type] # Testing this scenario
863
864
865 # Kerberos scenarios
866
867
868 @pytest.mark.parametrize("explicit_user", [False, True])
869 def test_gssapi_kerberos_auth(explicit_user, kerb_cred):
870 if sys.platform == "darwin":
871 pytest.skip("Environment problem with GSS.Framework - skip")
872
873 username = None
874 if explicit_user:
875 username = kerb_cred.user_princ
876
877 c = spnego.client(
878 username, None, hostname=kerb_cred.hostname, protocol="kerberos", options=spnego.NegotiateOptions.use_gssapi
879 )
880 s = spnego.server(options=spnego.NegotiateOptions.use_gssapi, protocol="kerberos")
881
882 assert c.get_extra_info("invalid") is None
883 assert c.get_extra_info("invalid", "default") == "default"
884 assert not c.complete
885 assert not s.complete
886 assert s.negotiated_protocol == "kerberos"
887
888 with pytest.raises(SpnegoError, match="Retrieving session key"):
889 _ = c.session_key
890
891 with pytest.raises(SpnegoError, match="Retrieving session key"):
892 _ = s.session_key
893
894 token1 = c.step()
895 assert isinstance(token1, bytes)
896 assert not c.complete
897 assert not s.complete
898 assert s.negotiated_protocol == "kerberos"
899
900 token2 = s.step(token1)
901 assert isinstance(token2, bytes)
902 assert not c.complete
903 assert s.complete
904 assert s.negotiated_protocol == "kerberos"
905
906 token3 = c.step(token2)
907 assert token3 is None
908 assert c.complete
909 assert s.complete
910 assert isinstance(c.session_key, bytes)
911 assert isinstance(s.session_key, bytes)
912 assert c.session_key == s.session_key
913
914 assert c.client_principal is None
915 assert s.client_principal == kerb_cred.user_princ
916
917 _message_test(c, s)
918
919 c = c.new_context()
920 s = s.new_context()
921
922 token1 = c.step()
923 assert isinstance(token1, bytes)
924 assert not c.complete
925 assert not s.complete
926 assert s.negotiated_protocol == "kerberos"
927
928 token2 = s.step(token1)
929 assert isinstance(token2, bytes)
930 assert not c.complete
931 assert s.complete
932 assert s.negotiated_protocol == "kerberos"
933
934 token3 = c.step(token2)
935 assert token3 is None
936 assert c.complete
937 assert s.complete
938 assert isinstance(c.session_key, bytes)
939 assert isinstance(s.session_key, bytes)
940 assert c.session_key == s.session_key
941
942 assert c.client_principal is None
943 assert s.client_principal == kerb_cred.user_princ
944
945 _message_test(c, s)
946
947
948 @pytest.mark.parametrize("explicit_user", [False, True])
949 def test_gssapi_kerberos_auth_no_integrity(explicit_user, kerb_cred):
950 if sys.platform == "darwin":
951 pytest.skip("Environment problem with GSS.Framework - skip")
952
953 username = None
954 if explicit_user:
955 username = kerb_cred.user_princ
956
957 c = spnego.client(
958 username,
959 None,
960 hostname=kerb_cred.hostname,
961 protocol="kerberos",
962 options=spnego.NegotiateOptions.use_gssapi,
963 context_req=spnego.ContextReq.mutual_auth | spnego.ContextReq.sequence_detect | spnego.ContextReq.no_integrity,
964 )
965 s = spnego.server(options=spnego.NegotiateOptions.use_gssapi, protocol="kerberos")
966
967 assert c.get_extra_info("invalid") is None
968 assert c.get_extra_info("invalid", "default") == "default"
969 assert not c.complete
970 assert not s.complete
971 assert s.negotiated_protocol == "kerberos"
972
973 with pytest.raises(SpnegoError, match="Retrieving session key"):
974 _ = c.session_key
975
976 with pytest.raises(SpnegoError, match="Retrieving session key"):
977 _ = s.session_key
978
979 token1 = c.step()
980 assert isinstance(token1, bytes)
981 assert not c.complete
982 assert not s.complete
983 assert s.negotiated_protocol == "kerberos"
984
985 token2 = s.step(token1)
986 assert isinstance(token2, bytes)
987 assert not c.complete
988 assert s.complete
989 assert s.negotiated_protocol == "kerberos"
990
991 token3 = c.step(token2)
992 assert token3 is None
993 assert c.complete
994 assert s.complete
995 assert isinstance(c.session_key, bytes)
996 assert isinstance(s.session_key, bytes)
997 assert c.session_key == s.session_key
998
999 assert c.client_principal is None
1000 assert s.client_principal == kerb_cred.user_princ
1001
1002 assert c.context_attr == spnego.ContextReq.mutual_auth | spnego.ContextReq.sequence_detect
1003 assert s.context_attr == spnego.ContextReq.mutual_auth | spnego.ContextReq.sequence_detect
1004
1005 c = c.new_context()
1006 s = s.new_context()
1007
1008 token1 = c.step()
1009 assert isinstance(token1, bytes)
1010 assert not c.complete
1011 assert not s.complete
1012 assert s.negotiated_protocol == "kerberos"
1013
1014 token2 = s.step(token1)
1015 assert isinstance(token2, bytes)
1016 assert not c.complete
1017 assert s.complete
1018 assert s.negotiated_protocol == "kerberos"
1019
1020 token3 = c.step(token2)
1021 assert token3 is None
1022 assert c.complete
1023 assert s.complete
1024 assert isinstance(c.session_key, bytes)
1025 assert isinstance(s.session_key, bytes)
1026 assert c.session_key == s.session_key
1027
1028 assert c.client_principal is None
1029 assert s.client_principal == kerb_cred.user_princ
1030
1031 print(c.context_attr)
1032 print(s.context_attr)
1033
1034
1035 @pytest.mark.parametrize("acquire_cred_from", [False, True])
1036 def test_gssapi_kerberos_auth_explicit_cred(acquire_cred_from, kerb_cred, monkeypatch):
1037 if sys.platform == "darwin":
1038 pytest.skip("Environment problem with GSS.Framework - skip")
1039
1040 if not acquire_cred_from:
1041 monkeypatch.delattr("gssapi.raw.acquire_cred_from", raising=False)
1042
1043 context_req = spnego.ContextReq.default | spnego.ContextReq.delegate
1044 c = spnego.client(
1045 kerb_cred.user_princ,
1046 kerb_cred.password("user"),
1047 hostname=socket.getfqdn(),
1048 protocol="kerberos",
1049 options=spnego.NegotiateOptions.use_gssapi,
1050 context_req=context_req,
1051 )
1052 s = spnego.server(options=spnego.NegotiateOptions.use_gssapi, protocol="kerberos")
1053
1054 assert c.get_extra_info("invalid") is None
1055 assert c.get_extra_info("invalid", "default") == "default"
1056
1057 assert not c.complete
1058 assert not s.complete
1059 assert s.negotiated_protocol == "kerberos"
1060
1061 with pytest.raises(SpnegoError, match="Retrieving session key"):
1062 _ = c.session_key
1063
1064 with pytest.raises(SpnegoError, match="Retrieving session key"):
1065 _ = s.session_key
1066
1067 token1 = c.step()
1068 assert isinstance(token1, bytes)
1069 assert not c.complete
1070 assert not s.complete
1071 assert s.negotiated_protocol == "kerberos"
1072
1073 token2 = s.step(token1)
1074 assert isinstance(token2, bytes)
1075 assert not c.complete
1076 assert s.complete
1077 assert s.negotiated_protocol == "kerberos"
1078
1079 token3 = c.step(token2)
1080 assert token3 is None
1081 assert c.complete
1082 assert s.complete
1083 assert isinstance(c.session_key, bytes)
1084 assert isinstance(s.session_key, bytes)
1085 assert c.session_key == s.session_key
1086
1087 assert c.client_principal is None
1088 assert s.client_principal == kerb_cred.user_princ
1089
1090 assert c.context_attr & spnego.ContextReq.delegate
1091 assert s.context_attr & spnego.ContextReq.delegate
1092
1093 _message_test(c, s)
1094
1095 c = c.new_context()
1096 s = s.new_context()
1097
1098 token1 = c.step()
1099 assert isinstance(token1, bytes)
1100 assert not c.complete
1101 assert not s.complete
1102 assert s.negotiated_protocol == "kerberos"
1103
1104 token2 = s.step(token1)
1105 assert isinstance(token2, bytes)
1106 assert not c.complete
1107 assert s.complete
1108 assert s.negotiated_protocol == "kerberos"
1109
1110 token3 = c.step(token2)
1111 assert token3 is None
1112 assert c.complete
1113 assert s.complete
1114 assert isinstance(c.session_key, bytes)
1115 assert isinstance(s.session_key, bytes)
1116 assert c.session_key == s.session_key
1117
1118 assert c.client_principal is None
1119 assert s.client_principal == kerb_cred.user_princ
1120
1121 assert c.context_attr & spnego.ContextReq.delegate
1122 assert s.context_attr & spnego.ContextReq.delegate
1123
1124 _message_test(c, s)
1125
1126
1127 @pytest.mark.parametrize(
1128 "protocol, set_principal",
1129 [
1130 ("kerberos", False),
1131 ("kerberos", True),
1132 ("negotiate", False),
1133 ("negotiate", True),
1134 ],
1135 )
1136 def test_kerberos_auth_keytab(protocol, set_principal, kerb_cred):
1137 if sys.platform == "darwin":
1138 pytest.skip("Environment problem with GSS.Framework - skip")
1139
1140 kerb_cred.extract_keytab(kerb_cred.user_princ, kerb_cred.client_keytab)
1141 if set_principal:
1142 kt = spnego.KerberosKeytab(keytab=kerb_cred.client_keytab, principal=kerb_cred.user_princ)
1143 else:
1144 kt = spnego.KerberosKeytab(keytab=kerb_cred.client_keytab)
1145
1146 context_req = spnego.ContextReq.default
1147 c = spnego.client(kt, hostname=socket.getfqdn(), protocol=protocol, context_req=context_req)
1148 s = spnego.server(protocol=protocol)
1149
1150 assert not c.complete
1151 assert not s.complete
1152 if protocol == "negotiate":
1153 assert s.negotiated_protocol is None
1154 else:
1155 assert s.negotiated_protocol == "kerberos"
1156
1157 token1 = c.step()
1158 assert isinstance(token1, bytes)
1159 assert not c.complete
1160 assert not s.complete
1161 if protocol == "negotiate":
1162 assert s.negotiated_protocol is None
1163 else:
1164 assert s.negotiated_protocol == "kerberos"
1165
1166 token2 = s.step(token1)
1167 assert isinstance(token2, bytes)
1168 assert not c.complete
1169 assert s.complete
1170 assert s.negotiated_protocol == "kerberos"
1171
1172 token3 = c.step(token2)
1173 assert token3 is None
1174 assert c.complete
1175 assert s.complete
1176 assert isinstance(c.session_key, bytes)
1177 assert isinstance(s.session_key, bytes)
1178 assert c.session_key == s.session_key
1179
1180 assert c.client_principal is None
1181 assert s.client_principal == kerb_cred.user_princ
1182
1183 _message_test(c, s)
1184
1185 c = c.new_context()
1186 s = s.new_context()
1187
1188 token1 = c.step()
1189 assert isinstance(token1, bytes)
1190 assert not c.complete
1191 assert not s.complete
1192 if protocol == "negotiate":
1193 assert s.negotiated_protocol is None
1194 else:
1195 assert s.negotiated_protocol == "kerberos"
1196
1197 token2 = s.step(token1)
1198 assert isinstance(token2, bytes)
1199 assert not c.complete
1200 assert s.complete
1201 assert s.negotiated_protocol == "kerberos"
1202
1203 token3 = c.step(token2)
1204 assert token3 is None
1205 assert c.complete
1206 assert s.complete
1207 assert isinstance(c.session_key, bytes)
1208 assert isinstance(s.session_key, bytes)
1209 assert c.session_key == s.session_key
1210
1211 assert c.client_principal is None
1212 assert s.client_principal == kerb_cred.user_princ
1213
1214 _message_test(c, s)
1215
1216
1217 @pytest.mark.parametrize(
1218 "protocol, explicit_user",
1219 [
1220 ("kerberos", False),
1221 ("kerberos", True),
1222 ("negotiate", False),
1223 ("kerberos", True),
1224 ],
1225 )
1226 def test_kerberos_auth_ccache(protocol, explicit_user, kerb_cred, monkeypatch):
1227 if sys.platform == "darwin":
1228 pytest.skip("Environment problem with GSS.Framework - skip")
1229
1230 # Verified we are actually using our explicit CCache
1231 monkeypatch.setenv("KRB5CCNAME", "missing")
1232
1233 context_req = spnego.ContextReq.default
1234
1235 if explicit_user:
1236 ccache = spnego.KerberosCCache(ccache=kerb_cred.ccache, principal=kerb_cred.user_princ)
1237 else:
1238 ccache = spnego.KerberosCCache(ccache=kerb_cred.ccache)
1239
1240 c = spnego.client(ccache, hostname=socket.getfqdn(), protocol=protocol, context_req=context_req)
1241 s = spnego.server(protocol=protocol)
1242
1243 assert not c.complete
1244 assert not s.complete
1245 if protocol == "negotiate":
1246 assert s.negotiated_protocol is None
1247 else:
1248 assert s.negotiated_protocol == "kerberos"
1249
1250 token1 = c.step()
1251 assert isinstance(token1, bytes)
1252 assert not c.complete
1253 assert not s.complete
1254 if protocol == "negotiate":
1255 assert s.negotiated_protocol is None
1256 else:
1257 assert s.negotiated_protocol == "kerberos"
1258 # assert s.negotiated_protocol == "kerberos"
1259
1260 token2 = s.step(token1)
1261 assert isinstance(token2, bytes)
1262 assert not c.complete
1263 assert s.complete
1264 assert s.negotiated_protocol == "kerberos"
1265
1266 token3 = c.step(token2)
1267 assert token3 is None
1268 assert c.complete
1269 assert s.complete
1270 assert isinstance(c.session_key, bytes)
1271 assert isinstance(s.session_key, bytes)
1272 assert c.session_key == s.session_key
1273
1274 assert c.client_principal is None
1275 assert s.client_principal == kerb_cred.user_princ
1276
1277 _message_test(c, s)
1278
1279 c = c.new_context()
1280 s = s.new_context()
1281
1282 token1 = c.step()
1283 assert isinstance(token1, bytes)
1284 assert not c.complete
1285 assert not s.complete
1286 if protocol == "negotiate":
1287 assert s.negotiated_protocol is None
1288 else:
1289 assert s.negotiated_protocol == "kerberos"
1290
1291 token2 = s.step(token1)
1292 assert isinstance(token2, bytes)
1293 assert not c.complete
1294 assert s.complete
1295 assert s.negotiated_protocol == "kerberos"
1296
1297 token3 = c.step(token2)
1298 assert token3 is None
1299 assert c.complete
1300 assert s.complete
1301 assert isinstance(c.session_key, bytes)
1302 assert isinstance(s.session_key, bytes)
1303 assert c.session_key == s.session_key
1304
1305 assert c.client_principal is None
1306 assert s.client_principal == kerb_cred.user_princ
1307
1308 _message_test(c, s)
1309
1310
1311 @pytest.mark.parametrize(
1312 "protocol, explicit_user",
1313 [
1314 ("kerberos", False),
1315 ("kerberos", True),
1316 ("negotiate", False),
1317 ("kerberos", True),
1318 ],
1319 )
1320 def test_kerberos_auth_env_cache(protocol, explicit_user, kerb_cred):
1321 if sys.platform == "darwin":
1322 pytest.skip("Environment problem with GSS.Framework - skip")
1323
1324 context_req = spnego.ContextReq.default
1325 cred = None
1326 if explicit_user:
1327 cred = spnego.CredentialCache(username=kerb_cred.user_princ)
1328
1329 c = spnego.client(cred, hostname=socket.getfqdn(), protocol=protocol, context_req=context_req)
1330 s = spnego.server(protocol=protocol)
1331
1332 assert not c.complete
1333 assert not s.complete
1334 if protocol == "negotiate":
1335 assert s.negotiated_protocol is None
1336 else:
1337 assert s.negotiated_protocol == "kerberos"
1338
1339 token1 = c.step()
1340 assert isinstance(token1, bytes)
1341 assert not c.complete
1342 assert not s.complete
1343 if protocol == "negotiate":
1344 assert s.negotiated_protocol is None
1345 else:
1346 assert s.negotiated_protocol == "kerberos"
1347
1348 token2 = s.step(token1)
1349 assert isinstance(token2, bytes)
1350 assert not c.complete
1351 assert s.complete
1352 assert s.negotiated_protocol == "kerberos"
1353
1354 token3 = c.step(token2)
1355 assert token3 is None
1356 assert c.complete
1357 assert s.complete
1358 assert isinstance(c.session_key, bytes)
1359 assert isinstance(s.session_key, bytes)
1360 assert c.session_key == s.session_key
1361
1362 assert c.client_principal is None
1363 assert s.client_principal == kerb_cred.user_princ
1364
1365 _message_test(c, s)
1366
1367 c = c.new_context()
1368 s = s.new_context()
1369
1370 token1 = c.step()
1371 assert isinstance(token1, bytes)
1372 assert not c.complete
1373 assert not s.complete
1374 if protocol == "negotiate":
1375 assert s.negotiated_protocol is None
1376 else:
1377 assert s.negotiated_protocol == "kerberos"
1378
1379 token2 = s.step(token1)
1380 assert isinstance(token2, bytes)
1381 assert not c.complete
1382 assert s.complete
1383 assert s.negotiated_protocol == "kerberos"
1384
1385 token3 = c.step(token2)
1386 assert token3 is None
1387 assert c.complete
1388 assert s.complete
1389 assert isinstance(c.session_key, bytes)
1390 assert isinstance(s.session_key, bytes)
1391 assert c.session_key == s.session_key
1392
1393 assert c.client_principal is None
1394 assert s.client_principal == kerb_cred.user_princ
1395
1396 _message_test(c, s)
1397
1398
1399 @pytest.mark.parametrize(
1400 "protocol, with_step",
1401 [
1402 ("kerberos", False),
1403 ("kerberos", True),
1404 ("negotiate", False),
1405 ("negotiate", True),
1406 ],
1407 )
1408 def test_kerberos_auth_channel_bindings(protocol, with_step, kerb_cred):
1409 if sys.platform == "darwin":
1410 pytest.skip("Environment problem with GSS.Framework - skip")
1411
1412 cbt = spnego.channel_bindings.GssChannelBindings(application_data=b"test_data:\x00\x01")
1413
1414 step_kwargs: typing.Dict[str, typing.Any] = {}
1415 client_kwargs: typing.Dict[str, typing.Any] = {}
1416 server_kwargs: typing.Dict[str, typing.Any] = {}
1417 if with_step:
1418 step_kwargs["channel_bindings"] = cbt
1419
1420 # Use a fake value to ensure step takes priority.
1421 client_kwargs["channel_bindings"] = spnego.channel_bindings.GssChannelBindings(
1422 application_data=b"test_data:\x00\x02"
1423 )
1424 server_kwargs["channel_bindings"] = spnego.channel_bindings.GssChannelBindings(
1425 application_data=b"test_data:\x00\x03"
1426 )
1427 else:
1428 client_kwargs["channel_bindings"] = cbt
1429 server_kwargs["channel_bindings"] = cbt
1430
1431 c = spnego.client(
1432 kerb_cred.user_princ,
1433 kerb_cred.password("user"),
1434 hostname=socket.getfqdn(),
1435 protocol=protocol,
1436 **client_kwargs,
1437 )
1438 s = spnego.server(protocol=protocol, **server_kwargs)
1439
1440 assert not c.complete
1441 assert not s.complete
1442 if protocol == "negotiate":
1443 assert s.negotiated_protocol is None
1444 else:
1445 assert s.negotiated_protocol == "kerberos"
1446
1447 token1 = c.step(**step_kwargs)
1448 assert isinstance(token1, bytes)
1449 assert not c.complete
1450 assert not s.complete
1451 if protocol == "negotiate":
1452 assert s.negotiated_protocol is None
1453 else:
1454 assert s.negotiated_protocol == "kerberos"
1455 # assert s.negotiated_protocol == "kerberos"
1456
1457 token2 = s.step(token1, **step_kwargs)
1458 assert isinstance(token2, bytes)
1459 assert not c.complete
1460 assert s.complete
1461 assert s.negotiated_protocol == "kerberos"
1462
1463 token3 = c.step(token2, **step_kwargs)
1464 assert token3 is None
1465 assert c.complete
1466 assert s.complete
1467 assert isinstance(c.session_key, bytes)
1468 assert isinstance(s.session_key, bytes)
1469 assert c.session_key == s.session_key
1470
1471 assert c.client_principal is None
1472 assert s.client_principal == kerb_cred.user_princ
1473
1474 _message_test(c, s)
1475
1476 c = c.new_context()
1477 s = s.new_context()
1478
1479 token1 = c.step(**step_kwargs)
1480 assert isinstance(token1, bytes)
1481 assert not c.complete
1482 assert not s.complete
1483 if protocol == "negotiate":
1484 assert s.negotiated_protocol is None
1485 else:
1486 assert s.negotiated_protocol == "kerberos"
1487
1488 token2 = s.step(token1, **step_kwargs)
1489 assert isinstance(token2, bytes)
1490 assert not c.complete
1491 assert s.complete
1492 assert s.negotiated_protocol == "kerberos"
1493
1494 token3 = c.step(token2, **step_kwargs)
1495 assert token3 is None
1496 assert c.complete
1497 assert s.complete
1498 assert isinstance(c.session_key, bytes)
1499 assert isinstance(s.session_key, bytes)
1500 assert c.session_key == s.session_key
1501
1502 assert c.client_principal is None
1503 assert s.client_principal == kerb_cred.user_princ
1504
1505 _message_test(c, s)
1506
1507
1508 # CredSSP scenarios
1509
1510
1511 @pytest.mark.parametrize(
1512 "options, restrict_tlsv12, version",
1513 [
1514 (spnego.NegotiateOptions.use_negotiate, False, None),
1515 (spnego.NegotiateOptions.use_negotiate, False, 2),
1516 (spnego.NegotiateOptions.use_negotiate, True, None),
1517 # Using NTLM directly results in a slightly separate behaviour for the pub key.
1518 (spnego.NegotiateOptions.use_ntlm, False, None),
1519 (spnego.NegotiateOptions.use_ntlm, False, 5),
1520 (spnego.NegotiateOptions.use_ntlm, True, None),
1521 ],
1522 )
1523 def test_credssp_ntlm_creds(options, restrict_tlsv12, version, ntlm_cred, monkeypatch, tmp_path):
1524 context_kwargs: typing.Dict[str, typing.Any] = {}
1525 if restrict_tlsv12:
1526 credssp_context = spnego.tls.default_tls_context(usage="accept")
1527
1528 tls_version = getattr(ssl, "TLSVersion", None)
1529 if hasattr(credssp_context.context, "maximum_version") and tls_version:
1530 setattr(credssp_context.context, "maximum_version", tls_version.TLSv1_2)
1531
1532 else:
1533 credssp_context.context.options |= ssl.Options.OP_NO_TLSv1_3
1534
1535 cert_pem, key_pem, pub_key = spnego.tls.generate_tls_certificate()
1536 with open(tmp_path / "ca.pem", mode="wb") as fd:
1537 fd.write(cert_pem)
1538 fd.write(key_pem)
1539
1540 credssp_context.context.load_cert_chain(tmp_path / "ca.pem")
1541 credssp_context.public_key = pub_key
1542 context_kwargs["credssp_tls_context"] = credssp_context
1543
1544 if version:
1545 monkeypatch.setattr(spnego._credssp, "_CREDSSP_VERSION", version)
1546 else:
1547 version = spnego._credssp._CREDSSP_VERSION
1548
1549 c = spnego.client(ntlm_cred[0], ntlm_cred[1], hostname=socket.gethostname(), protocol="credssp", options=options)
1550 s = spnego.server(protocol="credssp", options=options, **context_kwargs)
1551
1552 assert c.get_extra_info("invalid") is None
1553 assert c.get_extra_info("invalid", "default") == "default"
1554 assert c.get_extra_info("client_credential") is None
1555 assert isinstance(c.get_extra_info("sslcontext"), ssl.SSLContext)
1556 assert isinstance(c.get_extra_info("ssl_object"), ssl.SSLObject)
1557 assert c.get_extra_info("auth_stage") == "TLS Handshake"
1558
1559 assert s.get_extra_info("client_credential") is None
1560 assert isinstance(s.get_extra_info("sslcontext"), ssl.SSLContext)
1561 assert isinstance(s.get_extra_info("ssl_object"), ssl.SSLObject)
1562 assert s.get_extra_info("auth_stage") == "TLS Handshake"
1563
1564 assert c.client_principal is None
1565 assert c.get_extra_info("client_credential") is None
1566 assert c.negotiated_protocol is None
1567
1568 server_tls_token = None
1569 while c.get_extra_info("auth_stage") == "TLS Handshake":
1570 client_tls_token = c.step(server_tls_token)
1571 assert not c.complete
1572 assert not s.complete
1573
1574 server_tls_token = s.step(client_tls_token)
1575 assert not c.complete
1576 assert not s.complete
1577
1578 ntlm3_pub_key = c.step(server_tls_token)
1579 assert c.get_extra_info("auth_stage") == "Public key exchange"
1580 assert s.get_extra_info("auth_stage").startswith("Authentication")
1581 assert not c.complete
1582 assert not s.complete
1583
1584 server_pub_key = s.step(ntlm3_pub_key)
1585 assert c.get_extra_info("auth_stage") == "Public key exchange"
1586 assert s.get_extra_info("auth_stage") == "Public key exchange"
1587 assert not c.complete
1588 assert not s.complete
1589
1590 credential = c.step(server_pub_key)
1591 assert c.get_extra_info("auth_stage") == "Credential exchange"
1592 assert s.get_extra_info("auth_stage") == "Public key exchange"
1593 assert c.complete
1594 assert not s.complete
1595
1596 final_token = s.step(credential)
1597 assert c.get_extra_info("auth_stage") == "Credential exchange"
1598 assert s.get_extra_info("auth_stage") == "Credential exchange"
1599 assert final_token is None
1600 assert c.complete
1601 assert s.complete
1602
1603 assert c.negotiated_protocol == "ntlm"
1604 assert s.negotiated_protocol == "ntlm"
1605
1606 domain, username = ntlm_cred[0].split("\\")
1607
1608 assert c.get_extra_info("client_credential") is None
1609 client_credential = s.get_extra_info("client_credential")
1610 assert isinstance(client_credential, TSPasswordCreds)
1611 assert client_credential.username == username
1612 assert client_credential.domain_name == domain
1613 assert client_credential.password == ntlm_cred[1]
1614
1615 assert c.get_extra_info("protocol_version") == version
1616 assert s.get_extra_info("protocol_version") == version
1617
1618 assert isinstance(c.query_message_sizes().header, int)
1619 assert isinstance(s.query_message_sizes().header, int)
1620
1621 _message_test(c, s)
1622
1623 plaintext = os.urandom(16)
1624 c_winrm_result = c.wrap_winrm(plaintext)
1625 assert isinstance(c_winrm_result, WinRMWrapResult)
1626 assert isinstance(c_winrm_result.header, bytes)
1627 assert isinstance(c_winrm_result.data, bytes)
1628 assert isinstance(c_winrm_result.padding_length, int)
1629
1630 s_winrm_result = s.unwrap_winrm(c_winrm_result.header, c_winrm_result.data)
1631 assert s_winrm_result == plaintext
1632
1633 plaintext = os.urandom(16)
1634 s_winrm_result = s.wrap_winrm(plaintext)
1635 assert isinstance(s_winrm_result, WinRMWrapResult)
1636 assert isinstance(s_winrm_result.header, bytes)
1637 assert isinstance(s_winrm_result.data, bytes)
1638 assert isinstance(s_winrm_result.padding_length, int)
1639
1640 c_winrm_result = c.unwrap_winrm(s_winrm_result.header, s_winrm_result.data)
1641 assert c_winrm_result == plaintext
1642
1643 c = c.new_context()
1644 s = s.new_context()
1645
1646 server_tls_token = None
1647 while c.get_extra_info("auth_stage") == "TLS Handshake":
1648 client_tls_token = c.step(server_tls_token)
1649 assert not c.complete
1650 assert not s.complete
1651
1652 server_tls_token = s.step(client_tls_token)
1653 assert not c.complete
1654 assert not s.complete
1655
1656 ntlm3_pub_key = c.step(server_tls_token)
1657 assert c.get_extra_info("auth_stage") == "Public key exchange"
1658 assert s.get_extra_info("auth_stage").startswith("Authentication")
1659 assert not c.complete
1660 assert not s.complete
1661
1662 server_pub_key = s.step(ntlm3_pub_key)
1663 assert c.get_extra_info("auth_stage") == "Public key exchange"
1664 assert s.get_extra_info("auth_stage") == "Public key exchange"
1665 assert not c.complete
1666 assert not s.complete
1667
1668 credential = c.step(server_pub_key)
1669 assert c.get_extra_info("auth_stage") == "Credential exchange"
1670 assert s.get_extra_info("auth_stage") == "Public key exchange"
1671 assert c.complete
1672 assert not s.complete
1673
1674 final_token = s.step(credential)
1675 assert c.get_extra_info("auth_stage") == "Credential exchange"
1676 assert s.get_extra_info("auth_stage") == "Credential exchange"
1677 assert final_token is None
1678 assert c.complete
1679 assert s.complete
1680
1681 assert c.negotiated_protocol == "ntlm"
1682 assert s.negotiated_protocol == "ntlm"
1683
1684 domain, username = ntlm_cred[0].split("\\")
1685
1686 assert c.get_extra_info("client_credential") is None
1687 client_credential = s.get_extra_info("client_credential")
1688 assert isinstance(client_credential, TSPasswordCreds)
1689 assert client_credential.username == username
1690 assert client_credential.domain_name == domain
1691 assert client_credential.password == ntlm_cred[1]
1692
1693 assert c.get_extra_info("protocol_version") == version
1694 assert s.get_extra_info("protocol_version") == version
1695
1696 _message_test(c, s)
1697
1698 plaintext = os.urandom(16)
1699 c_winrm_result = c.wrap_winrm(plaintext)
1700 assert isinstance(c_winrm_result, WinRMWrapResult)
1701 assert isinstance(c_winrm_result.header, bytes)
1702 assert isinstance(c_winrm_result.data, bytes)
1703 assert isinstance(c_winrm_result.padding_length, int)
1704
1705 s_winrm_result = s.unwrap_winrm(c_winrm_result.header, c_winrm_result.data)
1706 assert s_winrm_result == plaintext
1707
1708 plaintext = os.urandom(16)
1709 s_winrm_result = s.wrap_winrm(plaintext)
1710 assert isinstance(s_winrm_result, WinRMWrapResult)
1711 assert isinstance(s_winrm_result.header, bytes)
1712 assert isinstance(s_winrm_result.data, bytes)
1713 assert isinstance(s_winrm_result.padding_length, int)
1714
1715 c_winrm_result = c.unwrap_winrm(s_winrm_result.header, s_winrm_result.data)
1716 assert c_winrm_result == plaintext
1717
1718
1719 @pytest.mark.parametrize("restrict_tlsv12", [False, True])
1720 def test_credssp_kerberos_creds(restrict_tlsv12, kerb_cred):
1721 if sys.platform == "darwin":
1722 pytest.skip("Environment problem with GSS.Framework - skip")
1723
1724 c_kerb_context = spnego.client(kerb_cred.user_princ, None, hostname=socket.getfqdn(), protocol="kerberos")
1725 s_kerb_context = spnego.server(protocol="kerberos")
1726
1727 client_kwargs: typing.Dict[str, typing.Any] = {}
1728 if restrict_tlsv12:
1729 tls_context = spnego.tls.default_tls_context()
1730
1731 tls_version = getattr(ssl, "TLSVersion", None)
1732 if hasattr(tls_context.context, "maximum_version") and tls_version:
1733 setattr(tls_context.context, "maximum_version", tls_version.TLSv1_2)
1734
1735 else:
1736 tls_context.context.options |= ssl.Options.OP_NO_TLSv1_3
1737
1738 client_kwargs["credssp_tls_context"] = tls_context
1739
1740 c = spnego.client(
1741 kerb_cred.user_princ,
1742 kerb_cred.password("user"),
1743 protocol="credssp",
1744 credssp_negotiate_context=c_kerb_context,
1745 **client_kwargs,
1746 )
1747 s = spnego.server(protocol="credssp", credssp_negotiate_context=s_kerb_context)
1748
1749 assert c.get_extra_info("invalid") is None
1750 assert c.get_extra_info("invalid", "default") == "default"
1751 assert c.get_extra_info("client_credential") is None
1752 assert isinstance(c.get_extra_info("sslcontext"), ssl.SSLContext)
1753 assert isinstance(c.get_extra_info("ssl_object"), ssl.SSLObject)
1754
1755 assert s.get_extra_info("client_credential") is None
1756 assert isinstance(s.get_extra_info("sslcontext"), ssl.SSLContext)
1757 assert isinstance(s.get_extra_info("ssl_object"), ssl.SSLObject)
1758
1759 server_token = None
1760 while c.get_extra_info("auth_stage") != "Public key exchange":
1761 client_token = c.step(server_token)
1762 assert not c.complete
1763 assert not s.complete
1764
1765 server_token = s.step(client_token)
1766 assert not c.complete
1767 assert not s.complete
1768
1769 assert s_kerb_context.complete
1770
1771 credential = c.step(server_token)
1772 assert c.complete
1773 assert not s.complete
1774
1775 final_token = s.step(credential)
1776 assert final_token is None
1777 assert c.complete
1778 assert s.complete
1779
1780 assert c.negotiated_protocol == "kerberos"
1781 assert s.negotiated_protocol == "kerberos"
1782 assert c_kerb_context.negotiated_protocol == "kerberos"
1783 assert s_kerb_context.negotiated_protocol == "kerberos"
1784
1785 assert s.client_principal == kerb_cred.user_princ
1786 assert c.get_extra_info("client_credential") is None
1787 client_credential = s.get_extra_info("client_credential")
1788 assert isinstance(client_credential, TSPasswordCreds)
1789 assert client_credential.username == kerb_cred.user_princ
1790 assert client_credential.password == kerb_cred.password("user")
1791
1792 _message_test(c, s)
1793
1794 plaintext = os.urandom(16)
1795 c_winrm_result = c.wrap_winrm(plaintext)
1796 assert isinstance(c_winrm_result, WinRMWrapResult)
1797 assert isinstance(c_winrm_result.header, bytes)
1798 assert isinstance(c_winrm_result.data, bytes)
1799 assert isinstance(c_winrm_result.padding_length, int)
1800
1801 s_winrm_result = s.unwrap_winrm(c_winrm_result.header, c_winrm_result.data)
1802 assert s_winrm_result == plaintext
1803
1804 plaintext = os.urandom(16)
1805 s_winrm_result = s.wrap_winrm(plaintext)
1806 assert isinstance(s_winrm_result, WinRMWrapResult)
1807 assert isinstance(s_winrm_result.header, bytes)
1808 assert isinstance(s_winrm_result.data, bytes)
1809 assert isinstance(s_winrm_result.padding_length, int)
1810
1811 c_winrm_result = c.unwrap_winrm(s_winrm_result.header, s_winrm_result.data)
1812 assert c_winrm_result == plaintext
1813
1814 c = c.new_context()
1815 s = s.new_context()
1816
1817 server_token = None
1818 while c.get_extra_info("auth_stage") != "Public key exchange":
1819 client_token = c.step(server_token)
1820 assert not c.complete
1821 assert not s.complete
1822
1823 server_token = s.step(client_token)
1824 assert not c.complete
1825 assert not s.complete
1826
1827 assert s_kerb_context.complete
1828
1829 credential = c.step(server_token)
1830 assert c.complete
1831 assert not s.complete
1832
1833 final_token = s.step(credential)
1834 assert final_token is None
1835 assert c.complete
1836 assert s.complete
1837
1838 assert c.negotiated_protocol == "kerberos"
1839 assert s.negotiated_protocol == "kerberos"
1840 assert c_kerb_context.negotiated_protocol == "kerberos"
1841 assert s_kerb_context.negotiated_protocol == "kerberos"
1842
1843 assert s.client_principal == kerb_cred.user_princ
1844 assert c.get_extra_info("client_credential") is None
1845 client_credential = s.get_extra_info("client_credential")
1846 assert isinstance(client_credential, TSPasswordCreds)
1847 assert client_credential.username == kerb_cred.user_princ
1848 assert client_credential.password == kerb_cred.password("user")
1849
1850 _message_test(c, s)
1851
1852 plaintext = os.urandom(16)
1853 c_winrm_result = c.wrap_winrm(plaintext)
1854 assert isinstance(c_winrm_result, WinRMWrapResult)
1855 assert isinstance(c_winrm_result.header, bytes)
1856 assert isinstance(c_winrm_result.data, bytes)
1857 assert isinstance(c_winrm_result.padding_length, int)
1858
1859 s_winrm_result = s.unwrap_winrm(c_winrm_result.header, c_winrm_result.data)
1860 assert s_winrm_result == plaintext
1861
1862 plaintext = os.urandom(16)
1863 s_winrm_result = s.wrap_winrm(plaintext)
1864 assert isinstance(s_winrm_result, WinRMWrapResult)
1865 assert isinstance(s_winrm_result.header, bytes)
1866 assert isinstance(s_winrm_result.data, bytes)
1867 assert isinstance(s_winrm_result.padding_length, int)
1868
1869 c_winrm_result = c.unwrap_winrm(s_winrm_result.header, s_winrm_result.data)
1870 assert c_winrm_result == plaintext
1871
1872
1873 def test_credssp_multiple_creds(ntlm_cred):
1874 creds: typing.List[spnego.Credential] = [
1875 spnego.NTLMHash(username=ntlm_cred[0], nt_hash=ntowfv1(ntlm_cred[1]).hex()),
1876 spnego.Password(username="delegate", password="password"),
1877 ]
1878 c = spnego.client(creds, hostname=socket.gethostname(), protocol="credssp")
1879 s = spnego.server(protocol="credssp")
1880
1881 assert c.client_principal is None
1882 assert c.negotiated_protocol is None
1883 assert c.get_extra_info("client_credential") is None
1884
1885 server_tls_token = None
1886 while c.get_extra_info("auth_stage") == "TLS Handshake":
1887 client_tls_token = c.step(server_tls_token)
1888 assert not c.complete
1889 assert not s.complete
1890
1891 server_tls_token = s.step(client_tls_token)
1892 assert not c.complete
1893 assert not s.complete
1894
1895 ntlm3_pub_key = c.step(server_tls_token)
1896 assert not c.complete
1897 assert not s.complete
1898
1899 server_pub_key = s.step(ntlm3_pub_key)
1900 assert not c.complete
1901 assert not s.complete
1902
1903 credential = c.step(server_pub_key)
1904 assert c.complete
1905 assert not s.complete
1906
1907 final_token = s.step(credential)
1908 assert final_token is None
1909 assert c.complete
1910 assert s.complete
1911
1912 assert c.negotiated_protocol == "ntlm"
1913 assert s.negotiated_protocol == "ntlm"
1914
1915 # Matches the principal authenticated with the Negotiate phase - NTLMHash
1916 assert s.client_principal == ntlm_cred[0]
1917
1918 # Matches the Password cred passed in, will not use the NTLMHash details as it wasn't enought for CredSSP
1919 client_credential = s.get_extra_info("client_credential")
1920 assert isinstance(client_credential, TSPasswordCreds)
1921 assert client_credential.username == "delegate"
1922 assert client_credential.domain_name == ""
1923 assert client_credential.password == "password"
1924
1925 _message_test(c, s)
1926
1927 c = c.new_context()
1928 s = s.new_context()
1929
1930 assert c.client_principal is None
1931 assert c.negotiated_protocol is None
1932 assert c.get_extra_info("client_credential") is None
1933
1934 server_tls_token = None
1935 while c.get_extra_info("auth_stage") == "TLS Handshake":
1936 client_tls_token = c.step(server_tls_token)
1937 assert not c.complete
1938 assert not s.complete
1939
1940 server_tls_token = s.step(client_tls_token)
1941 assert not c.complete
1942 assert not s.complete
1943
1944 ntlm3_pub_key = c.step(server_tls_token)
1945 assert not c.complete
1946 assert not s.complete
1947
1948 server_pub_key = s.step(ntlm3_pub_key)
1949 assert not c.complete
1950 assert not s.complete
1951
1952 credential = c.step(server_pub_key)
1953 assert c.complete
1954 assert not s.complete
1955
1956 final_token = s.step(credential)
1957 assert final_token is None
1958 assert c.complete
1959 assert s.complete
1960
1961 assert c.negotiated_protocol == "ntlm"
1962 assert s.negotiated_protocol == "ntlm"
1963
1964 # Matches the principal authenticated with the Negotiate phase - NTLMHash
1965 assert s.client_principal == ntlm_cred[0]
1966
1967 # Matches the Password cred passed in, will not use the NTLMHash details as it wasn't enought for CredSSP
1968 client_credential = s.get_extra_info("client_credential")
1969 assert isinstance(client_credential, TSPasswordCreds)
1970 assert client_credential.username == "delegate"
1971 assert client_credential.domain_name == ""
1972 assert client_credential.password == "password"
1973
1974 _message_test(c, s)
1975
1976
1977 def test_credssp_min_protocol_failure_initiator(ntlm_cred, monkeypatch):
1978 monkeypatch.setattr(spnego._credssp, "_CREDSSP_VERSION", 4)
1979
1980 c = spnego.client(
1981 ntlm_cred[0], ntlm_cred[1], hostname=socket.gethostname(), protocol="credssp", credssp_min_protocol=5
1982 )
1983 s = spnego.server(protocol="credssp")
1984
1985 # The TLS handshake can differ based on the protocol selected, keep on looping until we see the auth_context set up
1986 # For NTLM the auth context will be present after the first exchange of NTLM tokens.
1987 server_tls_token = None
1988 while c._auth_context is None: # type: ignore[attr-defined]
1989 client_tls_token = c.step(server_tls_token)
1990 assert not c.complete
1991 assert not s.complete
1992
1993 server_tls_token = s.step(client_tls_token)
1994 assert not c.complete
1995 assert not s.complete
1996
1997 with pytest.raises(
1998 InvalidTokenError, match="The peer protocol version was 4 and did not meet the minimum requirements of 5"
1999 ):
2000 c.step(server_tls_token)
2001
2002
2003 def test_credssp_min_protocol_failure_acceptor(ntlm_cred, monkeypatch):
2004 monkeypatch.setattr(spnego._credssp, "_CREDSSP_VERSION", 4)
2005
2006 c = spnego.client(ntlm_cred[0], ntlm_cred[1], hostname=socket.gethostname(), protocol="credssp")
2007 s = spnego.server(protocol="credssp", credssp_min_protocol=5)
2008
2009 # The TLS handshake can differ based on the protocol selected, keep on looping until we see the auth_context set up
2010 # For NTLM the auth context will be present after the first exchange of NTLM tokens.
2011 server_tls_token = None
2012 while True:
2013 client_tls_token = c.step(server_tls_token)
2014 assert not c.complete
2015 assert not s.complete
2016
2017 if c.get_extra_info("auth_stage").startswith("Authentication"):
2018 break
2019
2020 server_tls_token = s.step(client_tls_token)
2021 assert not c.complete
2022 assert not s.complete
2023
2024 with pytest.raises(
2025 InvalidTokenError, match="The peer protocol version was 4 and did not meet the minimum requirements of 5"
2026 ):
2027 s.step(client_tls_token)