NtlmPasswordAuthentication.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. // This code is derived from jcifs smb client library <jcifs at samba dot org>
  2. // Ported by J. Arturo <webmaster at komodosoft dot net>
  3. //
  4. // This library is free software; you can redistribute it and/or
  5. // modify it under the terms of the GNU Lesser General Public
  6. // License as published by the Free Software Foundation; either
  7. // version 2.1 of the License, or (at your option) any later version.
  8. //
  9. // This library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public
  15. // License along with this library; if not, write to the Free Software
  16. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. using System;
  18. using SharpCifs.Util;
  19. using SharpCifs.Util.Sharpen;
  20. namespace SharpCifs.Smb
  21. {
  22. /// <summary>This class stores and encrypts NTLM user credentials.</summary>
  23. /// <remarks>
  24. /// This class stores and encrypts NTLM user credentials. The default
  25. /// credentials are retrieved from the <tt>jcifs.smb.client.domain</tt>,
  26. /// <tt>jcifs.smb.client.username</tt>, and <tt>jcifs.smb.client.password</tt>
  27. /// properties.
  28. /// <p>
  29. /// Read <a href="../../../authhandler.html">jCIFS Exceptions and
  30. /// NtlmAuthenticator</a> for related information.
  31. /// </remarks>
  32. public sealed class NtlmPasswordAuthentication : Principal
  33. {
  34. private static readonly int LmCompatibility
  35. = Config.GetInt("jcifs.smb.lmCompatibility", 3);
  36. private static readonly Random Random = new Random();
  37. private static LogStream _log = LogStream.GetInstance();
  38. private static readonly byte[] S8 =
  39. {
  40. unchecked(unchecked(0x4b)),
  41. unchecked(unchecked(0x47)),
  42. unchecked(unchecked(0x53)),
  43. unchecked(unchecked(0x21)),
  44. unchecked(unchecked(0x40)),
  45. unchecked(unchecked(0x23)),
  46. unchecked(unchecked(0x24)),
  47. unchecked(unchecked(0x25))
  48. };
  49. // KGS!@#$%
  50. private static void E(byte[] key, byte[] data, byte[] e)
  51. {
  52. byte[] key7 = new byte[7];
  53. byte[] e8 = new byte[8];
  54. for (int i = 0; i < key.Length / 7; i++)
  55. {
  56. Array.Copy(key, i * 7, key7, 0, 7);
  57. DES des = new DES(key7);
  58. des.Encrypt(data, e8);
  59. Array.Copy(e8, 0, e, i * 8, 8);
  60. }
  61. }
  62. internal static string DefaultDomain;
  63. internal static string DefaultUsername;
  64. internal static string DefaultPassword;
  65. internal static readonly string Blank = string.Empty;
  66. public static readonly NtlmPasswordAuthentication Anonymous
  67. = new NtlmPasswordAuthentication(string.Empty, string.Empty, string.Empty);
  68. internal static void InitDefaults()
  69. {
  70. if (DefaultDomain != null)
  71. {
  72. return;
  73. }
  74. DefaultDomain = Config.GetProperty("jcifs.smb.client.domain", "?");
  75. DefaultUsername = Config.GetProperty("jcifs.smb.client.username", "GUEST");
  76. DefaultPassword = Config.GetProperty("jcifs.smb.client.password", Blank);
  77. }
  78. /// <summary>
  79. /// Generate the ANSI DES hash for the password associated with these credentials.
  80. /// </summary>
  81. /// <remarks>
  82. /// Generate the ANSI DES hash for the password associated with these credentials.
  83. /// </remarks>
  84. public static byte[] GetPreNtlmResponse(string password, byte[] challenge)
  85. {
  86. byte[] p14 = new byte[14];
  87. byte[] p21 = new byte[21];
  88. byte[] p24 = new byte[24];
  89. byte[] passwordBytes;
  90. try
  91. {
  92. passwordBytes = Runtime.GetBytesForString(password.ToUpper(), SmbConstants.OemEncoding);
  93. }
  94. catch (UnsupportedEncodingException uee)
  95. {
  96. throw new RuntimeException("Try setting jcifs.encoding=US-ASCII", uee);
  97. }
  98. int passwordLength = passwordBytes.Length;
  99. // Only encrypt the first 14 bytes of the password for Pre 0.12 NT LM
  100. if (passwordLength > 14)
  101. {
  102. passwordLength = 14;
  103. }
  104. Array.Copy(passwordBytes, 0, p14, 0, passwordLength);
  105. E(p14, S8, p21);
  106. E(p21, challenge, p24);
  107. return p24;
  108. }
  109. /// <summary>
  110. /// Generate the Unicode MD4 hash for the password associated with these credentials.
  111. /// </summary>
  112. /// <remarks>
  113. /// Generate the Unicode MD4 hash for the password associated with these credentials.
  114. /// </remarks>
  115. public static byte[] GetNtlmResponse(string password, byte[] challenge)
  116. {
  117. byte[] uni = null;
  118. byte[] p21 = new byte[21];
  119. byte[] p24 = new byte[24];
  120. try
  121. {
  122. uni = Runtime.GetBytesForString(password, SmbConstants.UniEncoding);
  123. }
  124. catch (UnsupportedEncodingException uee)
  125. {
  126. if (_log.Level > 0)
  127. {
  128. Runtime.PrintStackTrace(uee, _log);
  129. }
  130. }
  131. Md4 md4 = new Md4();
  132. md4.Update(uni);
  133. try
  134. {
  135. md4.Digest(p21, 0, 16);
  136. }
  137. catch (Exception ex)
  138. {
  139. if (_log.Level > 0)
  140. {
  141. Runtime.PrintStackTrace(ex, _log);
  142. }
  143. }
  144. E(p21, challenge, p24);
  145. return p24;
  146. }
  147. /// <summary>Creates the LMv2 response for the supplied information.</summary>
  148. /// <remarks>Creates the LMv2 response for the supplied information.</remarks>
  149. /// <param name="domain">The domain in which the username exists.</param>
  150. /// <param name="user">The username.</param>
  151. /// <param name="password">The user's password.</param>
  152. /// <param name="challenge">The server challenge.</param>
  153. /// <param name="clientChallenge">The client challenge (nonce).</param>
  154. public static byte[] GetLMv2Response(string domain,
  155. string user,
  156. string password,
  157. byte[] challenge,
  158. byte[] clientChallenge)
  159. {
  160. try
  161. {
  162. byte[] hash = new byte[16];
  163. byte[] response = new byte[24];
  164. // The next 2-1/2 lines of this should be placed with nTOWFv1 in place of password
  165. Md4 md4 = new Md4();
  166. md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding));
  167. Hmact64 hmac = new Hmact64(md4.Digest());
  168. hmac.Update(Runtime.GetBytesForString(user.ToUpper(), SmbConstants.UniEncoding));
  169. hmac.Update(Runtime.GetBytesForString(domain.ToUpper(), SmbConstants.UniEncoding));
  170. hmac = new Hmact64(hmac.Digest());
  171. hmac.Update(challenge);
  172. hmac.Update(clientChallenge);
  173. hmac.Digest(response, 0, 16);
  174. Array.Copy(clientChallenge, 0, response, 16, 8);
  175. return response;
  176. }
  177. catch (Exception ex)
  178. {
  179. if (_log.Level > 0)
  180. {
  181. Runtime.PrintStackTrace(ex, _log);
  182. }
  183. return null;
  184. }
  185. }
  186. public static byte[] GetNtlm2Response(byte[] nTowFv1,
  187. byte[] serverChallenge,
  188. byte[] clientChallenge)
  189. {
  190. byte[] sessionHash = new byte[8];
  191. try
  192. {
  193. MessageDigest md5;
  194. md5 = MessageDigest.GetInstance("MD5");
  195. md5.Update(serverChallenge);
  196. md5.Update(clientChallenge, 0, 8);
  197. Array.Copy(md5.Digest(), 0, sessionHash, 0, 8);
  198. }
  199. catch (Exception gse)
  200. {
  201. if (_log.Level > 0)
  202. {
  203. Runtime.PrintStackTrace(gse, _log);
  204. }
  205. throw new RuntimeException("MD5", gse);
  206. }
  207. byte[] key = new byte[21];
  208. Array.Copy(nTowFv1, 0, key, 0, 16);
  209. byte[] ntResponse = new byte[24];
  210. E(key, sessionHash, ntResponse);
  211. return ntResponse;
  212. }
  213. public static byte[] NtowFv1(string password)
  214. {
  215. if (password == null)
  216. {
  217. throw new RuntimeException("Password parameter is required");
  218. }
  219. try
  220. {
  221. Md4 md4 = new Md4();
  222. md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding));
  223. return md4.Digest();
  224. }
  225. catch (UnsupportedEncodingException uee)
  226. {
  227. throw new RuntimeException(uee.Message);
  228. }
  229. }
  230. public static byte[] NtowFv2(string domain, string username, string password)
  231. {
  232. try
  233. {
  234. Md4 md4 = new Md4();
  235. md4.Update(Runtime.GetBytesForString(password, SmbConstants.UniEncoding));
  236. Hmact64 hmac = new Hmact64(md4.Digest());
  237. hmac.Update(Runtime.GetBytesForString(username.ToUpper(), SmbConstants.UniEncoding));
  238. hmac.Update(Runtime.GetBytesForString(domain, SmbConstants.UniEncoding));
  239. return hmac.Digest();
  240. }
  241. catch (UnsupportedEncodingException uee)
  242. {
  243. throw new RuntimeException(uee.Message);
  244. }
  245. }
  246. internal static byte[] ComputeResponse(byte[] responseKey,
  247. byte[] serverChallenge,
  248. byte[] clientData,
  249. int offset,
  250. int length)
  251. {
  252. Hmact64 hmac = new Hmact64(responseKey);
  253. hmac.Update(serverChallenge);
  254. hmac.Update(clientData, offset, length);
  255. byte[] mac = hmac.Digest();
  256. byte[] ret = new byte[mac.Length + clientData.Length];
  257. Array.Copy(mac, 0, ret, 0, mac.Length);
  258. Array.Copy(clientData, 0, ret, mac.Length, clientData.Length);
  259. return ret;
  260. }
  261. public static byte[] GetLMv2Response(byte[] responseKeyLm,
  262. byte[] serverChallenge,
  263. byte[] clientChallenge)
  264. {
  265. return ComputeResponse(responseKeyLm,
  266. serverChallenge,
  267. clientChallenge,
  268. 0,
  269. clientChallenge.Length);
  270. }
  271. public static byte[] GetNtlMv2Response(byte[] responseKeyNt,
  272. byte[] serverChallenge,
  273. byte[] clientChallenge,
  274. long nanos1601,
  275. byte[] targetInfo)
  276. {
  277. int targetInfoLength = targetInfo != null
  278. ? targetInfo.Length
  279. : 0;
  280. byte[] temp = new byte[28 + targetInfoLength + 4];
  281. Encdec.Enc_uint32le(unchecked(0x00000101), temp, 0);
  282. // Header
  283. Encdec.Enc_uint32le(unchecked(0x00000000), temp, 4);
  284. // Reserved
  285. Encdec.Enc_uint64le(nanos1601, temp, 8);
  286. Array.Copy(clientChallenge, 0, temp, 16, 8);
  287. Encdec.Enc_uint32le(unchecked(0x00000000), temp, 24);
  288. // Unknown
  289. if (targetInfo != null)
  290. {
  291. Array.Copy(targetInfo, 0, temp, 28, targetInfoLength);
  292. }
  293. Encdec.Enc_uint32le(unchecked(0x00000000), temp, 28 + targetInfoLength);
  294. // mystery bytes!
  295. return ComputeResponse(responseKeyNt,
  296. serverChallenge,
  297. temp,
  298. 0,
  299. temp.Length);
  300. }
  301. internal static readonly NtlmPasswordAuthentication Null
  302. = new NtlmPasswordAuthentication(string.Empty, string.Empty, string.Empty);
  303. internal static readonly NtlmPasswordAuthentication Guest
  304. = new NtlmPasswordAuthentication("?", "GUEST", string.Empty);
  305. internal static readonly NtlmPasswordAuthentication Default
  306. = new NtlmPasswordAuthentication(null);
  307. internal string Domain;
  308. internal string Username;
  309. internal string Password;
  310. internal byte[] AnsiHash;
  311. internal byte[] UnicodeHash;
  312. internal bool HashesExternal;
  313. internal byte[] ClientChallenge;
  314. internal byte[] Challenge;
  315. /// <summary>
  316. /// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
  317. /// component of an SMB URL like "<tt>domain;user:pass</tt>".
  318. /// </summary>
  319. /// <remarks>
  320. /// Create an <tt>NtlmPasswordAuthentication</tt> object from the userinfo
  321. /// component of an SMB URL like "<tt>domain;user:pass</tt>". This constructor
  322. /// is used internally be jCIFS when parsing SMB URLs.
  323. /// </remarks>
  324. public NtlmPasswordAuthentication(string userInfo)
  325. {
  326. Domain = Username = Password = null;
  327. if (userInfo != null)
  328. {
  329. try
  330. {
  331. userInfo = Unescape(userInfo);
  332. }
  333. catch (UnsupportedEncodingException)
  334. {
  335. }
  336. int i;
  337. int u;
  338. int end;
  339. char c;
  340. end = userInfo.Length;
  341. for (i = 0, u = 0; i < end; i++)
  342. {
  343. c = userInfo[i];
  344. if (c == ';')
  345. {
  346. Domain = Runtime.Substring(userInfo, 0, i);
  347. u = i + 1;
  348. }
  349. else
  350. {
  351. if (c == ':')
  352. {
  353. Password = Runtime.Substring(userInfo, i + 1);
  354. break;
  355. }
  356. }
  357. }
  358. Username = Runtime.Substring(userInfo, u, i);
  359. }
  360. InitDefaults();
  361. if (Domain == null)
  362. {
  363. Domain = DefaultDomain;
  364. }
  365. if (Username == null)
  366. {
  367. Username = DefaultUsername;
  368. }
  369. if (Password == null)
  370. {
  371. Password = DefaultPassword;
  372. }
  373. }
  374. /// <summary>
  375. /// Create an <tt>NtlmPasswordAuthentication</tt> object from a
  376. /// domain, username, and password.
  377. /// </summary>
  378. /// <remarks>
  379. /// Create an <tt>NtlmPasswordAuthentication</tt> object from a
  380. /// domain, username, and password. Parameters that are <tt>null</tt>
  381. /// will be substituted with <tt>jcifs.smb.client.domain</tt>,
  382. /// <tt>jcifs.smb.client.username</tt>, <tt>jcifs.smb.client.password</tt>
  383. /// property values.
  384. /// </remarks>
  385. public NtlmPasswordAuthentication(string domain, string username, string password)
  386. {
  387. int ci;
  388. if (username != null)
  389. {
  390. ci = username.IndexOf('@');
  391. if (ci > 0)
  392. {
  393. domain = Runtime.Substring(username, ci + 1);
  394. username = Runtime.Substring(username, 0, ci);
  395. }
  396. else
  397. {
  398. ci = username.IndexOf('\\');
  399. if (ci > 0)
  400. {
  401. domain = Runtime.Substring(username, 0, ci);
  402. username = Runtime.Substring(username, ci + 1);
  403. }
  404. }
  405. }
  406. this.Domain = domain;
  407. this.Username = username;
  408. this.Password = password;
  409. InitDefaults();
  410. if (domain == null)
  411. {
  412. this.Domain = DefaultDomain;
  413. }
  414. if (username == null)
  415. {
  416. this.Username = DefaultUsername;
  417. }
  418. if (password == null)
  419. {
  420. this.Password = DefaultPassword;
  421. }
  422. }
  423. /// <summary>
  424. /// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
  425. /// hashes.
  426. /// </summary>
  427. /// <remarks>
  428. /// Create an <tt>NtlmPasswordAuthentication</tt> object with raw password
  429. /// hashes. This is used exclusively by the <tt>jcifs.http.NtlmSsp</tt>
  430. /// class which is in turn used by NTLM HTTP authentication functionality.
  431. /// </remarks>
  432. public NtlmPasswordAuthentication(string domain,
  433. string username,
  434. byte[] challenge,
  435. byte[] ansiHash,
  436. byte[] unicodeHash)
  437. {
  438. if (domain == null
  439. || username == null
  440. || ansiHash == null
  441. || unicodeHash == null)
  442. {
  443. throw new ArgumentException("External credentials cannot be null");
  444. }
  445. this.Domain = domain;
  446. this.Username = username;
  447. Password = null;
  448. this.Challenge = challenge;
  449. this.AnsiHash = ansiHash;
  450. this.UnicodeHash = unicodeHash;
  451. HashesExternal = true;
  452. }
  453. /// <summary>Returns the domain.</summary>
  454. /// <remarks>Returns the domain.</remarks>
  455. public string GetDomain()
  456. {
  457. return Domain;
  458. }
  459. /// <summary>Returns the username.</summary>
  460. /// <remarks>Returns the username.</remarks>
  461. public string GetUsername()
  462. {
  463. return Username;
  464. }
  465. /// <summary>
  466. /// Returns the password in plain text or <tt>null</tt> if the raw password
  467. /// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
  468. /// object which will be the case when NTLM HTTP Authentication is
  469. /// used.
  470. /// </summary>
  471. /// <remarks>
  472. /// Returns the password in plain text or <tt>null</tt> if the raw password
  473. /// hashes were used to construct this <tt>NtlmPasswordAuthentication</tt>
  474. /// object which will be the case when NTLM HTTP Authentication is
  475. /// used. There is no way to retrieve a users password in plain text unless
  476. /// it is supplied by the user at runtime.
  477. /// </remarks>
  478. public string GetPassword()
  479. {
  480. return Password;
  481. }
  482. /// <summary>
  483. /// Return the domain and username in the format:
  484. /// <tt>domain\\username</tt>.
  485. /// </summary>
  486. /// <remarks>
  487. /// Return the domain and username in the format:
  488. /// <tt>domain\\username</tt>. This is equivalent to <tt>toString()</tt>.
  489. /// </remarks>
  490. public new string GetName()
  491. {
  492. bool d = Domain.Length > 0 && Domain.Equals("?") == false;
  493. return d
  494. ? Domain + "\\" + Username
  495. : Username;
  496. }
  497. /// <summary>
  498. /// Computes the 24 byte ANSI password hash given the 8 byte server challenge.
  499. /// </summary>
  500. /// <remarks>
  501. /// Computes the 24 byte ANSI password hash given the 8 byte server challenge.
  502. /// </remarks>
  503. public byte[] GetAnsiHash(byte[] challenge)
  504. {
  505. if (HashesExternal)
  506. {
  507. return AnsiHash;
  508. }
  509. switch (LmCompatibility)
  510. {
  511. case 0:
  512. case 1:
  513. {
  514. return GetPreNtlmResponse(Password, challenge);
  515. }
  516. case 2:
  517. {
  518. return GetNtlmResponse(Password, challenge);
  519. }
  520. case 3:
  521. case 4:
  522. case 5:
  523. {
  524. if (ClientChallenge == null)
  525. {
  526. ClientChallenge = new byte[8];
  527. Random.NextBytes(ClientChallenge);
  528. }
  529. return GetLMv2Response(Domain,
  530. Username,
  531. Password,
  532. challenge,
  533. ClientChallenge);
  534. }
  535. default:
  536. {
  537. return GetPreNtlmResponse(Password, challenge);
  538. }
  539. }
  540. }
  541. /// <summary>
  542. /// Computes the 24 byte Unicode password hash given the 8 byte server challenge.
  543. /// </summary>
  544. /// <remarks>
  545. /// Computes the 24 byte Unicode password hash given the 8 byte server challenge.
  546. /// </remarks>
  547. public byte[] GetUnicodeHash(byte[] challenge)
  548. {
  549. if (HashesExternal)
  550. {
  551. return UnicodeHash;
  552. }
  553. switch (LmCompatibility)
  554. {
  555. case 0:
  556. case 1:
  557. case 2:
  558. {
  559. return GetNtlmResponse(Password, challenge);
  560. }
  561. case 3:
  562. case 4:
  563. case 5:
  564. {
  565. return new byte[0];
  566. }
  567. default:
  568. {
  569. return GetNtlmResponse(Password, challenge);
  570. }
  571. }
  572. }
  573. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  574. public byte[] GetSigningKey(byte[] challenge)
  575. {
  576. switch (LmCompatibility)
  577. {
  578. case 0:
  579. case 1:
  580. case 2:
  581. {
  582. byte[] signingKey = new byte[40];
  583. GetUserSessionKey(challenge, signingKey, 0);
  584. Array.Copy(GetUnicodeHash(challenge), 0, signingKey, 16, 24);
  585. return signingKey;
  586. }
  587. case 3:
  588. case 4:
  589. case 5:
  590. {
  591. throw new SmbException(
  592. "NTLMv2 requires extended security "
  593. + "(jcifs.smb.client.useExtendedSecurity must be true "
  594. + "if jcifs.smb.lmCompatibility >= 3)");
  595. }
  596. }
  597. return null;
  598. }
  599. /// <summary>Returns the effective user session key.</summary>
  600. /// <remarks>Returns the effective user session key.</remarks>
  601. /// <param name="challenge">The server challenge.</param>
  602. /// <returns>
  603. /// A <code>byte[]</code> containing the effective user session key,
  604. /// used in SMB MAC signing and NTLMSSP signing and sealing.
  605. /// </returns>
  606. public byte[] GetUserSessionKey(byte[] challenge)
  607. {
  608. if (HashesExternal)
  609. {
  610. return null;
  611. }
  612. byte[] key = new byte[16];
  613. try
  614. {
  615. GetUserSessionKey(challenge, key, 0);
  616. }
  617. catch (Exception ex)
  618. {
  619. if (_log.Level > 0)
  620. {
  621. Runtime.PrintStackTrace(ex, _log);
  622. }
  623. }
  624. return key;
  625. }
  626. /// <summary>Calculates the effective user session key.</summary>
  627. /// <remarks>Calculates the effective user session key.</remarks>
  628. /// <param name="challenge">The server challenge.</param>
  629. /// <param name="dest">
  630. /// The destination array in which the user session key will be
  631. /// placed.
  632. /// </param>
  633. /// <param name="offset">
  634. /// The offset in the destination array at which the
  635. /// session key will start.
  636. /// </param>
  637. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  638. internal void GetUserSessionKey(byte[] challenge, byte[] dest, int offset)
  639. {
  640. if (HashesExternal)
  641. {
  642. return;
  643. }
  644. try
  645. {
  646. Md4 md4 = new Md4();
  647. md4.Update(Runtime.GetBytesForString(Password, SmbConstants.UniEncoding));
  648. switch (LmCompatibility)
  649. {
  650. case 0:
  651. case 1:
  652. case 2:
  653. {
  654. md4.Update(md4.Digest());
  655. md4.Digest(dest, offset, 16);
  656. break;
  657. }
  658. case 3:
  659. case 4:
  660. case 5:
  661. {
  662. if (ClientChallenge == null)
  663. {
  664. ClientChallenge = new byte[8];
  665. Random.NextBytes(ClientChallenge);
  666. }
  667. Hmact64 hmac = new Hmact64(md4.Digest());
  668. hmac.Update(Runtime.GetBytesForString(Username.ToUpper(),
  669. SmbConstants.UniEncoding));
  670. hmac.Update(Runtime.GetBytesForString(Domain.ToUpper(),
  671. SmbConstants.UniEncoding));
  672. byte[] ntlmv2Hash = hmac.Digest();
  673. hmac = new Hmact64(ntlmv2Hash);
  674. hmac.Update(challenge);
  675. hmac.Update(ClientChallenge);
  676. Hmact64 userKey = new Hmact64(ntlmv2Hash);
  677. userKey.Update(hmac.Digest());
  678. userKey.Digest(dest, offset, 16);
  679. break;
  680. }
  681. default:
  682. {
  683. md4.Update(md4.Digest());
  684. md4.Digest(dest, offset, 16);
  685. break;
  686. }
  687. }
  688. }
  689. catch (Exception e)
  690. {
  691. throw new SmbException(string.Empty, e);
  692. }
  693. }
  694. /// <summary>
  695. /// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
  696. /// equality.
  697. /// </summary>
  698. /// <remarks>
  699. /// Compares two <tt>NtlmPasswordAuthentication</tt> objects for
  700. /// equality. Two <tt>NtlmPasswordAuthentication</tt> objects are equal if
  701. /// their caseless domain and username fields are equal and either both hashes are external and they are equal or both internally supplied passwords are equal. If one <tt>NtlmPasswordAuthentication</tt> object has external hashes (meaning negotiated via NTLM HTTP Authentication) and the other does not they will not be equal. This is technically not correct however the server 8 byte challage would be required to compute and compare the password hashes but that it not available with this method.
  702. /// </remarks>
  703. public override bool Equals(object obj)
  704. {
  705. if (obj is NtlmPasswordAuthentication)
  706. {
  707. NtlmPasswordAuthentication ntlm = (NtlmPasswordAuthentication)obj;
  708. if (ntlm.Domain.ToUpper().Equals(Domain.ToUpper())
  709. && ntlm.Username.ToUpper().Equals(Username.ToUpper()))
  710. {
  711. if (HashesExternal && ntlm.HashesExternal)
  712. {
  713. return Arrays.Equals(AnsiHash, ntlm.AnsiHash)
  714. && Arrays.Equals(UnicodeHash, ntlm.UnicodeHash);
  715. }
  716. if (!HashesExternal && Password.Equals(ntlm.Password))
  717. {
  718. return true;
  719. }
  720. }
  721. }
  722. return false;
  723. }
  724. /// <summary>Return the upcased username hash code.</summary>
  725. /// <remarks>Return the upcased username hash code.</remarks>
  726. public override int GetHashCode()
  727. {
  728. return GetName().ToUpper().GetHashCode();
  729. }
  730. /// <summary>
  731. /// Return the domain and username in the format:
  732. /// <tt>domain\\username</tt>.
  733. /// </summary>
  734. /// <remarks>
  735. /// Return the domain and username in the format:
  736. /// <tt>domain\\username</tt>. This is equivalent to <tt>getName()</tt>.
  737. /// </remarks>
  738. public override string ToString()
  739. {
  740. return GetName();
  741. }
  742. /// <exception cref="System.FormatException"></exception>
  743. /// <exception cref="UnsupportedEncodingException"></exception>
  744. internal static string Unescape(string str)
  745. {
  746. char ch;
  747. int i;
  748. int j;
  749. int state;
  750. int len;
  751. char[] @out;
  752. byte[] b = new byte[1];
  753. if (str == null)
  754. {
  755. return null;
  756. }
  757. len = str.Length;
  758. @out = new char[len];
  759. state = 0;
  760. for (i = j = 0; i < len; i++)
  761. {
  762. switch (state)
  763. {
  764. case 0:
  765. {
  766. ch = str[i];
  767. if (ch == '%')
  768. {
  769. state = 1;
  770. }
  771. else
  772. {
  773. @out[j++] = ch;
  774. }
  775. break;
  776. }
  777. case 1:
  778. {
  779. b[0] = unchecked(
  780. (byte)(
  781. Convert.ToInt32(Runtime.Substring(str, i, i + 2), 16)
  782. & unchecked(0xFF)
  783. )
  784. );
  785. @out[j++] = (Runtime.GetStringForBytes(b, 0, 1, "ASCII"))[0];
  786. i++;
  787. state = 0;
  788. break;
  789. }
  790. }
  791. }
  792. return new string(@out, 0, j);
  793. }
  794. }
  795. }