IndependentNTLMAuthenticationProvider.cs 17 KB

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