SmbSession.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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 System.Collections.Generic;
  19. using System.IO;
  20. using System.Net;
  21. using SharpCifs.Netbios;
  22. using SharpCifs.Util.Sharpen;
  23. namespace SharpCifs.Smb
  24. {
  25. public sealed class SmbSession
  26. {
  27. private static readonly string LogonShare
  28. = Config.GetProperty("jcifs.smb.client.logonShare", null);
  29. private static readonly int LookupRespLimit
  30. = Config.GetInt("jcifs.netbios.lookupRespLimit", 3);
  31. private static readonly string Domain
  32. = Config.GetProperty("jcifs.smb.client.domain", null);
  33. private static readonly string Username
  34. = Config.GetProperty("jcifs.smb.client.username", null);
  35. private static readonly int CachePolicy
  36. = Config.GetInt("jcifs.netbios.cachePolicy", 60 * 10) * 60;
  37. internal static NbtAddress[] DcList;
  38. internal static long DcListExpiration;
  39. internal static int DcListCounter;
  40. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  41. private static NtlmChallenge Interrogate(NbtAddress addr)
  42. {
  43. UniAddress dc = new UniAddress(addr);
  44. SmbTransport trans = SmbTransport.GetSmbTransport(dc, 0);
  45. if (Username == null)
  46. {
  47. trans.Connect();
  48. if (SmbTransport.LogStatic.Level >= 3)
  49. {
  50. SmbTransport.LogStatic.WriteLine(
  51. "Default credentials (jcifs.smb.client.username/password)"
  52. + " not specified. SMB signing may not work propertly."
  53. + " Skipping DC interrogation.");
  54. }
  55. }
  56. else
  57. {
  58. SmbSession ssn = trans.GetSmbSession(NtlmPasswordAuthentication.Default);
  59. ssn.GetSmbTree(LogonShare, null).TreeConnect(null, null);
  60. }
  61. return new NtlmChallenge(trans.Server.EncryptionKey, dc);
  62. }
  63. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  64. /// <exception cref="UnknownHostException"></exception>
  65. public static NtlmChallenge GetChallengeForDomain()
  66. {
  67. if (Domain == null)
  68. {
  69. throw new SmbException("A domain was not specified");
  70. }
  71. lock (Domain)
  72. {
  73. long now = Runtime.CurrentTimeMillis();
  74. int retry = 1;
  75. do
  76. {
  77. if (DcListExpiration < now)
  78. {
  79. NbtAddress[] list = NbtAddress.GetAllByName(Domain, 0x1C, null, null);
  80. DcListExpiration = now + CachePolicy * 1000L;
  81. if (list != null && list.Length > 0)
  82. {
  83. DcList = list;
  84. }
  85. else
  86. {
  87. DcListExpiration = now + 1000 * 60 * 15;
  88. if (SmbTransport.LogStatic.Level >= 2)
  89. {
  90. SmbTransport.LogStatic.WriteLine("Failed to retrieve DC list from WINS");
  91. }
  92. }
  93. }
  94. int max = Math.Min(DcList.Length, LookupRespLimit);
  95. for (int j = 0; j < max; j++)
  96. {
  97. int i = DcListCounter++ % max;
  98. if (DcList[i] != null)
  99. {
  100. try
  101. {
  102. return Interrogate(DcList[i]);
  103. }
  104. catch (SmbException se)
  105. {
  106. if (SmbTransport.LogStatic.Level >= 2)
  107. {
  108. SmbTransport.LogStatic.WriteLine("Failed validate DC: " + DcList[i]);
  109. if (SmbTransport.LogStatic.Level > 2)
  110. {
  111. Runtime.PrintStackTrace(se, SmbTransport.LogStatic);
  112. }
  113. }
  114. }
  115. DcList[i] = null;
  116. }
  117. }
  118. DcListExpiration = 0;
  119. }
  120. while (retry-- > 0);
  121. DcListExpiration = now + 1000 * 60 * 15;
  122. }
  123. throw new UnknownHostException(
  124. "Failed to negotiate with a suitable domain controller for " + Domain);
  125. }
  126. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  127. /// <exception cref="UnknownHostException"></exception>
  128. public static byte[] GetChallenge(UniAddress dc)
  129. {
  130. return GetChallenge(dc, 0);
  131. }
  132. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  133. /// <exception cref="UnknownHostException"></exception>
  134. public static byte[] GetChallenge(UniAddress dc, int port)
  135. {
  136. SmbTransport trans = SmbTransport.GetSmbTransport(dc, port);
  137. trans.Connect();
  138. return trans.Server.EncryptionKey;
  139. }
  140. /// <summary>
  141. /// Authenticate arbitrary credentials represented by the
  142. /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
  143. /// specified by the <tt>UniAddress</tt> parameter.
  144. /// </summary>
  145. /// <remarks>
  146. /// Authenticate arbitrary credentials represented by the
  147. /// <tt>NtlmPasswordAuthentication</tt> object against the domain controller
  148. /// specified by the <tt>UniAddress</tt> parameter. If the credentials are
  149. /// not accepted, an <tt>SmbAuthException</tt> will be thrown. If an error
  150. /// occurs an <tt>SmbException</tt> will be thrown. If the credentials are
  151. /// valid, the method will return without throwing an exception. See the
  152. /// last <a href="../../../faq.html">FAQ</a> question.
  153. /// <p>
  154. /// See also the <tt>jcifs.smb.client.logonShare</tt> property.
  155. /// </remarks>
  156. /// <exception cref="SmbException"></exception>
  157. public static void Logon(UniAddress dc, NtlmPasswordAuthentication auth)
  158. {
  159. Logon(dc, -1, auth);
  160. }
  161. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  162. public static void Logon(UniAddress dc, int port, NtlmPasswordAuthentication auth)
  163. {
  164. SmbTree tree = SmbTransport.GetSmbTransport(dc, port)
  165. .GetSmbSession(auth)
  166. .GetSmbTree(LogonShare, null);
  167. if (LogonShare == null)
  168. {
  169. tree.TreeConnect(null, null);
  170. }
  171. else
  172. {
  173. Trans2FindFirst2 req = new Trans2FindFirst2("\\", "*", SmbFile.AttrDirectory);
  174. Trans2FindFirst2Response resp = new Trans2FindFirst2Response();
  175. tree.Send(req, resp);
  176. }
  177. }
  178. /// <summary>
  179. /// Clear All Cached Transport-Connections
  180. /// </summary>
  181. /// <remarks>
  182. /// Alias of SmbTransport.ClearCachedConnections
  183. /// </remarks>
  184. public static void ClearCachedConnections()
  185. {
  186. SmbTransport.ClearCachedConnections();
  187. }
  188. internal int ConnectionState;
  189. internal int Uid;
  190. internal List<object> Trees;
  191. private UniAddress _address;
  192. private int _port;
  193. private int _localPort;
  194. private IPAddress _localAddr;
  195. internal SmbTransport transport;
  196. internal NtlmPasswordAuthentication Auth;
  197. internal long Expiration;
  198. internal string NetbiosName;
  199. internal SmbSession(UniAddress address,
  200. int port,
  201. IPAddress localAddr,
  202. int localPort,
  203. NtlmPasswordAuthentication auth)
  204. {
  205. // Transport parameters allows trans to be removed from CONNECTIONS
  206. this._address = address;
  207. this._port = port;
  208. this._localAddr = localAddr;
  209. this._localPort = localPort;
  210. this.Auth = auth;
  211. Trees = new List<object>();
  212. ConnectionState = 0;
  213. }
  214. internal SmbTree GetSmbTree(string share, string service)
  215. {
  216. lock (this)
  217. {
  218. SmbTree t;
  219. if (share == null)
  220. {
  221. share = "IPC$";
  222. }
  223. /*
  224. for (IEnumeration e = trees.GetEnumerator(); e.MoveNext(); )
  225. {
  226. t = (SmbTree)e.Current;
  227. if (t.Matches(share, service))
  228. {
  229. return t;
  230. }
  231. }
  232. */
  233. foreach (var e in Trees)
  234. {
  235. t = (SmbTree)e;
  236. if (t.Matches(share, service))
  237. {
  238. return t;
  239. }
  240. }
  241. t = new SmbTree(this, share, service);
  242. Trees.Add(t);
  243. return t;
  244. }
  245. }
  246. internal bool Matches(NtlmPasswordAuthentication auth)
  247. {
  248. return this.Auth == auth || this.Auth.Equals(auth);
  249. }
  250. internal SmbTransport Transport()
  251. {
  252. lock (this)
  253. {
  254. if (transport == null)
  255. {
  256. transport = SmbTransport.GetSmbTransport(_address,
  257. _port,
  258. _localAddr,
  259. _localPort,
  260. null);
  261. }
  262. return transport;
  263. }
  264. }
  265. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  266. internal void Send(ServerMessageBlock request, ServerMessageBlock response)
  267. {
  268. lock (Transport())
  269. {
  270. if (response != null)
  271. {
  272. response.Received = false;
  273. }
  274. Expiration = Runtime.CurrentTimeMillis() + SmbConstants.SoTimeout;
  275. SessionSetup(request, response);
  276. if (response != null && response.Received)
  277. {
  278. return;
  279. }
  280. if (request is SmbComTreeConnectAndX)
  281. {
  282. SmbComTreeConnectAndX tcax = (SmbComTreeConnectAndX)request;
  283. if (NetbiosName != null && tcax.path.EndsWith("\\IPC$"))
  284. {
  285. tcax.path = "\\\\" + NetbiosName + "\\IPC$";
  286. }
  287. }
  288. request.Uid = Uid;
  289. request.Auth = Auth;
  290. try
  291. {
  292. transport.Send(request, response);
  293. }
  294. catch (SmbException se)
  295. {
  296. if (request is SmbComTreeConnectAndX)
  297. {
  298. Logoff(true);
  299. }
  300. request.Digest = null;
  301. throw;
  302. }
  303. }
  304. }
  305. /// <exception cref="SharpCifs.Smb.SmbException"></exception>
  306. internal void SessionSetup(ServerMessageBlock andx, ServerMessageBlock andxResponse)
  307. {
  308. lock (Transport())
  309. {
  310. NtlmContext nctx = null;
  311. SmbException ex = null;
  312. SmbComSessionSetupAndX request;
  313. SmbComSessionSetupAndXResponse response;
  314. byte[] token = new byte[0];
  315. int state = 10;
  316. while (ConnectionState != 0)
  317. {
  318. if (ConnectionState == 2 || ConnectionState == 3)
  319. {
  320. // connected or disconnecting
  321. return;
  322. }
  323. try
  324. {
  325. Runtime.Wait(transport);
  326. }
  327. catch (Exception ie)
  328. {
  329. throw new SmbException(ie.Message, ie);
  330. }
  331. }
  332. ConnectionState = 1;
  333. // trying ...
  334. try
  335. {
  336. transport.Connect();
  337. if (transport.Log.Level >= 4)
  338. {
  339. transport.Log.WriteLine("sessionSetup: accountName=" + Auth.Username
  340. + ",primaryDomain=" + Auth.Domain);
  341. }
  342. Uid = 0;
  343. do
  344. {
  345. switch (state)
  346. {
  347. case 10:
  348. {
  349. if (Auth != NtlmPasswordAuthentication.Anonymous
  350. && transport.HasCapability(SmbConstants.CapExtendedSecurity))
  351. {
  352. state = 20;
  353. break;
  354. }
  355. request = new SmbComSessionSetupAndX(this, andx, Auth);
  356. response = new SmbComSessionSetupAndXResponse(andxResponse);
  357. if (transport.IsSignatureSetupRequired(Auth))
  358. {
  359. if (Auth.HashesExternal
  360. && NtlmPasswordAuthentication.DefaultPassword
  361. != NtlmPasswordAuthentication.Blank)
  362. {
  363. transport.GetSmbSession(NtlmPasswordAuthentication.Default)
  364. .GetSmbTree(LogonShare, null)
  365. .TreeConnect(null, null);
  366. }
  367. else
  368. {
  369. byte[] signingKey
  370. = Auth.GetSigningKey(transport.Server.EncryptionKey);
  371. request.Digest = new SigningDigest(signingKey, false);
  372. }
  373. }
  374. request.Auth = Auth;
  375. try
  376. {
  377. transport.Send(request, response);
  378. }
  379. catch (SmbAuthException sae)
  380. {
  381. throw;
  382. }
  383. catch (SmbException se)
  384. {
  385. ex = se;
  386. }
  387. if (response.IsLoggedInAsGuest
  388. && Runtime.EqualsIgnoreCase("GUEST", Auth.Username) == false
  389. && transport.Server.Security != SmbConstants.SecurityShare
  390. && Auth != NtlmPasswordAuthentication.Anonymous)
  391. {
  392. throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
  393. }
  394. if (ex != null)
  395. {
  396. throw ex;
  397. }
  398. Uid = response.Uid;
  399. if (request.Digest != null)
  400. {
  401. transport.Digest = request.Digest;
  402. }
  403. ConnectionState = 2;
  404. state = 0;
  405. break;
  406. }
  407. case 20:
  408. {
  409. if (nctx == null)
  410. {
  411. bool doSigning
  412. = (transport.Flags2
  413. & SmbConstants.Flags2SecuritySignatures) != 0;
  414. nctx = new NtlmContext(Auth, doSigning);
  415. }
  416. if (SmbTransport.LogStatic.Level >= 4)
  417. {
  418. SmbTransport.LogStatic.WriteLine(nctx);
  419. }
  420. if (nctx.IsEstablished())
  421. {
  422. NetbiosName = nctx.GetNetbiosName();
  423. ConnectionState = 2;
  424. state = 0;
  425. break;
  426. }
  427. try
  428. {
  429. token = nctx.InitSecContext(token, 0, token.Length);
  430. }
  431. catch (SmbException se)
  432. {
  433. try
  434. {
  435. transport.Disconnect(true);
  436. }
  437. catch (IOException)
  438. {
  439. }
  440. Uid = 0;
  441. throw;
  442. }
  443. if (token != null)
  444. {
  445. request = new SmbComSessionSetupAndX(this, null, token);
  446. response = new SmbComSessionSetupAndXResponse(null);
  447. if (transport.IsSignatureSetupRequired(Auth))
  448. {
  449. byte[] signingKey = nctx.GetSigningKey();
  450. if (signingKey != null)
  451. {
  452. request.Digest = new SigningDigest(signingKey, true);
  453. }
  454. }
  455. request.Uid = Uid;
  456. Uid = 0;
  457. try
  458. {
  459. transport.Send(request, response);
  460. }
  461. catch (SmbAuthException sae)
  462. {
  463. throw;
  464. }
  465. catch (SmbException se)
  466. {
  467. ex = se;
  468. try
  469. {
  470. transport.Disconnect(true);
  471. }
  472. catch (Exception)
  473. {
  474. }
  475. }
  476. if (response.IsLoggedInAsGuest
  477. && Runtime.EqualsIgnoreCase("GUEST", Auth.Username)
  478. == false)
  479. {
  480. throw new SmbAuthException(NtStatus.NtStatusLogonFailure);
  481. }
  482. if (ex != null)
  483. {
  484. throw ex;
  485. }
  486. Uid = response.Uid;
  487. if (request.Digest != null)
  488. {
  489. transport.Digest = request.Digest;
  490. }
  491. token = response.Blob;
  492. }
  493. break;
  494. }
  495. default:
  496. {
  497. throw new SmbException("Unexpected session setup state: " + state);
  498. }
  499. }
  500. }
  501. while (state != 0);
  502. }
  503. catch (SmbException se)
  504. {
  505. Logoff(true);
  506. ConnectionState = 0;
  507. throw;
  508. }
  509. finally
  510. {
  511. Runtime.NotifyAll(transport);
  512. }
  513. }
  514. }
  515. internal void Logoff(bool inError)
  516. {
  517. lock (Transport())
  518. {
  519. if (ConnectionState != 2)
  520. {
  521. // not-connected
  522. return;
  523. }
  524. ConnectionState = 3;
  525. // disconnecting
  526. NetbiosName = null;
  527. foreach (SmbTree t in Trees)
  528. {
  529. t.TreeDisconnect(inError);
  530. }
  531. if (!inError && transport.Server.Security != SmbConstants.SecurityShare)
  532. {
  533. SmbComLogoffAndX request = new SmbComLogoffAndX(null);
  534. request.Uid = Uid;
  535. try
  536. {
  537. transport.Send(request, null);
  538. }
  539. catch (SmbException)
  540. {
  541. }
  542. Uid = 0;
  543. }
  544. ConnectionState = 0;
  545. Runtime.NotifyAll(transport);
  546. }
  547. }
  548. public override string ToString()
  549. {
  550. return "SmbSession[accountName=" + Auth.Username
  551. + ",primaryDomain=" + Auth.Domain
  552. + ",uid=" + Uid
  553. + ",connectionState=" + ConnectionState + "]";
  554. }
  555. }
  556. }