IndependentNTLMAuthenticationProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /* Copyright (C) 2014-2017 Tal Aloni <tal.aloni.il@gmail.com>. All rights reserved.
  2. *
  3. * You can redistribute this program and/or modify it under the terms of
  4. * the GNU Lesser Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. */
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Security.Cryptography;
  10. using SMBLibrary.Authentication.GSSAPI;
  11. using Utilities;
  12. namespace SMBLibrary.Authentication.NTLM
  13. {
  14. public delegate string GetUserPassword(string userName);
  15. public class IndependentNTLMAuthenticationProvider : NTLMAuthenticationProviderBase
  16. {
  17. public class AuthContext
  18. {
  19. public string WorkStation;
  20. public byte[] ServerChallenge;
  21. public string UserName;
  22. public byte[] SessionKey;
  23. public bool IsGuest;
  24. public AuthContext(string workStation, byte[] serverChallenge)
  25. {
  26. WorkStation = workStation;
  27. ServerChallenge = serverChallenge;
  28. }
  29. }
  30. private GetUserPassword m_GetUserPassword;
  31. /// <param name="getUserPassword">
  32. /// The NTLM challenge response will be compared against the provided password.
  33. /// </param>
  34. public IndependentNTLMAuthenticationProvider(GetUserPassword getUserPassword)
  35. {
  36. m_GetUserPassword = getUserPassword;
  37. }
  38. public override NTStatus GetChallengeMessage(out object context, NegotiateMessage negotiateMessage, out ChallengeMessage challengeMessage)
  39. {
  40. byte[] serverChallenge = GenerateServerChallenge();
  41. context = new AuthContext(negotiateMessage.Workstation, serverChallenge);
  42. challengeMessage = new ChallengeMessage();
  43. // https://msdn.microsoft.com/en-us/library/cc236691.aspx
  44. challengeMessage.NegotiateFlags = NegotiateFlags.TargetTypeServer |
  45. NegotiateFlags.TargetInfo |
  46. NegotiateFlags.TargetNameSupplied |
  47. NegotiateFlags.Version;
  48. // [MS-NLMP] NTLMSSP_NEGOTIATE_NTLM MUST be set in the [..] CHALLENGE_MESSAGE to the client.
  49. challengeMessage.NegotiateFlags |= NegotiateFlags.NTLMSessionSecurity;
  50. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.UnicodeEncoding) > 0)
  51. {
  52. challengeMessage.NegotiateFlags |= NegotiateFlags.UnicodeEncoding;
  53. }
  54. else if ((negotiateMessage.NegotiateFlags & NegotiateFlags.OEMEncoding) > 0)
  55. {
  56. challengeMessage.NegotiateFlags |= NegotiateFlags.OEMEncoding;
  57. }
  58. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.ExtendedSessionSecurity) > 0)
  59. {
  60. challengeMessage.NegotiateFlags |= NegotiateFlags.ExtendedSessionSecurity;
  61. }
  62. else if ((negotiateMessage.NegotiateFlags & NegotiateFlags.LanManagerKey) > 0)
  63. {
  64. challengeMessage.NegotiateFlags |= NegotiateFlags.LanManagerKey;
  65. }
  66. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.Sign) > 0)
  67. {
  68. // [MS-NLMP] If the client sends NTLMSSP_NEGOTIATE_SIGN to the server in the NEGOTIATE_MESSAGE,
  69. // the server MUST return NTLMSSP_NEGOTIATE_SIGN to the client in the CHALLENGE_MESSAGE.
  70. challengeMessage.NegotiateFlags |= NegotiateFlags.Sign;
  71. }
  72. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.Seal) > 0)
  73. {
  74. // [MS-NLMP] If the client sends NTLMSSP_NEGOTIATE_SEAL to the server in the NEGOTIATE_MESSAGE,
  75. // the server MUST return NTLMSSP_NEGOTIATE_SEAL to the client in the CHALLENGE_MESSAGE.
  76. challengeMessage.NegotiateFlags |= NegotiateFlags.Seal;
  77. }
  78. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.Sign) > 0 ||
  79. (negotiateMessage.NegotiateFlags & NegotiateFlags.Seal) > 0)
  80. {
  81. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.Use56BitEncryption) > 0)
  82. {
  83. // [MS-NLMP] If the client sends NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN with
  84. // NTLMSSP_NEGOTIATE_56 to the server in the NEGOTIATE_MESSAGE, the server MUST return
  85. // NTLMSSP_NEGOTIATE_56 to the client in the CHALLENGE_MESSAGE.
  86. challengeMessage.NegotiateFlags |= NegotiateFlags.Use56BitEncryption;
  87. }
  88. if ((negotiateMessage.NegotiateFlags & NegotiateFlags.Use128BitEncryption) > 0)
  89. {
  90. // [MS-NLMP] If the client sends NTLMSSP_NEGOTIATE_128 to the server in the NEGOTIATE_MESSAGE,
  91. // the server MUST return NTLMSSP_NEGOTIATE_128 to the client in the CHALLENGE_MESSAGE only if
  92. // the client sets NTLMSSP_NEGOTIATE_SEAL or NTLMSSP_NEGOTIATE_SIGN.
  93. challengeMessage.NegotiateFlags |= NegotiateFlags.Use128BitEncryption;
  94. }
  95. }
  96. challengeMessage.TargetName = Environment.MachineName;
  97. challengeMessage.ServerChallenge = serverChallenge;
  98. challengeMessage.TargetInfo = AVPairUtils.GetAVPairSequence(Environment.MachineName, Environment.MachineName);
  99. challengeMessage.Version = NTLMVersion.Server2003;
  100. return NTStatus.SEC_I_CONTINUE_NEEDED;
  101. }
  102. public override NTStatus Authenticate(object context, AuthenticateMessage message)
  103. {
  104. AuthContext authContext = context as AuthContext;
  105. if (authContext == null)
  106. {
  107. // There are two possible reasons for authContext to be null:
  108. // 1. We have a bug in our implementation, let's assume that's not the case,
  109. // according to [MS-SMB2] 3.3.5.5.1 we aren't allowed to return SEC_E_INVALID_HANDLE anyway.
  110. // 2. The client sent AuthenticateMessage without sending NegotiateMessage first,
  111. // in this case the correct response is SEC_E_INVALID_TOKEN.
  112. return NTStatus.SEC_E_INVALID_TOKEN;
  113. }
  114. authContext.UserName = message.UserName;
  115. if ((message.NegotiateFlags & NegotiateFlags.Anonymous) > 0)
  116. {
  117. if (this.EnableGuestLogin)
  118. {
  119. authContext.IsGuest = true;
  120. return NTStatus.STATUS_SUCCESS;
  121. }
  122. else
  123. {
  124. return NTStatus.STATUS_LOGON_FAILURE;
  125. }
  126. }
  127. string password = m_GetUserPassword(message.UserName);
  128. if (password == null)
  129. {
  130. if (this.EnableGuestLogin)
  131. {
  132. authContext.IsGuest = true;
  133. return NTStatus.STATUS_SUCCESS;
  134. }
  135. else
  136. {
  137. return NTStatus.STATUS_LOGON_FAILURE;
  138. }
  139. }
  140. bool success;
  141. byte[] serverChallenge = authContext.ServerChallenge;
  142. byte[] sessionBaseKey;
  143. byte[] keyExchangeKey = null;
  144. if ((message.NegotiateFlags & NegotiateFlags.ExtendedSessionSecurity) > 0)
  145. {
  146. if (AuthenticationMessageUtils.IsNTLMv1ExtendedSecurity(message.LmChallengeResponse))
  147. {
  148. // NTLM v1 Extended Security:
  149. success = AuthenticateV1Extended(password, serverChallenge, message.LmChallengeResponse, message.NtChallengeResponse);
  150. if (success)
  151. {
  152. // https://msdn.microsoft.com/en-us/library/cc236699.aspx
  153. sessionBaseKey = new MD4().GetByteHashFromBytes(NTLMCryptography.NTOWFv1(password));
  154. byte[] lmowf = NTLMCryptography.LMOWFv1(password);
  155. keyExchangeKey = NTLMCryptography.KXKey(sessionBaseKey, message.NegotiateFlags, message.LmChallengeResponse, serverChallenge, lmowf);
  156. }
  157. }
  158. else
  159. {
  160. // NTLM v2:
  161. success = AuthenticateV2(message.DomainName, message.UserName, password, serverChallenge, message.LmChallengeResponse, message.NtChallengeResponse);
  162. if (success)
  163. {
  164. // https://msdn.microsoft.com/en-us/library/cc236700.aspx
  165. byte[] responseKeyNT = NTLMCryptography.NTOWFv2(password, message.UserName, message.DomainName);
  166. byte[] ntProofStr = ByteReader.ReadBytes(message.NtChallengeResponse, 0, 16);
  167. sessionBaseKey = new HMACMD5(responseKeyNT).ComputeHash(ntProofStr);
  168. keyExchangeKey = sessionBaseKey;
  169. }
  170. }
  171. }
  172. else
  173. {
  174. success = AuthenticateV1(password, serverChallenge, message.LmChallengeResponse, message.NtChallengeResponse);
  175. if (success)
  176. {
  177. // https://msdn.microsoft.com/en-us/library/cc236699.aspx
  178. sessionBaseKey = new MD4().GetByteHashFromBytes(NTLMCryptography.NTOWFv1(password));
  179. byte[] lmowf = NTLMCryptography.LMOWFv1(password);
  180. keyExchangeKey = NTLMCryptography.KXKey(sessionBaseKey, message.NegotiateFlags, message.LmChallengeResponse, serverChallenge, lmowf);
  181. }
  182. }
  183. if (success)
  184. {
  185. // https://msdn.microsoft.com/en-us/library/cc236676.aspx
  186. // https://blogs.msdn.microsoft.com/openspecification/2010/04/19/ntlm-keys-and-sundry-stuff/
  187. if ((message.NegotiateFlags & NegotiateFlags.KeyExchange) > 0)
  188. {
  189. authContext.SessionKey = RC4.Decrypt(keyExchangeKey, message.EncryptedRandomSessionKey);
  190. }
  191. else
  192. {
  193. authContext.SessionKey = keyExchangeKey;
  194. }
  195. return NTStatus.STATUS_SUCCESS;
  196. }
  197. else
  198. {
  199. return NTStatus.STATUS_LOGON_FAILURE;
  200. }
  201. }
  202. public override void DeleteSecurityContext(ref object context)
  203. {
  204. }
  205. public override object GetContextAttribute(object context, GSSAttributeName attributeName)
  206. {
  207. AuthContext authContext = context as AuthContext;
  208. if (authContext != null)
  209. {
  210. switch (attributeName)
  211. {
  212. case GSSAttributeName.IsGuest:
  213. return authContext.IsGuest;
  214. case GSSAttributeName.MachineName:
  215. return authContext.WorkStation;
  216. case GSSAttributeName.SessionKey:
  217. return authContext.SessionKey;
  218. case GSSAttributeName.UserName:
  219. return authContext.UserName;
  220. }
  221. }
  222. return null;
  223. }
  224. private bool EnableGuestLogin
  225. {
  226. get
  227. {
  228. return (m_GetUserPassword("Guest") == String.Empty);
  229. }
  230. }
  231. /// <summary>
  232. /// LM v1 / NTLM v1
  233. /// </summary>
  234. private static bool AuthenticateV1(string password, byte[] serverChallenge, byte[] lmResponse, byte[] ntResponse)
  235. {
  236. byte[] expectedLMResponse = NTLMCryptography.ComputeLMv1Response(serverChallenge, password);
  237. if (ByteUtils.AreByteArraysEqual(expectedLMResponse, lmResponse))
  238. {
  239. return true;
  240. }
  241. byte[] expectedNTResponse = NTLMCryptography.ComputeNTLMv1Response(serverChallenge, password);
  242. return ByteUtils.AreByteArraysEqual(expectedNTResponse, ntResponse);
  243. }
  244. /// <summary>
  245. /// LM v1 / NTLM v1 Extended Security
  246. /// </summary>
  247. private static bool AuthenticateV1Extended(string password, byte[] serverChallenge, byte[] lmResponse, byte[] ntResponse)
  248. {
  249. byte[] clientChallenge = ByteReader.ReadBytes(lmResponse, 0, 8);
  250. byte[] expectedNTLMv1Response = NTLMCryptography.ComputeNTLMv1ExtendedSecurityResponse(serverChallenge, clientChallenge, password);
  251. return ByteUtils.AreByteArraysEqual(expectedNTLMv1Response, ntResponse);
  252. }
  253. /// <summary>
  254. /// LM v2 / NTLM v2
  255. /// </summary>
  256. private bool AuthenticateV2(string domainName, string accountName, string password, byte[] serverChallenge, byte[] lmResponse, byte[] ntResponse)
  257. {
  258. byte[] _LMv2ClientChallenge = ByteReader.ReadBytes(lmResponse, 16, 8);
  259. byte[] expectedLMv2Response = NTLMCryptography.ComputeLMv2Response(serverChallenge, _LMv2ClientChallenge, password, accountName, domainName);
  260. if (ByteUtils.AreByteArraysEqual(expectedLMv2Response, lmResponse))
  261. {
  262. return true;
  263. }
  264. if (AuthenticationMessageUtils.IsNTLMv2NTResponse(ntResponse))
  265. {
  266. byte[] clientNTProof = ByteReader.ReadBytes(ntResponse, 0, 16);
  267. byte[] clientChallengeStructurePadded = ByteReader.ReadBytes(ntResponse, 16, ntResponse.Length - 16);
  268. byte[] expectedNTProof = NTLMCryptography.ComputeNTLMv2Proof(serverChallenge, clientChallengeStructurePadded, password, accountName, domainName);
  269. return ByteUtils.AreByteArraysEqual(clientNTProof, expectedNTProof);
  270. }
  271. return false;
  272. }
  273. /// <summary>
  274. /// Generate 8-byte server challenge
  275. /// </summary>
  276. private static byte[] GenerateServerChallenge()
  277. {
  278. byte[] serverChallenge = new byte[8];
  279. new Random().NextBytes(serverChallenge);
  280. return serverChallenge;
  281. }
  282. }
  283. }