SmbSession.cs 15 KB

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