IndependentNTLMAuthenticationProvider.cs 15 KB

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