Debian Codegraph @

src/spnego/_ntlm_raw/crypto.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Copyright: (c) 2020, Jordan Borean (@jborean93) <[email protected]>
2 # MIT License (see LICENSE or https://opensource.org/licenses/MIT)
3
4 """NTLM Cryptographic Operations
5
6 Implements the various cryptographic operations that are defined in `MS-NLMP Crypto Operations`_. Some crypto
7 operations aren't implemented due to it being a simple operation in Python.
8
9 .. _MS-NLMP Crypto Operations
10 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/26c42637-9549-46ae-be2e-90f6f1360193
11 """
12
13 import base64
14 import binascii
15 import hashlib
16 import hmac
17 import io
18 import re
19 import struct
20 import typing
21
22 from cryptography.hazmat.backends import default_backend
23 from cryptography.hazmat.primitives.ciphers import Cipher, algorithms
24
25 from spnego._ntlm_raw.des import DES
26 from spnego._ntlm_raw.md4 import md4
27 from spnego._ntlm_raw.messages import (
28 FileTime,
29 NegotiateFlags,
30 NTClientChallengeV2,
31 TargetInfo,
32 )
33
34 # A user does not need to specify their actual plaintext password they can specify the LM and NT hash (from lmowfv1 and
35 # ntowfv2) in the form 'lm_hash_hex:nt_hash_hex'. This is still considered a plaintext pass as we can use it to build
36 # the LM and NT response but it's only usable for NTLM.
37 _NTLM_HASH_PATTERN = re.compile(r"^[a-fA-F0-9]{32}:[a-fA-F0-9]{32}$")
38
39
40 class RC4Handle:
41 """RC4 class to wrap the underlying crypto function."""
42
43 def __init__(self, key: bytes) -> None:
44 self._key = key
45
46 arc4 = algorithms.ARC4(self._key)
47 cipher = Cipher(arc4, mode=None, backend=default_backend())
48 self._handle = cipher.encryptor()
49
50 def update(self, b_data: bytes) -> bytes:
51 """Update the RC4 stream and return the encrypted/decrypted bytes."""
52 return self._handle.update(b_data)
53
54 def reset(self) -> None:
55 """Reset's the cipher stream back to the original state."""
56 arc4 = algorithms.ARC4(self._key)
57 cipher = Cipher(arc4, mode=None, backend=default_backend())
58 self._handle = cipher.encryptor()
59
60
61 def is_ntlm_hash(password: str) -> bool:
62 return bool(_NTLM_HASH_PATTERN.match(password))
63
64
65 def compute_response_v1(
66 flags: int,
67 nt_hash: bytes,
68 lm_hash: bytes,
69 server_challenge: bytes,
70 client_challenge: bytes,
71 no_lm_response: bool = True,
72 ) -> typing.Tuple[bytes, bytes, bytes]:
73 """Compute NT and LM Response for NTLMv1.
74
75 Computes the NT and LM Response for NTLMv1 messages. The response is dependent on the flags that were negotiated
76 between the client and server.
77
78 The pseudo-code for this function as documented under `NTLM v1 Authentication`_ is::
79
80 Define ComputeResponse(NegFlg, ResponseKeyNT, ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge,
81 ClientChallenge, Time, ServerName) As
82
83 If (User is set to "" AND Passwd is set to "")
84 -- Special case for anonymous authentication
85 Set NtChallengeResponseLen to 0
86 Set NtChallengeResponseMaxLen to 0
87 Set NtChallengeResponseBufferOffset to 0
88
89 Set LmChallengeResponse to Z(1)
90 ElseIf
91 If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
92 Set NtChallengeResponse to DESL(ResponseKeyNT,
93 MD5(ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge))[0..7])
94
95 Set LmChallengeResponse to ConcatenationOf{ClientChallenge, Z(16)}
96 Else
97 Set NtChallengeResponse to DESL(ResponseKeyNT, CHALLENGE_MESSAGE.ServerChallenge)
98
99 If (NoLMResponseNTLMv1 is TRUE)
100 Set LmChallengeResponse to NtChallengeResponse
101 Else
102 Set LmChallengeResponse to DESL(ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge)
103 EndIf
104 EndIf
105 EndIf
106
107 Set SessionBaseKey to MD4(NTOWF)
108
109 Args:
110 flags: The negotiated flags between the initiator and acceptor.
111 nt_hash: The response key computed by :meth:`ntowfv1`.
112 lm_hash: The response key computed by :meth:`lmowfv1`.
113 server_challenge: The 8 byte nonce generated by the acceptor.
114 client_challenge: The 8 byte nonce generated by the initiator.
115 no_lm_response: Whether to compute (True) the `LmChallengeResponse` or not (False) when extended session
116 security was not negotiated.
117
118 Returns:
119 Tuple[bytes, bytes, bytes]: Returns the NTChallengeResponse, LMChallengeResponse and KeyExchangeKey.
120
121 .. _NTLM v1 Authentication:
122 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/464551a8-9fc4-428e-b3d3-bc5bfb2e73a5
123 """
124 if flags & NegotiateFlags.extended_session_security:
125 nt_response = desl(nt_hash, md5(server_challenge + client_challenge[:8]))
126 lm_response = client_challenge + (b"\x00" * 16)
127
128 else:
129 nt_response = lm_response = desl(nt_hash, server_challenge)
130
131 if not no_lm_response:
132 lm_response = desl(lm_hash, server_challenge)
133
134 session_base_key = md4(nt_hash)
135 key_exchange_key = kxkey(flags, session_base_key, lm_hash, lm_response, server_challenge)
136
137 return nt_response, lm_response, key_exchange_key
138
139
140 def compute_response_v2(
141 nt_hash: bytes,
142 server_challenge: bytes,
143 client_challenge: bytes,
144 time: FileTime,
145 av_pairs: TargetInfo,
146 ) -> typing.Tuple[bytes, bytes, bytes]:
147 """Compute NT and LM Response for NTLMv2.
148
149 Computes the NT and LM Response for NTLMv2 messages. The response is dependent on the flags that were negotiated
150 between the client and server.
151
152 The pseudo-code for this function as documented under `NTLM v2 Authentication`_ is::
153
154 Define ComputeResponse(NegFlg, ResponseKeyNT, ResponseKeyLM, CHALLENGE_MESSAGE.ServerChallenge,
155 ClientChallenge, Time, ServerName) As
156
157 If (User is set to "" && Passwd is set to "")
158 -- Special case for anonymous authentication
159 Set NtChallengeResponseLen to 0
160 Set NtChallengeResponseMaxLen to 0
161 Set NtChallengeResponseBufferOffset to 0
162
163 Set LmChallengeResponse to Z(1)
164 Else
165 Set temp to ConcatenationOf(Responserversion, HiResponserversion, Z(6), Time, ClientChallenge, Z(4),
166 ServerName, Z(4))
167
168 Set NTProofStr to HMAC_MD5(ResponseKeyNT, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge,temp))
169
170 Set NtChallengeResponse to ConcatenationOf(NTProofStr, temp)
171
172 Set LmChallengeResponse to ConcatenationOf(
173 HMAC_MD5(ResponseKeyLM, ConcatenationOf(CHALLENGE_MESSAGE.ServerChallenge, ClientChallenge)),
174 ClientChallenge)
175 EndIf
176
177 Set SessionBaseKey to HMAC_MD5(ResponseKeyNT, NTProofStr)
178
179 Args:
180 nt_hash: The response key computed by :meth:`ntwofv2`. The `ResponseKeyLM` is the same value so we only
181 pass in the 1 key.
182 server_challenge: The 8 byte nonce generated by the acceptor.
183 client_challenge: The 8 byte nonce generated by the initiator.
184 time: The FileTime to place in the NT hash.
185 av_pairs: The TargetInfo AvPairs fields that are placed in the Authenticate message.
186
187 Returns:
188 Tuple[bytes, bytes, bytes]: Returns the NTChallengeResponse, LMChallengeResponse and KeyExchangeKey.
189
190 .. _NTLM v2 Authentication:
191 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/5e550938-91d4-459f-b67d-75d70009e3f3
192 """
193 temp = NTClientChallengeV2(time_stamp=time, client_challenge=client_challenge, av_pairs=av_pairs)
194 b_temp = temp.pack() + b"\x00\x00\x00\x00"
195 nt_proof_str = hmac_md5(nt_hash, server_challenge + b_temp)
196
197 nt_response = nt_proof_str + b_temp
198 lm_response = hmac_md5(nt_hash, server_challenge + client_challenge) + client_challenge
199 session_base_key = hmac_md5(nt_hash, nt_proof_str)
200
201 return nt_response, lm_response, session_base_key # Is KeyExchangeKey in NTLMv2.
202
203
204 def crc32(m: bytes) -> bytes:
205 """Simple wrapper function to generate a CRC32 checksum."""
206 # We bitand to ensure the value is the same across all Python versions.
207 return struct.pack("<I", binascii.crc32(m) & 0xFFFFFFFF)
208
209
210 def des(k: bytes, d: bytes) -> bytes:
211 """DES encryption.
212
213 Indicates the encryption of an 8-byte data item `d` with the 7-byte key `k` using the Data Encryption Standard
214 (DES) algorithm in Electronic Codebook (ECB) mode. The result is 8 bytes in length ([FIPS46-2]).
215
216 Args:
217 k: The 7-byte key to use in the DES cipher.
218 d: The 8-byte data block to encrypt.
219
220 Returns:
221 bytes: The encrypted data block.
222 """
223 return DES(DES.key56_to_key64(k)).encrypt(d)
224
225
226 def desl(k: bytes, d: bytes) -> bytes:
227 """Encryption using the DES Long algorithm.
228
229 Indicates the encryption of an 8-byte data item `d` with the 16-byte key `k` using the Data Encryption
230 Standard Long (DESL) algorithm. The result is 24 bytes in length.
231
232 `DESL(K, D)` as by MS-NLMP `DESL`_ is computed as follows::
233
234 ConcatenationOf(
235 DES(K[0..6], D),
236 DES(K[7..13], D),
237 DES(ConcatenationOf(K[14..15], Z(5)), D),
238 );
239
240 Args:
241 k: The key to use for the DES cipher, will be truncated to 16 bytes and then padded to 21 bytes.
242 d: The value to run through the DESL algorithm, will be truncated to 8 bytes.
243
244 Returns:
245 bytes: The output of the DESL algorithm.
246
247 .. _DESL:
248 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/26c42637-9549-46ae-be2e-90f6f1360193
249 """
250 k = k[:16].ljust(21, b"\x00") # Key needs to be stripped at 16 characters and then padded to 21 chars.
251 d = d[:8].ljust(8, b"\x00") # Data need to be at most 8 bytes long.
252
253 b_value = io.BytesIO()
254
255 b_value.write(des(k[:7], d))
256 b_value.write(des(k[7:14], d))
257 b_value.write(des(k[14:], d))
258
259 return b_value.getvalue()
260
261
262 def hmac_md5(key: bytes, data: bytes) -> bytes:
263 """Simple wrapper function for a HMAC MD5 digest."""
264 return hmac.new(key, data, digestmod=hashlib.md5).digest()
265
266
267 def kxkey(
268 flags: int,
269 session_base_key: bytes,
270 lmowf: bytes,
271 lm_response: bytes,
272 server_challenge: bytes,
273 ) -> bytes:
274 """NTLM KXKEY function.
275
276 The MS-NLMP `KXKEY`_ function used to derive the key exchange key for a security context. This is only for NTLMv1
277 contexts as NTLMv2 just re-uses the session base key.
278
279 Args:
280 flags: The negotiate flags in the Challenge msg.
281 session_base_key: The session base key from :meth:`compute_response_v1`.
282 lmowf: The LM hash from :meth:`lmowfv1`.
283 lm_response: The lm response from :meth:`compute_response_v1`.
284 server_challenge: The server challenge in the Challenge msg.
285
286 Returns:
287 bytes: The derived key exchange key.
288
289 .. _KXKEY:
290 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/d86303b5-b29e-4fb9-b119-77579c761370
291 """
292 if flags & NegotiateFlags.extended_session_security:
293 return hmac_md5(session_base_key, server_challenge + lm_response[:8])
294
295 elif flags & NegotiateFlags.lm_key:
296 b_data = lm_response[:8]
297 return des(lmowf[:7], b_data) + des(lmowf[7:8] + b"\xBD\xBD\xBD\xBD\xBD\xBD", b_data)
298
299 elif flags & NegotiateFlags.non_nt_session_key:
300 return lmowf[:8] + b"\x00" * 8
301
302 else:
303 return session_base_key
304
305
306 def lmowfv1(password: str) -> bytes:
307 """NTLMv1 LMOWFv1 function
308
309 The Lan Manager v1 one way function as documented under `NTLM v1 Authentication`_.
310
311 The pseudo-code for this function is::
312
313 Define LMOWFv1(Passwd, User, UserDom) as
314 ConcatenationOf(
315 DES(UpperCase(Passwd)[0..6], "KGS!@#$%"),
316 DES(UpperCase(Passwd)[7..13], "KGS!@#$%"),
317 );
318
319 Args:
320 password: The password for the user.
321
322 Returns:
323 bytes: The LMv1 one way hash of the user's password.
324
325 .. _NTLM v1 Authentication:
326 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/464551a8-9fc4-428e-b3d3-bc5bfb2e73a5
327 """
328 if is_ntlm_hash(password):
329 return base64.b16decode(password.split(":")[0].upper())
330
331 # Fix the password to upper case and pad the length to exactly 14 bytes. While it is true LM only authentication
332 # will fail if the password exceeds 14 bytes typically it is used in conjunction with the NTv1 hash which has no
333 # such restrictions.
334 b_password = password.upper().encode("utf-8").ljust(14, b"\x00")[:14]
335
336 b_hash = io.BytesIO()
337 for start, end in [(0, 7), (7, 14)]:
338 b_hash.write(des(b_password[start:end], b"KGS!@#$%"))
339
340 return b_hash.getvalue()
341
342
343 def md5(m: bytes) -> bytes:
344 """Simple wrapper to generate a MD5 checksum."""
345 return hashlib.md5(m).digest()
346
347
348 def ntowfv1(password: str) -> bytes:
349 """NTLMv1 NTOWFv1 function
350
351 The NT v1 one way function as documented under `NTLM v1 Authentication`_.
352
353 The pseudo-code for this function is::
354
355 Define NTOWFv1(Passwd, User, UserDom) as MD4(UNICODE(Passwd))
356
357 Args:
358 password: The password for the user.
359
360 Returns:
361 bytes: The NTv1 one way hash of the user's password.
362
363 .. _NTLM v1 Authentication:
364 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/464551a8-9fc4-428e-b3d3-bc5bfb2e73a5
365 """
366 if is_ntlm_hash(password):
367 return base64.b16decode(password.split(":")[1].upper())
368
369 return md4(password.encode("utf-16-le"))
370
371
372 def ntowfv2(username: str, nt_hash: bytes, domain_name: typing.Optional[str]) -> bytes:
373 """NTLMv2 NTOWFv2 function
374
375 The NT v2 one way function as documented under `NTLM v2 Authentication`_.
376
377 The pseudo-code for this function is::
378
379 Define NTOWFv2(Passwd, User, UserDom) as
380
381 HMAC_MD5(MD4(UNICODE(Passwd)), UNICODE(ConcatenationOf(Uppercase(User), UserDom)))
382
383 Args:
384 username: The username.
385 nt_hash: The NT hash from :meth:`ntowfv1`.
386 domain_name: The optional domain name of the user.
387
388 Returns:
389 bytes: The NTv2 one way has of the user's credentials.
390
391 .. _NTLM v2 Authentication:
392 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/5e550938-91d4-459f-b67d-75d70009e3f3
393 """
394 b_user = (username.upper() + (domain_name or "")).encode("utf-16-le")
395 return hmac_md5(nt_hash, b_user)
396
397
398 def rc4(h: RC4Handle, d: bytes) -> bytes:
399 """RC4 encryption of the data specified using the handle generated by rc4init."""
400 return h.update(d)
401
402
403 def rc4k(k: bytes, d: bytes) -> bytes:
404 """RC4 encryption with an explicit key.
405
406 Indicates the encryption of data item `d` with the key `k` using the `RC4`_ algorithm.
407
408 Args:
409 k: The key to use for the RC4 cipher.
410 d: The data to encrypt.
411
412 Returns:
413 bytes: The RC4 encrypted bytes.
414
415 .. _RC4K:
416 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/26c42637-9549-46ae-be2e-90f6f1360193
417 """
418 return rc4init(k).update(d)
419
420
421 def rc4init(k: bytes) -> RC4Handle:
422 """Initialization of the RC4 handle using the key specified."""
423 return RC4Handle(k)
424
425
426 def sealkey(flags: int, session_key: bytes, usage: str) -> bytes:
427 """NTLM SEALKEY function.
428
429 The MS-NLMP `SEALKEY`_ function used to generate the sealing keys for a security context.
430
431 The pseudo-code for this function as documented under `SEALKEY`_ is::
432
433 Define SEALKEY(NegFlg, ExportedSessionKey, Mode) as
434
435 If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
436
437 If ( NTLMSSP_NEGOTIATE_128 is set in NegFlg)
438 Set SealKey to ExportedSessionKey
439
440 ElseIf ( NTLMSSP_NEGOTIATE_56 flag is set in NegFlg)
441 Set SealKey to ExportedSessionKey[0..6]
442
443 Else
444 Set SealKey to ExportedSessionKey[0..4]
445
446 Endif
447
448 If (Mode equals "Client")
449 Set SealKey to MD5(ConcatenationOf(SealKey,
450 "session key to client-to-server sealing key magic constant"))
451
452 Else
453 Set SealKey to MD5(ConcatenationOf(SealKey,
454 "session key to server-to-client sealing key magic constant"))
455
456 Endif
457 ElseIf ((NTLMSSP_NEGOTIATE_LM_KEY is set in NegFlg) or ((NTLMSSP_NEGOTIATE_DATAGRAM is set in NegFlg) and
458 (NTLMRevisionCurrent >= NTLMSSP_REVISION_W2K3)))
459
460 If (NTLMSSP_NEGOTIATE_56 flag is set in NegFlg)
461 Set SealKey to ConcatenationOf(ExportedSessionKey[0..6], 0xA0)
462
463 Else
464 Set SealKey to ConcatenationOf(ExportedSessionKey[0..4], 0xE5, 0x38, 0xB0)
465
466 EndIf
467
468 Else
469 Set SealKey to ExportedSessionKey
470 Endif
471 EndDefine
472
473 Args:
474 flags: The negotiated flags between the initiator and acceptor.
475 session_key: The derived session key.
476 usage: Whether the sealing key is for the 'initiate' or 'accept' context.
477
478 Returns:
479 bytes: The derived sealing key.
480
481 .. _SEALKEY:
482 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/bf39181d-e95d-40d7-a740-ab4ec3dc363d
483 """
484 if flags & NegotiateFlags.extended_session_security:
485 if flags & NegotiateFlags.key_128:
486 seal_key = session_key
487
488 elif flags & NegotiateFlags.key_56:
489 seal_key = session_key[:7]
490
491 else:
492 seal_key = session_key[:5]
493
494 direction = b"client-to-server" if usage == "initiate" else b"server-to-client"
495
496 return md5(seal_key + b"session key to %s sealing key magic constant\x00" % direction)
497
498 elif flags & NegotiateFlags.lm_key or flags & NegotiateFlags.datagram:
499 if flags & NegotiateFlags.key_56:
500 return session_key[:7] + b"\xA0"
501
502 else:
503 return session_key[:5] + b"\xE5\x38\xB0"
504
505 else:
506 return session_key
507
508
509 def signkey(flags: int, session_key: bytes, usage: str) -> bytes:
510 """NTLM SIGNKEY function.
511
512 The MS-NLMP `SIGNKEY`_ function used to generate the signing keys for a security context.
513
514 The pseudo-code for this function as documented under `SIGNKEY`_ is::
515
516 Define SIGNKEY(NegFlg, ExportedSessionKey, Mode) as
517
518 If (NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY flag is set in NegFlg)
519 If (Mode equals "Client")
520 Set SignKey to MD5(ConcatenationOf(ExportedSessionKey,
521 "session key to client-to-server signing key magic constant"))
522
523 Else
524 Set SignKey to MD5(ConcatenationOf(ExportedSessionKey,
525 "session key to server-to-client signing key magic constant"))
526
527 Endif
528 Else
529 Set SignKey to NIL
530
531 Endif
532 EndDefine
533
534 Args:
535 flags: The negotiated flags between the initiator and acceptor.
536 session_key: The derived session key.
537 usage: Whether the signing key is for the 'initiate' or 'accept' context.
538
539 Returns:
540 bytes: The derived singing key.
541
542 .. _SIGNKEY:
543 https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/524cdccb-563e-4793-92b0-7bc321fce096
544 """
545 if flags & NegotiateFlags.extended_session_security == 0:
546 return b""
547
548 direction = b"client-to-server" if usage == "initiate" else b"server-to-client"
549
550 return md5(session_key + b"session key to %s signing key magic constant\x00" % direction)