SecureShell.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include <stdio.h>
  5. #include "PuttyIntf.h"
  6. #include "Net.h"
  7. #include "Interface.h"
  8. #include "SecureShell.h"
  9. #include "TextsCore.h"
  10. #include "HelpCore.h"
  11. #include "Common.h"
  12. #include "ScpMain.h"
  13. #include "Security.h"
  14. #ifndef AUTO_WINSOCK
  15. #include <winsock2.h>
  16. #endif
  17. //---------------------------------------------------------------------------
  18. #pragma package(smart_init)
  19. //---------------------------------------------------------------------------
  20. #define MAX_BUFSIZE 32768
  21. const TColor LogLineColors[] =
  22. {clGreen, clRed, clMaroon, clBlue, clGray};
  23. //---------------------------------------------------------------------------
  24. __fastcall TSecureShell::TSecureShell()
  25. {
  26. FSessionData = new TSessionData("");
  27. FActive = False;
  28. PendLen = 0;
  29. PendSize = 0;
  30. FStdErrorTemp = "";
  31. FBytesSent = 0;
  32. FBytesReceived = 0;
  33. FLog = new TSessionLog(this);
  34. FOnQueryUser = NULL;
  35. FOnPromptUser = NULL;
  36. FOnDisplayBanner = NULL;
  37. FOnShowExtendedException = NULL;
  38. FOnUpdateStatus = NULL;
  39. FOnStdError = NULL;
  40. FOnCaptureOutput = NULL;
  41. FOnClose = NULL;
  42. FCSCipher = cipWarn; // = not detected yet
  43. FSCCipher = cipWarn;
  44. FReachedStatus = 0;
  45. UpdateStatus(sshClosed);
  46. FConfig = new Config();
  47. FSocket = new SOCKET;
  48. FMaxPacketSize = NULL;
  49. FBufSize = 0;
  50. }
  51. //---------------------------------------------------------------------------
  52. __fastcall TSecureShell::~TSecureShell()
  53. {
  54. ClearStdError();
  55. Active = false;
  56. SAFE_DESTROY(FSessionData);
  57. SAFE_DESTROY(FLog);
  58. delete FConfig;
  59. FConfig = NULL;
  60. UserObject = NULL;
  61. delete FSocket;
  62. FSocket = NULL;
  63. }
  64. //---------------------------------------------------------------------------
  65. void __fastcall TSecureShell::Open()
  66. {
  67. const char * InitError;
  68. char * RealHost;
  69. FStoredPasswordTried = false;
  70. FStoredPasswordTriedForKI = false;
  71. FReachedStatus = 0;
  72. {
  73. TCoreGuard Guard;
  74. SessionsCount++;
  75. if (SessionsCount == 1)
  76. {
  77. UpdateStatus(sshInitWinSock);
  78. NetInitialize();
  79. }
  80. else
  81. {
  82. Log->Id = reinterpret_cast<unsigned int>(this);
  83. }
  84. }
  85. Log->AddStartupInfo();
  86. Active = false;
  87. FBackend = &ssh_backend;
  88. FAuthenticationLog = "";
  89. UpdateStatus(sshLookupHost);
  90. SessionData->StoreToConfig(FConfig);
  91. InitError = FBackend->init(this, &FBackendHandle, FConfig,
  92. SessionData->HostName.c_str(), SessionData->PortNumber, &RealHost, 0,
  93. FConfig->tcp_keepalives);
  94. if (InitError)
  95. {
  96. FatalError(InitError);
  97. }
  98. FRealHost = RealHost;
  99. UpdateStatus(sshConnect);
  100. /*FLoggingContext = log_init(this, (void *)FConfig);
  101. FBackend->provide_logctx(FBackendHandle, FLoggingContext);*/
  102. Init();
  103. CheckConnection(CONNECTION_FAILED);
  104. FLastDataSent = Now();
  105. FLoginTime = Now();
  106. Log->AddSeparator();
  107. UpdateStatus(sshAuthenticated);
  108. }
  109. //---------------------------------------------------------------------------
  110. void __fastcall TSecureShell::Init()
  111. {
  112. try
  113. {
  114. try
  115. {
  116. while (!FBackend->sendok(FBackendHandle))
  117. {
  118. if (Configuration->LogProtocol >= 1)
  119. {
  120. LogEvent("Waiting for the server to continue with the initialisation");
  121. }
  122. WaitForData(true);
  123. }
  124. }
  125. catch(Exception & E)
  126. {
  127. if ((FReachedStatus == sshAuthenticate) && !FAuthenticationLog.IsEmpty())
  128. {
  129. FatalError(&E, FMTLOAD(AUTHENTICATION_LOG, (FAuthenticationLog)));
  130. }
  131. else
  132. {
  133. throw;
  134. }
  135. }
  136. }
  137. catch(Exception & E)
  138. {
  139. if (FReachedStatus == sshAuthenticate)
  140. {
  141. FatalError(&E, LoadStr(AUTHENTICATION_FAILED));
  142. }
  143. else
  144. {
  145. throw;
  146. }
  147. }
  148. }
  149. //---------------------------------------------------------------------------
  150. void __fastcall TSecureShell::PuttyLogEvent(const AnsiString & Str)
  151. {
  152. #define SERVER_VERSION_MSG "Server version: "
  153. // Gross hack
  154. if (Str.Pos(SERVER_VERSION_MSG) == 1)
  155. {
  156. FSshVersionString = Str.SubString(strlen(SERVER_VERSION_MSG) + 1,
  157. Str.Length() - strlen(SERVER_VERSION_MSG));
  158. }
  159. LogEvent(Str);
  160. }
  161. //---------------------------------------------------------------------------
  162. AnsiString __fastcall TSecureShell::GetSshImplementation()
  163. {
  164. const char * Ptr = strchr(FSshVersionString.c_str(), '-');
  165. if (Ptr != NULL)
  166. {
  167. Ptr = strchr(Ptr + 1, '-');
  168. }
  169. return (Ptr != NULL) ? AnsiString(Ptr + 1) : AnsiString();
  170. }
  171. //---------------------------------------------------------------------
  172. AnsiString __fastcall TSecureShell::GetPassword()
  173. {
  174. return (FPassword.IsEmpty() ? AnsiString() :
  175. DecryptPassword(FPassword, SessionData->SessionName));
  176. }
  177. //---------------------------------------------------------------------
  178. bool __fastcall TSecureShell::GetStoredPasswordTried()
  179. {
  180. return FStoredPasswordTried || FStoredPasswordTriedForKI;
  181. }
  182. //---------------------------------------------------------------------------
  183. TDateTime __fastcall TSecureShell::GetIdleInterval()
  184. {
  185. return (FSessionData->PingType != ptOff) ? FSessionData->PingIntervalDT :
  186. TDateTime(0);
  187. }
  188. //---------------------------------------------------------------------------
  189. bool __fastcall TSecureShell::PromptUser(const AnsiString Prompt,
  190. AnsiString & Response, bool IsPassword)
  191. {
  192. USEDPARAM(IsPassword);
  193. assert(IsPassword); // false only for username prompts
  194. bool Result;
  195. if (Prompt.Pos("Passphrase for key ") == 1)
  196. {
  197. AnsiString Key(Prompt);
  198. int P = Prompt.Pos("\"");
  199. if (P > 0)
  200. {
  201. Key.Delete(1, P);
  202. P = Key.LastDelimiter("\"");
  203. if (P > 0)
  204. {
  205. Key.SetLength(P - 1);
  206. }
  207. }
  208. LogEvent(FORMAT("Passphrase prompt (%s)", (Prompt)));
  209. Result = DoPromptUser(FMTLOAD(PROMPT_KEY_PASSPHRASE, (Key)),
  210. pkPassphrase, Response);
  211. }
  212. else if (Prompt.Pos("'s password: "))
  213. {
  214. LogEvent(FORMAT("Session password prompt (%s)", (Prompt)));
  215. if (!SessionData->Password.IsEmpty() && !FStoredPasswordTried)
  216. {
  217. LogEvent("Using stored password.");
  218. Result = true;
  219. Response = SessionData->Password;
  220. FStoredPasswordTried = true;
  221. }
  222. else
  223. {
  224. LogEvent("Asking user for password.");
  225. Result = DoPromptUser(
  226. FMTLOAD(PROMPT_SESSION_PASSWORD, (SessionData->SessionName)),
  227. pkPassword, Response);
  228. }
  229. }
  230. else
  231. {
  232. // in other cases we assume TIS/Cryptocard/keyboard-interactive authentification prompt
  233. LogEvent(FORMAT("%s prompt from server", (Prompt)));
  234. if (!SessionData->Password.IsEmpty() &&
  235. SessionData->AuthKIPassword && !FStoredPasswordTriedForKI)
  236. {
  237. LogEvent("Responding with stored password.");
  238. Result = true;
  239. Response = SessionData->Password;
  240. FStoredPasswordTriedForKI = true;
  241. }
  242. else
  243. {
  244. LogEvent("Asking user for response.");
  245. static const AnsiString ResponseSuffix("\r\nResponse: ");
  246. // Strip Cryptocard/TIS "Response" suffix
  247. AnsiString UserPrompt = Prompt;
  248. if (UserPrompt.SubString(UserPrompt.Length() - ResponseSuffix.Length() + 1,
  249. ResponseSuffix.Length()) == ResponseSuffix)
  250. {
  251. UserPrompt.SetLength(UserPrompt.Length() - ResponseSuffix.Length());
  252. }
  253. Result = DoPromptUser(UserPrompt, pkServerPrompt, Response);
  254. }
  255. };
  256. if (Configuration->RememberPassword)
  257. {
  258. FPassword = EncryptPassword(Response, SessionData->SessionName);
  259. }
  260. return Result;
  261. }
  262. //---------------------------------------------------------------------------
  263. bool __fastcall TSecureShell::DoPromptUser(AnsiString Prompt, TPromptKind Kind,
  264. AnsiString & Response)
  265. {
  266. bool Result = false;
  267. if (OnPromptUser != NULL)
  268. {
  269. OnPromptUser(this, Prompt, Kind, Response, Result, NULL);
  270. }
  271. return Result;
  272. }
  273. //---------------------------------------------------------------------------
  274. void __fastcall TSecureShell::GotHostKey()
  275. {
  276. // due to re-key GotHostKey() may be called again later during session
  277. if (FReachedStatus < sshAuthenticate)
  278. {
  279. UpdateStatus(sshAuthenticate);
  280. }
  281. }
  282. //---------------------------------------------------------------------------
  283. void __fastcall TSecureShell::FromBackend(Boolean IsStdErr, char * Data, Integer Length)
  284. {
  285. CheckConnection();
  286. // Following is taken from scp.c from_backend() and modified
  287. if (IsStdErr)
  288. {
  289. AddStdError(AnsiString(Data, Length));
  290. }
  291. else
  292. {
  293. unsigned char *p = (unsigned char *)Data;
  294. unsigned Len = (unsigned)Length;
  295. // If this is before the real session begins, raise exception.
  296. if (!OutPtr)
  297. {
  298. FatalError("Internal error: Session not yet begun.");
  299. }
  300. if ((OutLen > 0) && (Len > 0))
  301. {
  302. unsigned Used = OutLen;
  303. if (Used > Len) Used = Len;
  304. memcpy(OutPtr, p, Used);
  305. OutPtr += Used; OutLen -= Used;
  306. p += Used; Len -= Used;
  307. }
  308. if (Len > 0)
  309. {
  310. if (PendSize < PendLen + Len)
  311. {
  312. PendSize = PendLen + Len + 4096;
  313. Pending = (char *)
  314. (Pending ? srealloc(Pending, PendSize) : smalloc(PendSize));
  315. if (!Pending) FatalError("Out of memory");
  316. }
  317. memcpy(Pending + PendLen, p, Len);
  318. PendLen += Len;
  319. }
  320. }
  321. }
  322. //---------------------------------------------------------------------------
  323. Integer __fastcall TSecureShell::Receive(char * Buf, Integer Len)
  324. {
  325. CheckConnection();
  326. if (Len > 0)
  327. {
  328. // Following is taken from scp.c ssh_scp_recv() and modified
  329. OutPtr = Buf;
  330. OutLen = Len;
  331. /*
  332. * See if the pending-input block contains some of what we
  333. * need.
  334. */
  335. if (PendLen > 0)
  336. {
  337. unsigned PendUsed = PendLen;
  338. if (PendUsed > OutLen)
  339. {
  340. PendUsed = OutLen;
  341. }
  342. memcpy(OutPtr, Pending, PendUsed);
  343. memmove(Pending, Pending + PendUsed, PendLen - PendUsed);
  344. OutPtr += PendUsed;
  345. OutLen -= PendUsed;
  346. PendLen -= PendUsed;
  347. if (PendLen == 0)
  348. {
  349. PendSize = 0;
  350. sfree(Pending);
  351. Pending = NULL;
  352. }
  353. }
  354. // I don't undestand this yet, but it works :-)
  355. while (OutLen > 0)
  356. {
  357. if (Configuration->LogProtocol >= 1)
  358. {
  359. LogEvent(FORMAT("Waiting for another %u bytes", (static_cast<int>(OutLen))));
  360. }
  361. WaitForData(false);
  362. }
  363. // This seems ambiguous
  364. if (Len <= 0) FatalError(LoadStr(LOST_CONNECTION));
  365. };
  366. FBytesReceived += Len;
  367. if (Configuration->LogProtocol >= 1)
  368. {
  369. LogEvent(FORMAT("Received %u bytes", (static_cast<int>(Len))));
  370. }
  371. return Len;
  372. }
  373. //---------------------------------------------------------------------------
  374. AnsiString __fastcall TSecureShell::ReceiveLine()
  375. {
  376. unsigned Index;
  377. Char Ch;
  378. AnsiString Line;
  379. Boolean EOL = False;
  380. do
  381. {
  382. // If there is any buffer of received chars
  383. if (PendLen > 0)
  384. {
  385. Index = 0;
  386. // Repeat until we walk thru whole buffer or reach end-of-line
  387. while ((Index < PendLen) && (!Index || (Pending[Index-1] != '\n')))
  388. {
  389. Index++;
  390. }
  391. EOL = (Boolean)(Index && (Pending[Index-1] == '\n'));
  392. Integer PrevLen = Line.Length();
  393. Line.SetLength(PrevLen + Index);
  394. Receive(Line.c_str() + PrevLen, Index);
  395. }
  396. // If buffer don't contain end-of-line character
  397. // we read one more which causes receiving new buffer of chars
  398. if (!EOL)
  399. {
  400. Receive(&Ch, 1);
  401. Line += Ch;
  402. EOL = (Ch == '\n');
  403. }
  404. }
  405. while (!EOL);
  406. // We don't want end-of-line character
  407. Line.SetLength(Line.Length()-1);
  408. CaptureOutput(llOutput, Line);
  409. return Line;
  410. }
  411. //---------------------------------------------------------------------------
  412. void __fastcall TSecureShell::SendSpecial(int Code)
  413. {
  414. LogEvent(FORMAT("Sending special code: %d", (Code)));
  415. CheckConnection();
  416. FBackend->special(FBackendHandle, (Telnet_Special)Code);
  417. CheckConnection();
  418. FLastDataSent = Now();
  419. }
  420. //---------------------------------------------------------------------------
  421. void __fastcall TSecureShell::SendEOF()
  422. {
  423. SendSpecial(TS_EOF);
  424. }
  425. //---------------------------------------------------------------------------
  426. void __fastcall TSecureShell::Send(const char * Buf, Integer Len)
  427. {
  428. CheckConnection();
  429. FBufSize = FBackend->send(FBackendHandle, (char *)Buf, Len);
  430. if (Configuration->LogProtocol >= 1)
  431. {
  432. LogEvent(FORMAT("Sent %u bytes", (static_cast<int>(Len))));
  433. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (FBufSize)));
  434. }
  435. FLastDataSent = Now();
  436. FBytesSent += Len;
  437. while (FBufSize > MAX_BUFSIZE)
  438. {
  439. if (Configuration->LogProtocol >= 1)
  440. {
  441. LogEvent(FORMAT("There are %u bytes remaining in the send buffer, "
  442. "need to send at least another %u bytes",
  443. (FBufSize, FBufSize - MAX_BUFSIZE)));
  444. }
  445. // it seems that this does not work anyway
  446. // (i.e. once the send buffer fills we hang here)
  447. WaitForData(true);
  448. FBufSize = FBackend->sendbuffer(FBackendHandle);
  449. if (Configuration->LogProtocol >= 1)
  450. {
  451. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (FBufSize)));
  452. }
  453. }
  454. CheckConnection();
  455. }
  456. //---------------------------------------------------------------------------
  457. void __fastcall TSecureShell::SendNull()
  458. {
  459. LogEvent("Sending NULL.");
  460. Send("", 1);
  461. }
  462. //---------------------------------------------------------------------------
  463. void __fastcall TSecureShell::SendStr(AnsiString Str)
  464. {
  465. CheckConnection();
  466. Send(Str.c_str(), Str.Length());
  467. }
  468. //---------------------------------------------------------------------------
  469. void __fastcall TSecureShell::SendLine(AnsiString Line)
  470. {
  471. SendStr(Line);
  472. Send("\n", 1);
  473. Log->Add(llInput, Line);
  474. }
  475. //---------------------------------------------------------------------------
  476. void __fastcall TSecureShell::AddStdError(AnsiString Str)
  477. {
  478. StdError += Str;
  479. Integer P;
  480. Str = DeleteChar(Str, '\r');
  481. // We send only whole line at once to log, so we have to cache
  482. // incoming std error data
  483. FStdErrorTemp += Str;
  484. AnsiString Line;
  485. // Do we have at least one complete line in std error cache?
  486. while ((P = FStdErrorTemp.Pos("\n")) > 0)
  487. {
  488. Line = FStdErrorTemp.SubString(1, P-1);
  489. FStdErrorTemp.Delete(1, P);
  490. AddStdErrorLine(Line);
  491. }
  492. }
  493. //---------------------------------------------------------------------------
  494. void __fastcall TSecureShell::AddStdErrorLine(const AnsiString Str)
  495. {
  496. if (OnStdError == NULL)
  497. {
  498. if (Status == sshAuthenticate)
  499. {
  500. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? "" : "\n") + Str;
  501. }
  502. }
  503. else
  504. {
  505. OnStdError(this, llStdError, Str);
  506. }
  507. CaptureOutput(llStdError, Str);
  508. }
  509. //---------------------------------------------------------------------------
  510. void __fastcall TSecureShell::ClearStdError()
  511. {
  512. // Flush std error cache
  513. if (!FStdErrorTemp.IsEmpty())
  514. {
  515. if (Status == sshAuthenticate)
  516. {
  517. FAuthenticationLog +=
  518. (FAuthenticationLog.IsEmpty() ? "" : "\n") + FStdErrorTemp;
  519. }
  520. CaptureOutput(llStdError, FStdErrorTemp);
  521. FStdErrorTemp = "";
  522. }
  523. StdError = "";
  524. }
  525. //---------------------------------------------------------------------------
  526. void __fastcall TSecureShell::CaptureOutput(TLogLineType Type,
  527. const AnsiString & Line)
  528. {
  529. if (FOnCaptureOutput != NULL)
  530. {
  531. FOnCaptureOutput(this, Type, Line);
  532. }
  533. Log->Add(Type, Line);
  534. }
  535. //---------------------------------------------------------------------------
  536. void __fastcall TSecureShell::FatalError(Exception * E, AnsiString Msg)
  537. {
  538. if (FActive)
  539. {
  540. // We log this instead of exception handler, because Close() would
  541. // probably cause exception handler to loose pointer to TShellLog()
  542. LogEvent("Attempt to close connection due to fatal exception:");
  543. Log->Add(llException, Msg);
  544. Log->AddException(E);
  545. Close();
  546. }
  547. SSH_FATAL_ERROR_EXT(E, Msg);
  548. }
  549. //---------------------------------------------------------------------------
  550. void __fastcall TSecureShell::FatalError(AnsiString Error)
  551. {
  552. FatalError(NULL, Error);
  553. }
  554. //---------------------------------------------------------------------------
  555. void __fastcall TSecureShell::SetSocket(void * value)
  556. {
  557. assert(value);
  558. // now this can be called repeatedly, so allow being called again with
  559. // the same socket
  560. if (FActive && (*static_cast<SOCKET*>(value) != INVALID_SOCKET) &&
  561. (*static_cast<SOCKET*>(FSocket) != *static_cast<SOCKET*>(value)))
  562. FatalError("Cannot set socket during connection");
  563. assert(FSocket);
  564. *static_cast<SOCKET*>(FSocket) = *static_cast<SOCKET*>(value);
  565. if (*static_cast<SOCKET*>(FSocket) != INVALID_SOCKET)
  566. {
  567. FActive = true;
  568. }
  569. else
  570. {
  571. Discard();
  572. }
  573. }
  574. //---------------------------------------------------------------------------
  575. void __fastcall TSecureShell::SetSessionData(TSessionData * value)
  576. {
  577. assert(!FActive);
  578. FSessionData->Assign(value);
  579. }
  580. //---------------------------------------------------------------------------
  581. void __fastcall TSecureShell::SetActive(bool value)
  582. {
  583. if (FActive != value)
  584. {
  585. if (value)
  586. {
  587. Open();
  588. }
  589. else
  590. {
  591. Close();
  592. }
  593. }
  594. }
  595. //---------------------------------------------------------------------------
  596. bool __fastcall TSecureShell::GetActive() const
  597. {
  598. return FActive;
  599. }
  600. //---------------------------------------------------------------------------
  601. void __fastcall TSecureShell::Discard()
  602. {
  603. bool WasActive = FActive;
  604. FActive = false;
  605. if (WasActive)
  606. {
  607. if (FReachedStatus)
  608. {
  609. TCoreGuard Guard;
  610. SessionsCount--;
  611. if (SessionsCount == 0)
  612. {
  613. NetFinalize();
  614. }
  615. }
  616. if (OnClose)
  617. {
  618. OnClose(this);
  619. }
  620. }
  621. FStatus = sshClosed;
  622. }
  623. //---------------------------------------------------------------------------
  624. void __fastcall TSecureShell::Close()
  625. {
  626. LogEvent("Closing connection.");
  627. CheckConnection();
  628. FBackend->free(FBackendHandle);
  629. Discard();
  630. }
  631. //---------------------------------------------------------------------------
  632. void inline __fastcall TSecureShell::CheckConnection(int Message)
  633. {
  634. if (!FActive || get_ssh_state_closed(FBackendHandle))
  635. {
  636. AnsiString Str = LoadStr(Message >= 0 ? Message : NOT_CONNECTED);
  637. int ExitCode = get_ssh_exitcode(FBackendHandle);
  638. if (ExitCode >= 0)
  639. {
  640. Str += " " + FMTLOAD(SSH_EXITCODE, (ExitCode));
  641. }
  642. FatalError(Str);
  643. }
  644. }
  645. //---------------------------------------------------------------------------
  646. bool __fastcall TSecureShell::Select(int Sec)
  647. {
  648. CheckConnection();
  649. struct timeval time;
  650. fd_set readfds;
  651. FD_ZERO(&readfds);
  652. FD_SET(*static_cast<SOCKET*>(FSocket), &readfds);
  653. time.tv_sec = Sec;
  654. time.tv_usec = 0;
  655. int R = select(1, &readfds, NULL, NULL, &time);
  656. if (R < 0)
  657. {
  658. SSH_FATAL_ERROR(FMTLOAD(UNKNOWN_SOCKET_STATUS, (R)));
  659. }
  660. if (Configuration->LogProtocol >= 2)
  661. {
  662. LogEvent(FORMAT("Select result is %d", (R)));
  663. }
  664. return (R > 0);
  665. }
  666. //---------------------------------------------------------------------------
  667. void __fastcall TSecureShell::PoolForData(unsigned int & Result)
  668. {
  669. if (Configuration->LogProtocol >= 2)
  670. {
  671. LogEvent("Pooling for data in case they finally arrives");
  672. }
  673. if (Select(0))
  674. {
  675. LogEvent("Data has arrived, closing query to user.");
  676. Result = qaRetry;
  677. }
  678. }
  679. //---------------------------------------------------------------------------
  680. extern int select_result(WPARAM, LPARAM);
  681. void __fastcall TSecureShell::WaitForData(bool Sending)
  682. {
  683. bool NeedToWait = true;
  684. SOCKET & Socket = *static_cast<SOCKET*>(FSocket);
  685. if (socket_writable(Socket))
  686. {
  687. if (Configuration->LogProtocol >= 1)
  688. {
  689. LogEvent("Checking low level send buffer");
  690. }
  691. select_result((WPARAM)(Socket), (LPARAM)FD_WRITE);
  692. }
  693. if (FBufSize > 0)
  694. {
  695. if (Configuration->LogProtocol >= 1)
  696. {
  697. LogEvent(FORMAT("Trying to dispatch send buffer (%u bytes)", (FBufSize)));
  698. }
  699. int NewBufSize = FBackend->send(FBackendHandle, "", 0);
  700. if ((NewBufSize < FBufSize) && Sending)
  701. {
  702. NeedToWait = false;
  703. }
  704. FBufSize = NewBufSize;
  705. if (Configuration->LogProtocol >= 1)
  706. {
  707. LogEvent(FORMAT("There are %u bytes remaining in the send buffer", (FBufSize)));
  708. }
  709. }
  710. bool IncomingData;
  711. if (!NeedToWait)
  712. {
  713. if (Configuration->LogProtocol >= 2)
  714. {
  715. LogEvent("Looking for incoming data");
  716. }
  717. // This is just attempt to make it as close as possible to previous behaviour
  718. // Maybe it is not necessary at all.
  719. IncomingData = Select(0);
  720. }
  721. else
  722. {
  723. do
  724. {
  725. if (Configuration->LogProtocol >= 2)
  726. {
  727. LogEvent("Looking for incoming data");
  728. }
  729. IncomingData = Select(FSessionData->Timeout);
  730. if (!IncomingData)
  731. {
  732. LogEvent("Waiting for data timed out, asking user what to do.");
  733. TQueryParams Params(qpFatalAbort | qpAllowContinueOnError);
  734. Params.Timer = 500;
  735. Params.TimerEvent = PoolForData;
  736. Params.TimerMessage = FMTLOAD(TIMEOUT_STILL_WAITING, (FSessionData->Timeout));
  737. Params.TimerAnswers = qaAbort;
  738. if (DoQueryUser(FMTLOAD(CONFIRM_PROLONG_TIMEOUT, (FSessionData->Timeout)),
  739. qaRetry | qaAbort, &Params) != qaRetry)
  740. {
  741. FatalError(LoadStr(USER_TERMINATED));
  742. }
  743. }
  744. }
  745. while (!IncomingData);
  746. }
  747. if (IncomingData)
  748. {
  749. select_result((WPARAM)(Socket), (LPARAM)FD_READ);
  750. }
  751. }
  752. //---------------------------------------------------------------------------
  753. bool __fastcall TSecureShell::SshFallbackCmd() const
  754. {
  755. return ssh_fallback_cmd(FBackendHandle);
  756. }
  757. //---------------------------------------------------------------------------
  758. void __fastcall TSecureShell::Error(const AnsiString Error) const
  759. {
  760. SSH_ERROR(Error);
  761. }
  762. //---------------------------------------------------------------------------
  763. extern int (WINAPI *p_WSAEnumNetworkEvents)
  764. (SOCKET s, WSAEVENT hEventObject, LPWSANETWORKEVENTS lpNetworkEvents);
  765. //---------------------------------------------------------------------------
  766. void __fastcall TSecureShell::Idle()
  767. {
  768. if (Configuration->LogProtocol >= 1)
  769. {
  770. LogEvent("Session upkeep");
  771. }
  772. noise_regular();
  773. // Keep session alive
  774. if ((FSessionData->PingType != ptOff) &&
  775. (Now() - FLastDataSent > FSessionData->PingIntervalDT))
  776. {
  777. KeepAlive();
  778. // in case keep alive could not be processed, postpone next attempt
  779. FLastDataSent = Now();
  780. }
  781. call_ssh_timer(FBackendHandle);
  782. // to let detect dropped connection immediatelly, also to let
  783. // process SSH-level communication with the server (KEX particularly)
  784. if (Select(0))
  785. {
  786. LogEvent("Detected incoming data while idle");
  787. select_result((WPARAM)(*static_cast<SOCKET*>(FSocket)), (LPARAM)FD_READ);
  788. CheckConnection();
  789. }
  790. }
  791. //---------------------------------------------------------------------------
  792. void __fastcall TSecureShell::KeepAlive()
  793. {
  794. LogEvent("Sending null packet to keep session alive.");
  795. SendSpecial(TS_PING);
  796. }
  797. //---------------------------------------------------------------------------
  798. void __fastcall TSecureShell::SetLog(TSessionLog * value)
  799. {
  800. FLog->Assign(value);
  801. }
  802. //---------------------------------------------------------------------------
  803. void __fastcall TSecureShell::SetConfiguration(TConfiguration *value)
  804. {
  805. FConfiguration = value;
  806. Log->Configuration = value;
  807. }
  808. //---------------------------------------------------------------------------
  809. TDateTime __fastcall TSecureShell::GetDuration() const
  810. {
  811. return Now() - FLoginTime;
  812. }
  813. //---------------------------------------------------------------------------
  814. int __fastcall TSecureShell::RemainingSendBuffer()
  815. {
  816. return MAX_BUFSIZE - FBufSize;
  817. }
  818. //---------------------------------------------------------------------------
  819. unsigned long __fastcall TSecureShell::MaxPacketSize()
  820. {
  821. if (SshVersion == 1)
  822. {
  823. return 0;
  824. }
  825. else
  826. {
  827. if (FMaxPacketSize == NULL)
  828. {
  829. FMaxPacketSize = ssh2_remmaxpkt(FBackendHandle);
  830. }
  831. return *FMaxPacketSize;
  832. }
  833. }
  834. //---------------------------------------------------------------------------
  835. TCompressionType __fastcall TSecureShell::FuncToCompression(
  836. const void * Compress) const
  837. {
  838. if (SshVersion == 1)
  839. {
  840. return get_ssh1_compressing(FBackendHandle) ? ctZLib : ctNone;
  841. }
  842. else
  843. {
  844. return (ssh_compress *)Compress == &ssh_zlib ? ctZLib : ctNone;
  845. }
  846. }
  847. //---------------------------------------------------------------------------
  848. TCompressionType __fastcall TSecureShell::GetCSCompression() const
  849. {
  850. assert(Active);
  851. return FuncToCompression(get_cscomp(FBackendHandle));
  852. }
  853. //---------------------------------------------------------------------------
  854. TCompressionType __fastcall TSecureShell::GetSCCompression() const
  855. {
  856. assert(Active);
  857. return FuncToCompression(get_sccomp(FBackendHandle));
  858. }
  859. //---------------------------------------------------------------------------
  860. int __fastcall TSecureShell::GetSshVersion() const
  861. {
  862. assert(Active);
  863. return get_ssh_version(FBackendHandle);
  864. }
  865. //---------------------------------------------------------------------------
  866. TCipher __fastcall TSecureShell::FuncToSsh1Cipher(const void * Cipher) const
  867. {
  868. const ssh_cipher *CipherFuncs[] =
  869. {&ssh_3des, &ssh_des, &ssh_blowfish_ssh1};
  870. const TCipher TCiphers[] = {cip3DES, cipDES, cipBlowfish};
  871. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  872. TCipher Result = cipWarn;
  873. for (int Index = 0; Index < LENOF(TCiphers); Index++)
  874. {
  875. if ((ssh_cipher *)Cipher == CipherFuncs[Index])
  876. {
  877. Result = TCiphers[Index];
  878. }
  879. }
  880. assert(Result != cipWarn);
  881. return Result;
  882. }
  883. //---------------------------------------------------------------------------
  884. TCipher __fastcall TSecureShell::FuncToSsh2Cipher(const void * Cipher) const
  885. {
  886. const ssh2_ciphers *CipherFuncs[] =
  887. {&ssh2_3des, &ssh2_des, &ssh2_aes, &ssh2_blowfish};
  888. const TCipher TCiphers[] = {cip3DES, cipDES, cipAES, cipBlowfish};
  889. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  890. TCipher Result = cipWarn;
  891. for (int C = 0; C < LENOF(TCiphers); C++)
  892. {
  893. for (int F = 0; F < CipherFuncs[C]->nciphers; F++)
  894. {
  895. if ((ssh2_cipher *)Cipher == CipherFuncs[C]->list[F])
  896. {
  897. Result = TCiphers[C];
  898. }
  899. }
  900. }
  901. assert(Result != cipWarn);
  902. return Result;
  903. }
  904. //---------------------------------------------------------------------------
  905. TCipher __fastcall TSecureShell::GetCSCipher()
  906. {
  907. assert(Active);
  908. if (FCSCipher == cipWarn)
  909. {
  910. if (SshVersion == 1)
  911. {
  912. FCSCipher = FuncToSsh1Cipher(get_cipher(FBackendHandle));
  913. }
  914. else
  915. {
  916. FCSCipher = FuncToSsh2Cipher(get_cscipher(FBackendHandle));
  917. }
  918. }
  919. return FCSCipher;
  920. }
  921. //---------------------------------------------------------------------------
  922. TCipher __fastcall TSecureShell::GetSCCipher()
  923. {
  924. CheckConnection();
  925. if (FSCCipher == cipWarn)
  926. {
  927. if (SshVersion == 1)
  928. {
  929. FSCCipher = FuncToSsh1Cipher(get_cipher(FBackendHandle));
  930. }
  931. else
  932. {
  933. FSCCipher = FuncToSsh2Cipher(get_sccipher(FBackendHandle));
  934. }
  935. }
  936. return FSCCipher;
  937. }
  938. //---------------------------------------------------------------------------
  939. void __fastcall TSecureShell::DoShowExtendedException(Exception * E)
  940. {
  941. DoHandleExtendedException(E);
  942. if (OnShowExtendedException != NULL)
  943. {
  944. OnShowExtendedException(this, E, NULL);
  945. }
  946. }
  947. //---------------------------------------------------------------------------
  948. void __fastcall TSecureShell::DoHandleExtendedException(Exception * E)
  949. {
  950. Log->AddException(E);
  951. }
  952. //---------------------------------------------------------------------------
  953. int __fastcall TSecureShell::DoQueryUser(const AnsiString Query,
  954. TStrings * MoreMessages, int Answers, const TQueryParams * Params, TQueryType Type)
  955. {
  956. LogEvent(FORMAT("Asking user:\n%s (%s)", (Query, (MoreMessages ? MoreMessages->CommaText : AnsiString() ))));
  957. int Answer = qaCancel;
  958. if (FOnQueryUser)
  959. {
  960. FOnQueryUser(this, Query, MoreMessages, Answers, Params, Answer, Type, NULL);
  961. }
  962. return Answer;
  963. }
  964. //---------------------------------------------------------------------------
  965. int __fastcall TSecureShell::DoQueryUser(const AnsiString Query,
  966. const AnsiString OtherMessage, int Answers, const TQueryParams * Params,
  967. TQueryType Type)
  968. {
  969. TStrings * MoreMessages = new TStringList();
  970. Integer Result;
  971. try {
  972. if (!OtherMessage.IsEmpty()) MoreMessages->Add(OtherMessage);
  973. Result = DoQueryUser(Query, MoreMessages, Answers, Params, Type);
  974. } __finally {
  975. delete MoreMessages;
  976. }
  977. return Result;
  978. }
  979. //---------------------------------------------------------------------------
  980. int __fastcall TSecureShell::DoQueryUser(const AnsiString Query,
  981. int Answers, const TQueryParams * Params, TQueryType Type)
  982. {
  983. return DoQueryUser(Query, "", Answers, Params, Type);
  984. }
  985. //---------------------------------------------------------------------------
  986. int __fastcall TSecureShell::DoQueryUser(const AnsiString Query,
  987. Exception * E, int Answers, const TQueryParams * Params, TQueryType Type)
  988. {
  989. int Result;
  990. TStrings * MoreMessages = new TStringList();
  991. try
  992. {
  993. if (E->InheritsFrom(__classid(ExtException)) &&
  994. ((ExtException*)E)->MoreMessages)
  995. {
  996. MoreMessages->Assign(((ExtException*)E)->MoreMessages);
  997. }
  998. if (!E->Message.IsEmpty() && !Query.IsEmpty()) MoreMessages->Insert(0, E->Message);
  999. Result = DoQueryUser(!Query.IsEmpty() ? Query : E->Message,
  1000. MoreMessages->Count ? MoreMessages : NULL,
  1001. Answers, Params, Type);
  1002. }
  1003. __finally
  1004. {
  1005. delete MoreMessages;
  1006. }
  1007. return Result;
  1008. }
  1009. //---------------------------------------------------------------------------
  1010. void __fastcall TSecureShell::VerifyHostKey(const AnsiString Host, int Port,
  1011. const AnsiString KeyType, const AnsiString KeyStr, const AnsiString Fingerprint)
  1012. {
  1013. GotHostKey();
  1014. int Result;
  1015. FHostKeyFingerprint = Fingerprint;
  1016. // Verify the key against the registry.
  1017. Result = verify_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1018. if (Result != 0)
  1019. {
  1020. TQueryParams Params;
  1021. Params.HelpKeyword = (Result == 1 ? HELP_UNKNOWN_KEY : HELP_DIFFERENT_KEY);
  1022. int R = DoQueryUser(
  1023. FMTLOAD((Result == 1 ? UNKNOWN_KEY2 : DIFFERENT_KEY2), (KeyType, Fingerprint)),
  1024. qaYes | qaNo | qaCancel, &Params, qtWarning);
  1025. switch (R) {
  1026. case qaYes:
  1027. store_host_key(Host.c_str(), Port, KeyType.c_str(), KeyStr.c_str());
  1028. break;
  1029. case qaCancel:
  1030. SSH_FATAL_ERROR(LoadStr(KEY_NOT_VERIFIED));
  1031. }
  1032. }
  1033. }
  1034. //---------------------------------------------------------------------------
  1035. void __fastcall TSecureShell::AskAlg(const AnsiString AlgType,
  1036. const AnsiString AlgName)
  1037. {
  1038. AnsiString Msg;
  1039. if (AlgType == "key-exchange algorithm")
  1040. {
  1041. Msg = FMTLOAD(KEX_BELOW_TRESHOLD, (AlgName));
  1042. }
  1043. else
  1044. {
  1045. int CipherType;
  1046. if (AlgType == "cipher")
  1047. {
  1048. CipherType = CIPHER_TYPE_BOTH;
  1049. }
  1050. else if (AlgType == "client-to-server cipher")
  1051. {
  1052. CipherType = CIPHER_TYPE_CS;
  1053. }
  1054. else if (AlgType == "server-to-client cipher")
  1055. {
  1056. CipherType = CIPHER_TYPE_SC;
  1057. }
  1058. else
  1059. {
  1060. assert(false);
  1061. }
  1062. Msg = FMTLOAD(CIPHER_BELOW_TRESHOLD, (LoadStr(CipherType), AlgName));
  1063. }
  1064. if (DoQueryUser(Msg, qaYes | qaNo, NULL, qtWarning) == qaNo)
  1065. {
  1066. Abort();
  1067. }
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TSecureShell::DoDisplayBanner(const AnsiString & Banner)
  1071. {
  1072. if ((OnDisplayBanner != NULL) &&
  1073. Configuration->ShowBanner(SessionData->SessionKey, Banner))
  1074. {
  1075. bool NeverShowAgain = false;
  1076. OnDisplayBanner(this, SessionData->SessionName, Banner, NeverShowAgain);
  1077. if (NeverShowAgain)
  1078. {
  1079. Configuration->NeverShowBanner(SessionData->SessionKey, Banner);
  1080. }
  1081. }
  1082. }
  1083. //---------------------------------------------------------------------------
  1084. void __fastcall TSecureShell::DisplayBanner(const AnsiString & Banner)
  1085. {
  1086. DoDisplayBanner(Banner);
  1087. }
  1088. //---------------------------------------------------------------------------
  1089. void __fastcall TSecureShell::OldKeyfileWarning()
  1090. {
  1091. DoQueryUser(LoadStr(OLD_KEY), qaOK, NULL, qtWarning);
  1092. }
  1093. //---------------------------------------------------------------------------
  1094. int __fastcall TSecureShell::GetStatus() const
  1095. {
  1096. return FStatus;
  1097. }
  1098. //---------------------------------------------------------------------------
  1099. void __fastcall TSecureShell::UpdateStatus(int Value)
  1100. {
  1101. if (FStatus != Value)
  1102. {
  1103. FStatus = Value;
  1104. if (FStatus > FReachedStatus) FReachedStatus = FStatus;
  1105. if (FOnUpdateStatus) FOnUpdateStatus(this);
  1106. }
  1107. }
  1108. //---------------------------------------------------------------------------
  1109. void __fastcall TSecureShell::SetUserObject(TObject * value)
  1110. {
  1111. if (UserObject != value)
  1112. {
  1113. if (UserObject)
  1114. {
  1115. delete UserObject;
  1116. }
  1117. FUserObject = value;
  1118. }
  1119. }
  1120. //=== TSessionLog -----------------------------------------------------------
  1121. const char *LogLineMarks = "<>!.*";
  1122. __fastcall TSessionLog::TSessionLog(TSecureShell * AOwner): TStringList()
  1123. {
  1124. FEnabled = true;
  1125. FOwner = AOwner;
  1126. FFile = NULL;
  1127. FLoggedLines = 0;
  1128. FTopIndex = -1;
  1129. FFileName = "";
  1130. FId = 0;
  1131. }
  1132. //---------------------------------------------------------------------------
  1133. __fastcall TSessionLog::~TSessionLog()
  1134. {
  1135. CloseLogFile();
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. AnsiString __fastcall TSessionLog::GetSessionName()
  1139. {
  1140. assert(FOwner != NULL);
  1141. assert(FOwner->SessionData != NULL);
  1142. return FOwner->SessionData->SessionName;
  1143. }
  1144. //---------------------------------------------------------------------------
  1145. void __fastcall TSessionLog::SetLine(Integer Index, AnsiString value)
  1146. {
  1147. Strings[Index] = AnsiString(Strings[Index - FTopIndex][1]) + value;
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. AnsiString __fastcall TSessionLog::GetLine(Integer Index)
  1151. {
  1152. return Strings[Index - FTopIndex].SubString(2, Strings[Index - FTopIndex].Length() - 1);
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. void __fastcall TSessionLog::SetType(Integer Index, TLogLineType value)
  1156. {
  1157. Strings[Index - FTopIndex][1] = LogLineMarks[value];
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. TLogLineType __fastcall TSessionLog::GetType(Integer Index)
  1161. {
  1162. int P = AnsiString(LogLineMarks).Pos(Strings[Index - FTopIndex][1]);
  1163. if (P)
  1164. {
  1165. return TLogLineType(P - 1);
  1166. }
  1167. else
  1168. {
  1169. assert(false);
  1170. return (TLogLineType)0;
  1171. }
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. void __fastcall TSessionLog::DoAdd(TLogLineType aType, AnsiString aLine)
  1175. {
  1176. assert(Configuration);
  1177. if (IsLogging())
  1178. {
  1179. try
  1180. {
  1181. if (Configuration->Logging)
  1182. {
  1183. BeginUpdate();
  1184. }
  1185. try
  1186. {
  1187. while (!aLine.IsEmpty())
  1188. {
  1189. AnsiString MarkStr = LogLineMarks[aType];
  1190. AnsiString NewStr = CutToChar(aLine, '\n', False);
  1191. if (Configuration->Logging)
  1192. {
  1193. TStringList::Add(MarkStr + NewStr);
  1194. FLoggedLines++;
  1195. }
  1196. DoAddLine(aType, NewStr);
  1197. if (Configuration->Logging && Configuration->LogToFile)
  1198. {
  1199. if (!FFile) OpenLogFile();
  1200. if (FFile)
  1201. {
  1202. AnsiString Timestamp = FormatDateTime(" yyyy-mm-dd hh:nn:ss.zzz ", Now());
  1203. fprintf((FILE *)FFile, "%s\n",
  1204. (MarkStr + Timestamp + NewStr).c_str());
  1205. }
  1206. }
  1207. }
  1208. if (Configuration->Logging)
  1209. {
  1210. if (FTopIndex < 0) FTopIndex = 0;
  1211. DeleteUnnecessary();
  1212. }
  1213. }
  1214. __finally
  1215. {
  1216. if (Configuration->Logging)
  1217. {
  1218. EndUpdate();
  1219. }
  1220. }
  1221. }
  1222. catch (Exception &E)
  1223. {
  1224. // We failed logging, turn it of and notify user.
  1225. Configuration->Logging = False;
  1226. try
  1227. {
  1228. throw ExtException(&E, LOG_ERROR);
  1229. }
  1230. catch (Exception &E)
  1231. {
  1232. FOwner->DoShowExtendedException(&E);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. void __fastcall TSessionLog::Add(TLogLineType aType, AnsiString aLine)
  1239. {
  1240. DoAdd(aType, aLine);
  1241. }
  1242. //---------------------------------------------------------------------------
  1243. void __fastcall TSessionLog::AddFromOtherLog(TObject * /*Sender*/,
  1244. TLogLineType aType, const AnsiString AddedLine)
  1245. {
  1246. DoAdd(aType, AddedLine);
  1247. }
  1248. //---------------------------------------------------------------------------
  1249. void __fastcall TSessionLog::AddException(Exception * E)
  1250. {
  1251. if (E)
  1252. {
  1253. Add(llException, ExceptionLogString(E));
  1254. }
  1255. }
  1256. //---------------------------------------------------------------------------
  1257. void __fastcall TSessionLog::SetConfiguration(TConfiguration * value)
  1258. {
  1259. if (FConfiguration != value)
  1260. {
  1261. FConfiguration = value;
  1262. ReflectSettings();
  1263. }
  1264. }
  1265. //---------------------------------------------------------------------------
  1266. void __fastcall TSessionLog::ReflectSettings()
  1267. {
  1268. // if logging to file was turned off or log file was change -> close current log file
  1269. if (FFile && (!LogToFile || (FFileName != LogFileName))) CloseLogFile();
  1270. // we used to open log file here, now it is posponed until first call to DoAdd()
  1271. // this allows TSecureShell to change the Id sooner.
  1272. DeleteUnnecessary();
  1273. }
  1274. //---------------------------------------------------------------------------
  1275. void __fastcall TSessionLog::SetEnabled(bool value)
  1276. {
  1277. if (FEnabled != value)
  1278. {
  1279. FEnabled = value;
  1280. ReflectSettings();
  1281. }
  1282. }
  1283. //---------------------------------------------------------------------------
  1284. Boolean __fastcall TSessionLog::GetLogToFile()
  1285. {
  1286. return Enabled && (Configuration != NULL) && Configuration->Logging &&
  1287. Configuration->LogToFile;
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TSessionLog::CloseLogFile()
  1291. {
  1292. if (FFile)
  1293. {
  1294. fclose((FILE *)FFile);
  1295. FFile = NULL;
  1296. }
  1297. FFileName = "";
  1298. }
  1299. //---------------------------------------------------------------------------
  1300. void TSessionLog::OpenLogFile()
  1301. {
  1302. if (LogToFile)
  1303. {
  1304. try
  1305. {
  1306. assert(!FFile);
  1307. assert(Configuration);
  1308. AnsiString NewFileName = LogFileName;
  1309. if (Id != 0)
  1310. {
  1311. NewFileName = FORMAT("%s%s.%.8x%s", (ExtractFilePath(NewFileName),
  1312. ExtractFileName(NewFileName), static_cast<int>(FId), ExtractFileExt(NewFileName)));
  1313. }
  1314. FFile = fopen(NewFileName.c_str(), (Configuration->LogFileAppend ? "a" : "w"));
  1315. if (FFile)
  1316. {
  1317. setvbuf((FILE *)FFile, NULL, _IONBF, BUFSIZ);
  1318. FFileName = NewFileName;
  1319. }
  1320. else
  1321. {
  1322. throw Exception(FMTLOAD(LOG_OPENERROR, (NewFileName)));
  1323. }
  1324. }
  1325. catch (Exception &E)
  1326. {
  1327. // We failed logging to file, turn it of and notify user.
  1328. FFileName = "";
  1329. Configuration->LogToFile = false;
  1330. try
  1331. {
  1332. throw ExtException(&E, LOG_ERROR);
  1333. }
  1334. catch (Exception &E)
  1335. {
  1336. FOwner->DoShowExtendedException(&E);
  1337. }
  1338. }
  1339. }
  1340. }
  1341. //---------------------------------------------------------------------------
  1342. void TSessionLog::DeleteUnnecessary()
  1343. {
  1344. BeginUpdate();
  1345. try
  1346. {
  1347. if (!Configuration || !Configuration->Logging)
  1348. {
  1349. Clear();
  1350. }
  1351. else
  1352. {
  1353. while (!Configuration->LogWindowComplete && (Count > Configuration->LogWindowLines))
  1354. {
  1355. Delete(0);
  1356. FTopIndex++;
  1357. }
  1358. }
  1359. }
  1360. __finally
  1361. {
  1362. EndUpdate();
  1363. }
  1364. }
  1365. //---------------------------------------------------------------------------
  1366. TColor __fastcall TSessionLog::GetColor(int Index)
  1367. {
  1368. return LogLineColors[Type[Index]];
  1369. }
  1370. //---------------------------------------------------------------------------
  1371. void __fastcall TSessionLog::DoAddLine(TLogLineType Type, const AnsiString AddedLine)
  1372. {
  1373. if (FOnAddLine)
  1374. {
  1375. FOnAddLine(this, Type, AddedLine);
  1376. }
  1377. }
  1378. //---------------------------------------------------------------------------
  1379. void __fastcall TSessionLog::AddStartupInfo()
  1380. {
  1381. assert(FOwner != NULL);
  1382. TSessionData * Data = FOwner->SessionData;
  1383. assert(Data != NULL);
  1384. assert(Configuration);
  1385. if (Configuration->Logging || FOnAddLine)
  1386. {
  1387. BeginUpdate();
  1388. try
  1389. {
  1390. #define ADF(S, F) Add(llMessage, FORMAT(S, F));
  1391. AddSeparator();
  1392. ADF("WinSCP %s (OS %s)", (Configuration->VersionStr, Configuration->OSVersionStr));
  1393. ADF("Login time: %s", (FormatDateTime("dddddd tt", Now())));
  1394. AddSeparator();
  1395. ADF("Session name: %s", (Data->SessionName));
  1396. ADF("Host name: %s (Port: %d)", (Data->HostName, Data->PortNumber));
  1397. ADF("User name: %s (Password: %s, Key file: %s)",
  1398. (Data->UserName, BooleanToEngStr(!Data->Password.IsEmpty()),
  1399. BooleanToEngStr(!Data->PublicKeyFile.IsEmpty())))
  1400. ADF("Transfer Protocol: %s", (Data->FSProtocolStr));
  1401. ADF("SSH protocol version: %s; Compression: %s",
  1402. (Data->SshProtStr, BooleanToEngStr(Data->Compression)));
  1403. ADF("Agent forwarding: %s; TIS/CryptoCard: %s; KI: %s; GSSAPI: %s",
  1404. (BooleanToEngStr(Data->AgentFwd), BooleanToEngStr(Data->AuthTIS),
  1405. BooleanToEngStr(Data->AuthKI), BooleanToEngStr(Data->AuthGSSAPI)));
  1406. ADF("Ciphers: %s; Ssh2DES: %s",
  1407. (Data->CipherList, BooleanToEngStr(Data->Ssh2DES)));
  1408. char * PingTypes = "-NC";
  1409. ADF("Ping type: %s, Ping interval: %d sec; Timeout: %d sec",
  1410. (AnsiString(PingTypes[Data->PingType]), Data->PingInterval, Data->Timeout));
  1411. AnsiString Bugs;
  1412. char const * BugFlags = "A+-";
  1413. for (int Index = 0; Index < BUG_COUNT; Index++)
  1414. {
  1415. Bugs += AnsiString(BugFlags[Data->Bug[(TSshBug)Index]])+(Index<BUG_COUNT-1?",":"");
  1416. }
  1417. ADF("SSH Bugs: %s", (Bugs));
  1418. Bugs = "";
  1419. for (int Index = 0; Index < SFTP_BUG_COUNT; Index++)
  1420. {
  1421. Bugs += AnsiString(BugFlags[Data->SFTPBug[(TSftpBug)Index]])+(Index<SFTP_BUG_COUNT-1?",":"");
  1422. }
  1423. ADF("SFTP Bugs: %s", (Bugs));
  1424. ADF("Proxy: %s", (ProxyMethodList[Data->ProxyMethod]));
  1425. if (Data->ProxyMethod != pmNone)
  1426. {
  1427. ADF("HostName: %s (Port: %d); Username: %s; Passwd: %s",
  1428. (Data->ProxyHost, Data->ProxyPort,
  1429. Data->ProxyUsername, BooleanToEngStr(!Data->ProxyPassword.IsEmpty())));
  1430. if (Data->ProxyMethod == pmTelnet)
  1431. {
  1432. ADF("Telnet command: %s", (Data->ProxyTelnetCommand));
  1433. }
  1434. }
  1435. ADF("Return code variable: %s; Lookup user groups: %s",
  1436. ((Data->DetectReturnVar ? AnsiString("Autodetect") : Data->ReturnVar),
  1437. BooleanToEngStr(Data->LookupUserGroups)));
  1438. ADF("Shell: %s, EOL: %d", ((Data->Shell.IsEmpty()? AnsiString("default") : Data->Shell), Data->EOLType));
  1439. ADF("Local directory: %s, Remote directory: %s, Update: %s, Cache: %s",
  1440. ((Data->LocalDirectory.IsEmpty() ? AnsiString("default") : Data->LocalDirectory),
  1441. (Data->RemoteDirectory.IsEmpty() ? AnsiString("home") : Data->RemoteDirectory),
  1442. BooleanToEngStr(Data->UpdateDirectories),
  1443. BooleanToEngStr(Data->CacheDirectories)));
  1444. ADF("Cache directory changes: %s, Permanent: %s",
  1445. (BooleanToEngStr(Data->CacheDirectoryChanges),
  1446. BooleanToEngStr(Data->PreserveDirectoryChanges)));
  1447. ADF("Clear aliases: %s, Unset nat.vars: %s, Resolve symlinks: %s",
  1448. (BooleanToEngStr(Data->ClearAliases), BooleanToEngStr(Data->UnsetNationalVars),
  1449. BooleanToEngStr(Data->ResolveSymlinks)));
  1450. ADF("Alias LS: %s, Ign LS warn: %s, Scp1 Comp: %s",
  1451. (BooleanToEngStr(Data->AliasGroupList),
  1452. BooleanToEngStr(Data->IgnoreLsWarnings),
  1453. BooleanToEngStr(Data->Scp1Compatibility)));
  1454. AddSeparator();
  1455. #undef ADF
  1456. }
  1457. __finally
  1458. {
  1459. EndUpdate();
  1460. }
  1461. }
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. void __fastcall TSessionLog::AddSeparator()
  1465. {
  1466. Add(llMessage, "--------------------------------------------------------------------------");
  1467. }
  1468. //---------------------------------------------------------------------------
  1469. int __fastcall TSessionLog::GetIndexes(int Index)
  1470. {
  1471. assert((Index >= 0) && (Index < Count));
  1472. int Result = TopIndex + Index;
  1473. assert((Result >= 0) && (Result < LoggedLines));
  1474. return Result;
  1475. }
  1476. //---------------------------------------------------------------------------
  1477. int __fastcall TSessionLog::GetBottomIndex()
  1478. {
  1479. return (Count ? Indexes[Count-1] : -1);
  1480. }
  1481. //---------------------------------------------------------------------------
  1482. AnsiString __fastcall TSessionLog::GetLogFileName()
  1483. {
  1484. assert(Configuration);
  1485. AnsiString Result = StripPathQuotes(Configuration->LogFileName);
  1486. return Result;
  1487. }
  1488. //---------------------------------------------------------------------------
  1489. Boolean __fastcall TSessionLog::GetLoggingToFile()
  1490. {
  1491. return
  1492. (Configuration && Configuration->Logging && Configuration->LogToFile && FFile);
  1493. }
  1494. //---------------------------------------------------------------------------
  1495. void __fastcall TSessionLog::Clear()
  1496. {
  1497. FTopIndex += Count;
  1498. TStringList::Clear();
  1499. }