SecureShell.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "Common.h"
  5. #include "PuttyIntf.h"
  6. #include "Exceptions.h"
  7. #include "Interface.h"
  8. #include "SecureShell.h"
  9. #include "TextsCore.h"
  10. #include "HelpCore.h"
  11. #include "CoreMain.h"
  12. #include <StrUtils.hpp>
  13. #ifndef AUTO_WINSOCK
  14. #include <winsock2.h>
  15. #endif
  16. //---------------------------------------------------------------------------
  17. #pragma package(smart_init)
  18. //---------------------------------------------------------------------------
  19. #define MAX_BUFSIZE 32768
  20. //---------------------------------------------------------------------------
  21. struct TPuttyTranslation
  22. {
  23. const wchar_t * Original;
  24. int Translation;
  25. UnicodeString HelpKeyword;
  26. };
  27. //---------------------------------------------------------------------------
  28. char * __fastcall AnsiStrNew(const wchar_t * S)
  29. {
  30. AnsiString Buf = S;
  31. char * Result = new char[Buf.Length() + 1];
  32. memcpy(Result, Buf.c_str(), Buf.Length() + 1);
  33. return Result;
  34. }
  35. //---------------------------------------------------------------------------
  36. void __fastcall AnsiStrDispose(char * S)
  37. {
  38. delete [] S;
  39. }
  40. //---------------------------------------------------------------------------
  41. __fastcall TSecureShell::TSecureShell(TSessionUI* UI,
  42. TSessionData * SessionData, TSessionLog * Log, TConfiguration * Configuration)
  43. {
  44. FUI = UI;
  45. FSessionData = SessionData;
  46. FLog = Log;
  47. FConfiguration = Configuration;
  48. FActive = false;
  49. FWaiting = 0;
  50. FOpened = false;
  51. FSshImplementation = sshiUnknown;
  52. OutPtr = NULL;
  53. Pending = NULL;
  54. FBackendHandle = NULL;
  55. ResetConnection();
  56. FOnCaptureOutput = NULL;
  57. FOnReceive = NULL;
  58. FSocket = INVALID_SOCKET;
  59. FSocketEvent = CreateEvent(NULL, false, false, NULL);
  60. FFrozen = false;
  61. FSimple = false;
  62. FCollectPrivateKeyUsage = false;
  63. FWaitingForData = 0;
  64. }
  65. //---------------------------------------------------------------------------
  66. __fastcall TSecureShell::~TSecureShell()
  67. {
  68. assert(FWaiting == 0);
  69. Active = false;
  70. ResetConnection();
  71. CloseHandle(FSocketEvent);
  72. }
  73. //---------------------------------------------------------------------------
  74. void __fastcall TSecureShell::ResetConnection()
  75. {
  76. FreeBackend();
  77. ClearStdError();
  78. PendLen = 0;
  79. PendSize = 0;
  80. sfree(Pending);
  81. Pending = NULL;
  82. FCWriteTemp = L"";
  83. ResetSessionInfo();
  84. FAuthenticating = false;
  85. FAuthenticated = false;
  86. FStoredPasswordTried = false;
  87. FStoredPasswordTriedForKI = false;
  88. FStoredPassphraseTried = false;
  89. }
  90. //---------------------------------------------------------------------------
  91. void __fastcall TSecureShell::ResetSessionInfo()
  92. {
  93. FSessionInfoValid = false;
  94. FMaxPacketSize = NULL;
  95. }
  96. //---------------------------------------------------------------------------
  97. inline void __fastcall TSecureShell::UpdateSessionInfo()
  98. {
  99. if (!FSessionInfoValid)
  100. {
  101. FSshVersion = get_ssh_version(FBackendHandle);
  102. FSessionInfo.ProtocolBaseName = L"SSH";
  103. FSessionInfo.ProtocolName =
  104. FORMAT(L"%s-%d", (FSessionInfo.ProtocolBaseName, get_ssh_version(FBackendHandle)));
  105. FSessionInfo.SecurityProtocolName = FSessionInfo.ProtocolName;
  106. FSessionInfo.CSCompression =
  107. FuncToCompression(FSshVersion, get_cscomp(FBackendHandle));
  108. FSessionInfo.SCCompression =
  109. FuncToCompression(FSshVersion, get_sccomp(FBackendHandle));
  110. if (FSshVersion == 1)
  111. {
  112. FSessionInfo.CSCipher = CipherNames[FuncToSsh1Cipher(get_cipher(FBackendHandle))];
  113. FSessionInfo.SCCipher = CipherNames[FuncToSsh1Cipher(get_cipher(FBackendHandle))];
  114. }
  115. else
  116. {
  117. FSessionInfo.CSCipher = CipherNames[FuncToSsh2Cipher(get_cscipher(FBackendHandle))];
  118. FSessionInfo.SCCipher = CipherNames[FuncToSsh2Cipher(get_sccipher(FBackendHandle))];
  119. }
  120. FSessionInfoValid = true;
  121. }
  122. }
  123. //---------------------------------------------------------------------------
  124. const TSessionInfo & __fastcall TSecureShell::GetSessionInfo()
  125. {
  126. if (!FSessionInfoValid)
  127. {
  128. UpdateSessionInfo();
  129. }
  130. return FSessionInfo;
  131. }
  132. //---------------------------------------------------------------------
  133. Conf * __fastcall TSecureShell::StoreToConfig(TSessionData * Data, bool Simple)
  134. {
  135. Conf * conf = conf_new();
  136. assert((asOn == FORCE_ON) && (asOff == FORCE_OFF) && (asAuto == AUTO));
  137. #define CONF_ssh_cipherlist_MAX CIPHER_MAX
  138. #define CONF_DEF_INT_NONE(KEY) conf_set_int(conf, KEY, 0);
  139. #define CONF_DEF_STR_NONE(KEY) conf_set_str(conf, KEY, "");
  140. // noop, used only for these and we set the first three explicitly below and latter two are not used in our code
  141. #define CONF_DEF_INT_INT(KEY) assert((KEY == CONF_ssh_cipherlist) || (KEY == CONF_ssh_kexlist) || (KEY == CONF_ssh_gsslist) || (KEY == CONF_colours) || (KEY == CONF_wordness));
  142. // noop, used only for these three and they all can handle undef value
  143. #define CONF_DEF_STR_STR(KEY) assert((KEY == CONF_ttymodes) || (KEY == CONF_portfwd) || (KEY == CONF_environmt));
  144. // noop, not used in our code
  145. #define CONF_DEF_FONT_NONE(KEY) assert((KEY == CONF_font) || (KEY == CONF_boldfont) || (KEY == CONF_widefont) || (KEY == CONF_wideboldfont));
  146. #define CONF_DEF_FILENAME_NONE(KEY) \
  147. { \
  148. Filename * filename = filename_from_str(""); \
  149. conf_set_filename(conf, KEY, filename); \
  150. filename_free(filename); \
  151. }
  152. #define CONF_SET_DEFAULT(VALTYPE, KEYTYPE, KEYWORD) CONF_DEF_ ## VALTYPE ## _ ## KEYTYPE(CONF_ ## KEYWORD);
  153. CONFIG_OPTIONS(CONF_SET_DEFAULT);
  154. #undef CONF_SET_DEFAULT
  155. #undef CONF_DEF_FILENAME_NONE
  156. #undef CONF_DEF_FONT_NONE
  157. #undef CONF_DEF_STR_STR
  158. #undef CONF_DEF_INT_INT
  159. #undef CONF_DEF_STR_NONE
  160. #undef CONF_DEF_INT_NONE
  161. // user-configurable settings
  162. conf_set_str(conf, CONF_host, AnsiString(Data->HostNameExpanded).c_str());
  163. conf_set_str(conf, CONF_username, AnsiString(Data->UserNameExpanded).c_str());
  164. conf_set_int(conf, CONF_port, Data->PortNumber);
  165. conf_set_int(conf, CONF_protocol, PROT_SSH);
  166. // always set 0, as we will handle keepalives ourselves to avoid
  167. // multi-threaded issues in putty timer list
  168. conf_set_int(conf, CONF_ping_interval, 0);
  169. conf_set_int(conf, CONF_compression, Data->Compression);
  170. conf_set_int(conf, CONF_tryagent, Data->TryAgent);
  171. conf_set_int(conf, CONF_agentfwd, Data->AgentFwd);
  172. conf_set_int(conf, CONF_addressfamily, Data->AddressFamily);
  173. conf_set_str(conf, CONF_ssh_rekey_data, AnsiString(Data->RekeyData).c_str());
  174. conf_set_int(conf, CONF_ssh_rekey_time, Data->RekeyTime);
  175. for (int c = 0; c < CIPHER_COUNT; c++)
  176. {
  177. int pcipher;
  178. switch (Data->Cipher[c]) {
  179. case cipWarn: pcipher = CIPHER_WARN; break;
  180. case cip3DES: pcipher = CIPHER_3DES; break;
  181. case cipBlowfish: pcipher = CIPHER_BLOWFISH; break;
  182. case cipAES: pcipher = CIPHER_AES; break;
  183. case cipDES: pcipher = CIPHER_DES; break;
  184. case cipArcfour: pcipher = CIPHER_ARCFOUR; break;
  185. default: FAIL;
  186. }
  187. conf_set_int_int(conf, CONF_ssh_cipherlist, c, pcipher);
  188. }
  189. for (int k = 0; k < KEX_COUNT; k++)
  190. {
  191. int pkex;
  192. switch (Data->Kex[k]) {
  193. case kexWarn: pkex = KEX_WARN; break;
  194. case kexDHGroup1: pkex = KEX_DHGROUP1; break;
  195. case kexDHGroup14: pkex = KEX_DHGROUP14; break;
  196. case kexDHGEx: pkex = KEX_DHGEX; break;
  197. case kexRSA: pkex = KEX_RSA; break;
  198. default: FAIL;
  199. }
  200. conf_set_int_int(conf, CONF_ssh_kexlist, k, pkex);
  201. }
  202. UnicodeString SPublicKeyFile = Data->PublicKeyFile;
  203. if (SPublicKeyFile.IsEmpty()) SPublicKeyFile = Configuration->DefaultKeyFile;
  204. SPublicKeyFile = StripPathQuotes(ExpandEnvironmentVariables(SPublicKeyFile));
  205. Filename * KeyFileFileName = filename_from_str(UTF8String(SPublicKeyFile).c_str());
  206. conf_set_filename(conf, CONF_keyfile, KeyFileFileName);
  207. filename_free(KeyFileFileName);
  208. conf_set_int(conf, CONF_sshprot, Data->SshProt);
  209. conf_set_int(conf, CONF_ssh2_des_cbc, Data->Ssh2DES);
  210. conf_set_int(conf, CONF_ssh_no_userauth, Data->SshNoUserAuth);
  211. conf_set_int(conf, CONF_try_tis_auth, Data->AuthTIS);
  212. conf_set_int(conf, CONF_try_ki_auth, Data->AuthKI);
  213. conf_set_int(conf, CONF_try_gssapi_auth, Data->AuthGSSAPI);
  214. conf_set_int(conf, CONF_gssapifwd, Data->GSSAPIFwdTGT);
  215. conf_set_int(conf, CONF_change_username, Data->ChangeUsername);
  216. conf_set_int(conf, CONF_proxy_type, Data->ProxyMethod);
  217. conf_set_str(conf, CONF_proxy_host, AnsiString(Data->ProxyHost).c_str());
  218. conf_set_int(conf, CONF_proxy_port, Data->ProxyPort);
  219. conf_set_str(conf, CONF_proxy_username, AnsiString(Data->ProxyUsername).c_str());
  220. conf_set_str(conf, CONF_proxy_password, AnsiString(Data->ProxyPassword).c_str());
  221. if (Data->ProxyMethod == pmCmd)
  222. {
  223. conf_set_str(conf, CONF_proxy_telnet_command, AnsiString(Data->ProxyLocalCommand).c_str());
  224. }
  225. else
  226. {
  227. conf_set_str(conf, CONF_proxy_telnet_command, AnsiString(Data->ProxyTelnetCommand).c_str());
  228. }
  229. conf_set_int(conf, CONF_proxy_dns, Data->ProxyDNS);
  230. conf_set_int(conf, CONF_even_proxy_localhost, Data->ProxyLocalhost);
  231. conf_set_int(conf, CONF_sshbug_ignore1, Data->Bug[sbIgnore1]);
  232. conf_set_int(conf, CONF_sshbug_plainpw1, Data->Bug[sbPlainPW1]);
  233. conf_set_int(conf, CONF_sshbug_rsa1, Data->Bug[sbRSA1]);
  234. conf_set_int(conf, CONF_sshbug_hmac2, Data->Bug[sbHMAC2]);
  235. conf_set_int(conf, CONF_sshbug_derivekey2, Data->Bug[sbDeriveKey2]);
  236. conf_set_int(conf, CONF_sshbug_rsapad2, Data->Bug[sbRSAPad2]);
  237. conf_set_int(conf, CONF_sshbug_rekey2, Data->Bug[sbRekey2]);
  238. conf_set_int(conf, CONF_sshbug_pksessid2, Data->Bug[sbPKSessID2]);
  239. conf_set_int(conf, CONF_sshbug_maxpkt2, Data->Bug[sbMaxPkt2]);
  240. conf_set_int(conf, CONF_sshbug_ignore2, Data->Bug[sbIgnore2]);
  241. conf_set_int(conf, CONF_sshbug_winadj, Data->Bug[sbWinAdj]);
  242. if (!Data->TunnelPortFwd.IsEmpty())
  243. {
  244. assert(!Simple);
  245. UnicodeString TunnelPortFwd = Data->TunnelPortFwd;
  246. while (!TunnelPortFwd.IsEmpty())
  247. {
  248. UnicodeString Buf = CutToChar(TunnelPortFwd, L',', true);
  249. AnsiString Key = AnsiString(CutToChar(Buf, L'\t', true));
  250. AnsiString Value = AnsiString(Buf);
  251. conf_set_str_str(conf, CONF_portfwd, Key.c_str(), Value.c_str());
  252. }
  253. // when setting up a tunnel, do not open shell/sftp
  254. conf_set_int(conf, CONF_ssh_no_shell, TRUE);
  255. }
  256. else
  257. {
  258. assert(Simple);
  259. conf_set_int(conf, CONF_ssh_simple, Data->SshSimple && Simple);
  260. if (Data->FSProtocol == fsSCPonly)
  261. {
  262. conf_set_int(conf, CONF_ssh_subsys, FALSE);
  263. if (Data->Shell.IsEmpty())
  264. {
  265. // Following forces Putty to open default shell
  266. // see ssh.c: do_ssh2_authconn() and ssh1_protocol()
  267. conf_set_str(conf, CONF_remote_cmd, "");
  268. }
  269. else
  270. {
  271. conf_set_str(conf, CONF_remote_cmd, AnsiString(Data->Shell).c_str());
  272. }
  273. }
  274. else
  275. {
  276. if (Data->SftpServer.IsEmpty())
  277. {
  278. conf_set_int(conf, CONF_ssh_subsys, TRUE);
  279. conf_set_str(conf, CONF_remote_cmd, "sftp");
  280. }
  281. else
  282. {
  283. conf_set_int(conf, CONF_ssh_subsys, FALSE);
  284. conf_set_str(conf, CONF_remote_cmd, AnsiString(Data->SftpServer).c_str());
  285. }
  286. if (Data->FSProtocol != fsSFTPonly)
  287. {
  288. conf_set_int(conf, CONF_ssh_subsys2, FALSE);
  289. if (Data->Shell.IsEmpty())
  290. {
  291. // Following forces Putty to open default shell
  292. // see ssh.c: do_ssh2_authconn() and ssh1_protocol()
  293. conf_set_str(conf, CONF_remote_cmd2, "");
  294. // PuTTY ignores CONF_remote_cmd2 set to "",
  295. // so we have to enforce it
  296. // (CONF_force_remote_cmd2 is our config option)
  297. conf_set_int(conf, CONF_force_remote_cmd2, 1);
  298. }
  299. else
  300. {
  301. conf_set_str(conf, CONF_remote_cmd2, AnsiString(Data->Shell).c_str());
  302. }
  303. }
  304. if ((Data->FSProtocol == fsSFTPonly) && Data->SftpServer.IsEmpty())
  305. {
  306. // see psftp_connect() from psftp.c
  307. conf_set_int(conf, CONF_ssh_subsys2, FALSE);
  308. conf_set_str(conf, CONF_remote_cmd2,
  309. "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n"
  310. "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n"
  311. "exec sftp-server");
  312. }
  313. }
  314. }
  315. conf_set_int(conf, CONF_connect_timeout, Data->Timeout * MSecsPerSec);
  316. conf_set_int(conf, CONF_sndbuf, Data->SendBuf);
  317. // permanent settings
  318. conf_set_int(conf, CONF_nopty, TRUE);
  319. conf_set_int(conf, CONF_tcp_keepalives, 0);
  320. conf_set_int(conf, CONF_ssh_show_banner, TRUE);
  321. for (int Index = 0; Index < ngsslibs; Index++)
  322. {
  323. conf_set_int_int(conf, CONF_ssh_gsslist, Index, gsslibkeywords[Index].v);
  324. }
  325. return conf;
  326. }
  327. //---------------------------------------------------------------------------
  328. void __fastcall TSecureShell::Open()
  329. {
  330. FBackend = &ssh_backend;
  331. ResetConnection();
  332. FAuthenticating = false;
  333. FAuthenticated = false;
  334. // do not use UTF-8 until decided otherwise (see TSCPFileSystem::DetectUtf())
  335. FUtfStrings = false;
  336. Active = false;
  337. FAuthenticationLog = L"";
  338. FNoConnectionResponse = false;
  339. FUI->Information(LoadStr(STATUS_LOOKUPHOST), true);
  340. try
  341. {
  342. char * RealHost;
  343. FreeBackend(); // in case we are reconnecting
  344. const char * InitError;
  345. Conf * conf = StoreToConfig(FSessionData, Simple);
  346. try
  347. {
  348. InitError = FBackend->init(this, &FBackendHandle, conf,
  349. AnsiString(FSessionData->HostNameExpanded).c_str(), FSessionData->PortNumber, &RealHost, 0,
  350. conf_get_int(conf, CONF_tcp_keepalives));
  351. }
  352. __finally
  353. {
  354. conf_free(conf);
  355. }
  356. sfree(RealHost);
  357. if (InitError)
  358. {
  359. PuttyFatalError(InitError);
  360. }
  361. FUI->Information(LoadStr(STATUS_CONNECT), true);
  362. Init();
  363. CheckConnection(CONNECTION_FAILED);
  364. }
  365. catch (Exception & E)
  366. {
  367. if (FNoConnectionResponse && TryFtp())
  368. {
  369. Configuration->Usage->Inc(L"ProtocolSuggestions");
  370. // HELP_FTP_SUGGESTION won't be used as all errors that set
  371. // FNoConnectionResponse have already their own help keyword
  372. FUI->FatalError(&E, LoadStr(FTP_SUGGESTION), HELP_FTP_SUGGESTION);
  373. }
  374. else
  375. {
  376. throw;
  377. }
  378. }
  379. FLastDataSent = Now();
  380. FSessionInfo.LoginTime = Now();
  381. FAuthenticating = false;
  382. FAuthenticated = true;
  383. FUI->Information(LoadStr(STATUS_AUTHENTICATED), true);
  384. ResetSessionInfo();
  385. assert(!FSessionInfo.SshImplementation.IsEmpty());
  386. FOpened = true;
  387. UnicodeString SshImplementation = GetSessionInfo().SshImplementation;
  388. if (// e.g. "OpenSSH_5.3"
  389. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  390. // Sun SSH is based on OpenSSH (suffers the same bugs)
  391. (SshImplementation.Pos(L"Sun_SSH") == 1))
  392. {
  393. FSshImplementation = sshiOpenSSH;
  394. }
  395. // e.g. "mod_sftp/0.9.8"
  396. else if (SshImplementation.Pos(L"mod_sftp") == 1)
  397. {
  398. FSshImplementation = sshiProFTPD;
  399. }
  400. // e.g. "5.25 FlowSsh: Bitvise SSH Server (WinSSHD) 6.07: free only for personal non-commercial use"
  401. else if (SshImplementation.Pos(L"FlowSsh") > 0)
  402. {
  403. FSshImplementation = sshiBitvise;
  404. }
  405. // e.g. "srtSSHServer_10.00"
  406. else if (ContainsText(SshImplementation, L"srtSSHServer"))
  407. {
  408. FSshImplementation = sshiTitan;
  409. }
  410. else
  411. {
  412. FSshImplementation = sshiUnknown;
  413. }
  414. }
  415. //---------------------------------------------------------------------------
  416. bool __fastcall TSecureShell::TryFtp()
  417. {
  418. bool Result;
  419. if (!FConfiguration->TryFtpWhenSshFails)
  420. {
  421. Result = false;
  422. }
  423. else
  424. {
  425. if (((FSessionData->FSProtocol != fsSFTP) && (FSessionData->FSProtocol != fsSFTPonly)) ||
  426. (FSessionData->PortNumber != SshPortNumber) ||
  427. FSessionData->Tunnel || (FSessionData->ProxyMethod != ::pmNone))
  428. {
  429. LogEvent(L"Using non-standard protocol or port, tunnel or proxy, will not knock FTP port.");
  430. Result = false;
  431. }
  432. else
  433. {
  434. LogEvent(L"Knocking FTP port.");
  435. SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
  436. Result = (Socket != INVALID_SOCKET);
  437. if (Result)
  438. {
  439. LPHOSTENT HostEntry = gethostbyname(AnsiString(FSessionData->HostNameExpanded).c_str());
  440. Result = (HostEntry != NULL);
  441. if (Result)
  442. {
  443. SOCKADDR_IN Address;
  444. memset(&Address, 0, sizeof(Address));
  445. Address.sin_family = AF_INET;
  446. int Port = FtpPortNumber;
  447. Address.sin_port = htons(static_cast<short>(Port));
  448. Address.sin_addr.s_addr = *((unsigned long *)*HostEntry->h_addr_list);
  449. HANDLE Event = CreateEvent(NULL, false, false, NULL);
  450. Result = (WSAEventSelect(Socket, (WSAEVENT)Event, FD_CONNECT | FD_CLOSE) != SOCKET_ERROR);
  451. if (Result)
  452. {
  453. Result =
  454. (connect(Socket, reinterpret_cast<sockaddr *>(&Address), sizeof(Address)) != SOCKET_ERROR) ||
  455. (WSAGetLastError() == WSAEWOULDBLOCK);
  456. if (Result)
  457. {
  458. Result = (WaitForSingleObject(Event, 2000) == WAIT_OBJECT_0);
  459. }
  460. }
  461. CloseHandle(Event);
  462. }
  463. closesocket(Socket);
  464. }
  465. if (Result)
  466. {
  467. LogEvent(L"FTP port opened, will suggest using FTP protocol.");
  468. }
  469. else
  470. {
  471. LogEvent(L"FTP port did not open.");
  472. }
  473. }
  474. }
  475. return Result;
  476. }
  477. //---------------------------------------------------------------------------
  478. void __fastcall TSecureShell::Init()
  479. {
  480. try
  481. {
  482. try
  483. {
  484. // Recent pscp checks FBackend->exitcode(FBackendHandle) in the loop
  485. // (see comment in putty revision 8110)
  486. // It seems that we do not need to do it.
  487. while (!get_ssh_state_session(FBackendHandle))
  488. {
  489. if (Configuration->ActualLogProtocol >= 1)
  490. {
  491. LogEvent(L"Waiting for the server to continue with the initialization");
  492. }
  493. WaitForData();
  494. }
  495. // unless this is tunnel session, it must be safe to send now
  496. assert(FBackend->sendok(FBackendHandle) || !FSessionData->TunnelPortFwd.IsEmpty());
  497. }
  498. catch(Exception & E)
  499. {
  500. if (FAuthenticating && !FAuthenticationLog.IsEmpty())
  501. {
  502. FUI->FatalError(&E, FMTLOAD(AUTHENTICATION_LOG, (FAuthenticationLog)));
  503. }
  504. else
  505. {
  506. throw;
  507. }
  508. }
  509. }
  510. catch(Exception & E)
  511. {
  512. if (FAuthenticating)
  513. {
  514. FUI->FatalError(&E, LoadStr(AUTHENTICATION_FAILED));
  515. }
  516. else
  517. {
  518. throw;
  519. }
  520. }
  521. }
  522. //---------------------------------------------------------------------------
  523. UnicodeString __fastcall TSecureShell::ConvertFromPutty(const char * Str, int Length)
  524. {
  525. int BomLength = strlen(MPEXT_BOM);
  526. if ((Length >= BomLength) &&
  527. (strncmp(Str, MPEXT_BOM, BomLength) == 0))
  528. {
  529. return UnicodeString(UTF8String(Str + BomLength, Length - BomLength));
  530. }
  531. else
  532. {
  533. return UnicodeString(AnsiString(Str, Length));
  534. }
  535. }
  536. //---------------------------------------------------------------------------
  537. void __fastcall TSecureShell::PuttyLogEvent(const char * AStr)
  538. {
  539. UnicodeString Str = ConvertFromPutty(AStr, strlen(AStr));
  540. #define SERVER_VERSION_MSG L"Server version: "
  541. // Gross hack
  542. if (Str.Pos(SERVER_VERSION_MSG) == 1)
  543. {
  544. FSessionInfo.SshVersionString = Str.SubString(wcslen(SERVER_VERSION_MSG) + 1,
  545. Str.Length() - wcslen(SERVER_VERSION_MSG));
  546. const wchar_t * Ptr = wcschr(FSessionInfo.SshVersionString.c_str(), L'-');
  547. if (Ptr != NULL)
  548. {
  549. Ptr = wcschr(Ptr + 1, L'-');
  550. }
  551. FSessionInfo.SshImplementation = (Ptr != NULL) ? Ptr + 1 : L"";
  552. }
  553. #define FORWARDING_FAILURE_MSG L"Forwarded connection refused by server: "
  554. else if (Str.Pos(FORWARDING_FAILURE_MSG) == 1)
  555. {
  556. FLastTunnelError = Str.SubString(wcslen(FORWARDING_FAILURE_MSG) + 1,
  557. Str.Length() - wcslen(FORWARDING_FAILURE_MSG));
  558. static const TPuttyTranslation Translation[] = {
  559. { L"Administratively prohibited [%]", PFWD_TRANSL_ADMIN },
  560. { L"Connect failed [%]", PFWD_TRANSL_CONNECT },
  561. };
  562. TranslatePuttyMessage(Translation, LENOF(Translation), FLastTunnelError);
  563. }
  564. LogEvent(Str);
  565. }
  566. //---------------------------------------------------------------------------
  567. bool __fastcall TSecureShell::PromptUser(bool /*ToServer*/,
  568. UnicodeString AName, bool /*NameRequired*/,
  569. UnicodeString Instructions, bool InstructionsRequired,
  570. TStrings * Prompts, TStrings * Results)
  571. {
  572. // there can be zero prompts!
  573. assert(Results->Count == Prompts->Count);
  574. TPromptKind PromptKind;
  575. // beware of changing order
  576. static const TPuttyTranslation NameTranslation[] = {
  577. { L"SSH login name", USERNAME_TITLE },
  578. { L"SSH key passphrase", PASSPHRASE_TITLE },
  579. { L"SSH TIS authentication", SERVER_PROMPT_TITLE },
  580. { L"SSH CryptoCard authentication", SERVER_PROMPT_TITLE },
  581. { L"SSH server: %", SERVER_PROMPT_TITLE2 },
  582. { L"SSH server authentication", SERVER_PROMPT_TITLE },
  583. { L"SSH password", PASSWORD_TITLE },
  584. { L"New SSH password", NEW_PASSWORD_TITLE },
  585. };
  586. UnicodeString Name = AName;
  587. int Index = TranslatePuttyMessage(NameTranslation, LENOF(NameTranslation), Name);
  588. const TPuttyTranslation * InstructionTranslation = NULL;
  589. const TPuttyTranslation * PromptTranslation = NULL;
  590. size_t PromptTranslationCount = 1;
  591. UnicodeString PromptDesc;
  592. if (Index == 0) // username
  593. {
  594. static const TPuttyTranslation UsernamePromptTranslation[] = {
  595. { L"login as: ", USERNAME_PROMPT2 },
  596. };
  597. PromptTranslation = UsernamePromptTranslation;
  598. PromptKind = pkUserName;
  599. PromptDesc = L"username";
  600. }
  601. else if (Index == 1) // passphrase
  602. {
  603. static const TPuttyTranslation PassphrasePromptTranslation[] = {
  604. { L"Passphrase for key \"%\": ", PROMPT_KEY_PASSPHRASE },
  605. };
  606. PromptTranslation = PassphrasePromptTranslation;
  607. PromptKind = pkPassphrase;
  608. PromptDesc = L"passphrase";
  609. }
  610. else if (Index == 2) // TIS
  611. {
  612. static const TPuttyTranslation TISInstructionTranslation[] = {
  613. { L"Using TIS authentication.%", TIS_INSTRUCTION },
  614. };
  615. static const TPuttyTranslation TISPromptTranslation[] = {
  616. { L"Response: ", PROMPT_PROMPT },
  617. };
  618. InstructionTranslation = TISInstructionTranslation;
  619. PromptTranslation = TISPromptTranslation;
  620. PromptKind = pkTIS;
  621. PromptDesc = L"tis";
  622. }
  623. else if (Index == 3) // CryptoCard
  624. {
  625. static const TPuttyTranslation CryptoCardInstructionTranslation[] = {
  626. { L"Using CryptoCard authentication.%", CRYPTOCARD_INSTRUCTION },
  627. };
  628. static const TPuttyTranslation CryptoCardPromptTranslation[] = {
  629. { L"Response: ", PROMPT_PROMPT },
  630. };
  631. InstructionTranslation = CryptoCardInstructionTranslation;
  632. PromptTranslation = CryptoCardPromptTranslation;
  633. PromptKind = pkCryptoCard;
  634. PromptDesc = L"cryptocard";
  635. }
  636. else if ((Index == 4) || (Index == 5))
  637. {
  638. static const TPuttyTranslation KeybInteractiveInstructionTranslation[] = {
  639. { L"Using keyboard-interactive authentication.%", KEYBINTER_INSTRUCTION },
  640. };
  641. static const TPuttyTranslation KeybInteractivePromptTranslation[] = {
  642. // as used by Linux-PAM (pam_exec/pam_exec.c, libpam/pam_get_authtok.c,
  643. // pam_unix/pam_unix_auth.c, pam_userdb/pam_userdb.c)
  644. { L"Password: ", PASSWORD_PROMPT },
  645. };
  646. InstructionTranslation = KeybInteractiveInstructionTranslation;
  647. PromptTranslation = KeybInteractivePromptTranslation;
  648. PromptKind = pkKeybInteractive;
  649. PromptDesc = L"keyboard interactive";
  650. }
  651. else if (Index == 6)
  652. {
  653. assert(Prompts->Count == 1);
  654. Prompts->Strings[0] = LoadStr(PASSWORD_PROMPT);
  655. PromptKind = pkPassword;
  656. PromptDesc = L"password";
  657. }
  658. else if (Index == 7)
  659. {
  660. static const TPuttyTranslation NewPasswordPromptTranslation[] = {
  661. { L"Current password (blank for previously entered password): ", NEW_PASSWORD_CURRENT_PROMPT },
  662. { L"Enter new password: ", NEW_PASSWORD_NEW_PROMPT },
  663. { L"Confirm new password: ", NEW_PASSWORD_CONFIRM_PROMPT },
  664. };
  665. PromptTranslation = NewPasswordPromptTranslation;
  666. PromptTranslationCount = LENOF(NewPasswordPromptTranslation);
  667. PromptKind = pkNewPassword;
  668. PromptDesc = L"new password";
  669. }
  670. else
  671. {
  672. PromptKind = pkPrompt;
  673. PromptDesc = L"unknown";
  674. FAIL;
  675. }
  676. UnicodeString InstructionsLog =
  677. (Instructions.IsEmpty() ? UnicodeString(L"<no instructions>") : FORMAT(L"\"%s\"", (Instructions)));
  678. UnicodeString PromptsLog =
  679. (Prompts->Count > 0 ? FORMAT(L"\"%s\"", (Prompts->Strings[0])) : UnicodeString(L"<no prompt>")) +
  680. (Prompts->Count > 1 ? FORMAT(L"%d more", (Prompts->Count - 1)) : UnicodeString());
  681. LogEvent(FORMAT(L"Prompt (%s, \"%s\", %s, %s)", (PromptDesc, AName, InstructionsLog, PromptsLog)));
  682. Name = Name.Trim();
  683. if (InstructionTranslation != NULL)
  684. {
  685. TranslatePuttyMessage(InstructionTranslation, 1, Instructions);
  686. }
  687. // some servers add leading blank line to make the prompt look prettier
  688. // on terminal console
  689. Instructions = Instructions.Trim();
  690. for (int Index = 0; Index < Prompts->Count; Index++)
  691. {
  692. UnicodeString Prompt = Prompts->Strings[Index];
  693. if (PromptTranslation != NULL)
  694. {
  695. TranslatePuttyMessage(PromptTranslation, PromptTranslationCount, Prompt);
  696. }
  697. // some servers add leading blank line to make the prompt look prettier
  698. // on terminal console
  699. Prompts->Strings[Index] = Prompt.Trim();
  700. }
  701. bool Result = false;
  702. if (PromptKind == pkUserName)
  703. {
  704. if (FSessionData->AuthGSSAPI)
  705. {
  706. // use empty username if no username was filled on login dialog
  707. // and GSSAPI auth is enabled, hence there's chance that the server can
  708. // deduce the username otherwise
  709. Results->Strings[0] = L"";
  710. Result = true;
  711. }
  712. }
  713. else if ((PromptKind == pkTIS) || (PromptKind == pkCryptoCard) ||
  714. (PromptKind == pkKeybInteractive))
  715. {
  716. if (FSessionData->AuthKIPassword && !FSessionData->Password.IsEmpty() &&
  717. !FStoredPasswordTriedForKI && (Prompts->Count == 1) &&
  718. FLAGCLEAR(int(Prompts->Objects[0]), pupEcho))
  719. {
  720. LogEvent(L"Using stored password.");
  721. FUI->Information(LoadStr(AUTH_PASSWORD), false);
  722. Result = true;
  723. Results->Strings[0] = FSessionData->Password;
  724. FStoredPasswordTriedForKI = true;
  725. }
  726. else if (Instructions.IsEmpty() && !InstructionsRequired && (Prompts->Count == 0))
  727. {
  728. LogEvent(L"Ignoring empty SSH server authentication request");
  729. Result = true;
  730. }
  731. }
  732. else if (PromptKind == pkPassword)
  733. {
  734. if (!FSessionData->Password.IsEmpty() && !FStoredPasswordTried)
  735. {
  736. LogEvent(L"Using stored password.");
  737. FUI->Information(LoadStr(AUTH_PASSWORD), false);
  738. Result = true;
  739. Results->Strings[0] = FSessionData->Password;
  740. FStoredPasswordTried = true;
  741. }
  742. }
  743. else if (PromptKind == pkPassphrase)
  744. {
  745. if (!FSessionData->Passphrase.IsEmpty() && !FStoredPassphraseTried)
  746. {
  747. LogEvent(L"Using configured passphrase.");
  748. Result = true;
  749. Results->Strings[0] = FSessionData->Passphrase;
  750. FStoredPassphraseTried = true;
  751. }
  752. }
  753. if (!Result)
  754. {
  755. Result = FUI->PromptUser(FSessionData,
  756. PromptKind, Name, Instructions, Prompts, Results);
  757. if (Result)
  758. {
  759. if ((Prompts->Count >= 1) &&
  760. (FLAGSET(int(Prompts->Objects[0]), pupEcho) || Configuration->LogSensitive))
  761. {
  762. LogEvent(FORMAT(L"Response: \"%s\"", (Results->Strings[0])));
  763. }
  764. if ((PromptKind == pkUserName) && (Prompts->Count == 1))
  765. {
  766. FUserName = Results->Strings[0];
  767. }
  768. }
  769. }
  770. return Result;
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TSecureShell::GotHostKey()
  774. {
  775. // due to re-key GotHostKey() may be called again later during session
  776. if (!FAuthenticating && !FAuthenticated)
  777. {
  778. FAuthenticating = true;
  779. FUI->Information(LoadStr(STATUS_AUTHENTICATE), true);
  780. }
  781. }
  782. //---------------------------------------------------------------------------
  783. void __fastcall TSecureShell::CWrite(const char * Data, int Length)
  784. {
  785. // some messages to stderr may indicate that something has changed with the
  786. // session, so reset the session info
  787. ResetSessionInfo();
  788. // We send only whole line at once, so we have to cache incoming data
  789. FCWriteTemp += DeleteChar(ConvertFromPutty(Data, Length), L'\r');
  790. UnicodeString Line;
  791. // Do we have at least one complete line in std error cache?
  792. while (FCWriteTemp.Pos(L"\n") > 0)
  793. {
  794. UnicodeString Line = CutToChar(FCWriteTemp, L'\n', false);
  795. FLog->Add(llStdError, Line);
  796. if (FAuthenticating)
  797. {
  798. TranslateAuthenticationMessage(Line);
  799. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? L"" : L"\n") + Line;
  800. }
  801. FUI->Information(Line, false);
  802. }
  803. }
  804. //---------------------------------------------------------------------------
  805. void __fastcall TSecureShell::RegisterReceiveHandler(TNotifyEvent Handler)
  806. {
  807. assert(FOnReceive == NULL);
  808. FOnReceive = Handler;
  809. }
  810. //---------------------------------------------------------------------------
  811. void __fastcall TSecureShell::UnregisterReceiveHandler(TNotifyEvent Handler)
  812. {
  813. assert(FOnReceive == Handler);
  814. USEDPARAM(Handler);
  815. FOnReceive = NULL;
  816. }
  817. //---------------------------------------------------------------------------
  818. void __fastcall TSecureShell::FromBackend(bool IsStdErr, const unsigned char * Data, int Length)
  819. {
  820. // Note that we do not apply ConvertFromPutty to Data yet (as opposite to CWrite).
  821. // as there's no use for this atm.
  822. CheckConnection();
  823. if (Configuration->ActualLogProtocol >= 1)
  824. {
  825. LogEvent(FORMAT(L"Received %u bytes (%d)", (Length, int(IsStdErr))));
  826. }
  827. // Following is taken from scp.c from_backend() and modified
  828. if (IsStdErr)
  829. {
  830. AddStdError(ConvertInput(RawByteString(reinterpret_cast<const char *>(Data), Length)));
  831. }
  832. else
  833. {
  834. const unsigned char *p = Data;
  835. unsigned Len = (unsigned)Length;
  836. // with event-select mechanism we can now receive data even before we
  837. // actually expect them (OutPtr can be NULL)
  838. if ((OutPtr != NULL) && (OutLen > 0) && (Len > 0))
  839. {
  840. unsigned Used = OutLen;
  841. if (Used > Len) Used = Len;
  842. memmove(OutPtr, p, Used);
  843. OutPtr += Used; OutLen -= Used;
  844. p += Used; Len -= Used;
  845. }
  846. if (Len > 0)
  847. {
  848. if (PendSize < PendLen + Len)
  849. {
  850. PendSize = PendLen + Len + 4096;
  851. Pending = (unsigned char *)
  852. (Pending ? srealloc(Pending, PendSize) : smalloc(PendSize));
  853. if (!Pending) FatalError(L"Out of memory");
  854. }
  855. memmove(Pending + PendLen, p, Len);
  856. PendLen += Len;
  857. }
  858. if (FOnReceive != NULL)
  859. {
  860. if (!FFrozen)
  861. {
  862. FFrozen = true;
  863. try
  864. {
  865. do
  866. {
  867. FDataWhileFrozen = false;
  868. FOnReceive(NULL);
  869. }
  870. while (FDataWhileFrozen);
  871. }
  872. __finally
  873. {
  874. FFrozen = false;
  875. }
  876. }
  877. else
  878. {
  879. FDataWhileFrozen = true;
  880. }
  881. }
  882. }
  883. }
  884. //---------------------------------------------------------------------------
  885. bool __fastcall TSecureShell::Peek(unsigned char *& Buf, int Len)
  886. {
  887. bool Result = (int(PendLen) >= Len);
  888. if (Result)
  889. {
  890. Buf = Pending;
  891. }
  892. return Result;
  893. }
  894. //---------------------------------------------------------------------------
  895. Integer __fastcall TSecureShell::Receive(unsigned char * Buf, Integer Len)
  896. {
  897. CheckConnection();
  898. if (Len > 0)
  899. {
  900. // Following is taken from scp.c ssh_scp_recv() and modified
  901. OutPtr = Buf;
  902. OutLen = Len;
  903. try
  904. {
  905. /*
  906. * See if the pending-input block contains some of what we
  907. * need.
  908. */
  909. if (PendLen > 0)
  910. {
  911. unsigned PendUsed = PendLen;
  912. if (PendUsed > OutLen)
  913. {
  914. PendUsed = OutLen;
  915. }
  916. memmove(OutPtr, Pending, PendUsed);
  917. memmove(Pending, Pending + PendUsed, PendLen - PendUsed);
  918. OutPtr += PendUsed;
  919. OutLen -= PendUsed;
  920. PendLen -= PendUsed;
  921. if (PendLen == 0)
  922. {
  923. PendSize = 0;
  924. sfree(Pending);
  925. Pending = NULL;
  926. }
  927. }
  928. while (OutLen > 0)
  929. {
  930. if (Configuration->ActualLogProtocol >= 1)
  931. {
  932. LogEvent(FORMAT(L"Waiting for another %u bytes", (static_cast<int>(OutLen))));
  933. }
  934. WaitForData();
  935. }
  936. // This seems ambiguous
  937. if (Len <= 0) FatalError(LoadStr(LOST_CONNECTION));
  938. }
  939. __finally
  940. {
  941. OutPtr = NULL;
  942. }
  943. }
  944. if (Configuration->ActualLogProtocol >= 1)
  945. {
  946. LogEvent(FORMAT(L"Read %u bytes (%d pending)",
  947. (static_cast<int>(Len), static_cast<int>(PendLen))));
  948. }
  949. return Len;
  950. }
  951. //---------------------------------------------------------------------------
  952. UnicodeString __fastcall TSecureShell::ReceiveLine()
  953. {
  954. unsigned Index;
  955. RawByteString Line;
  956. Boolean EOL = False;
  957. do
  958. {
  959. // If there is any buffer of received chars
  960. if (PendLen > 0)
  961. {
  962. Index = 0;
  963. // Repeat until we walk thru whole buffer or reach end-of-line
  964. while ((Index < PendLen) && (!Index || (Pending[Index-1] != '\n')))
  965. {
  966. Index++;
  967. }
  968. EOL = (Boolean)(Index && (Pending[Index-1] == '\n'));
  969. Integer PrevLen = Line.Length();
  970. Line.SetLength(PrevLen + Index);
  971. Receive(reinterpret_cast<unsigned char *>(Line.c_str()) + PrevLen, Index);
  972. }
  973. // If buffer don't contain end-of-line character
  974. // we read one more which causes receiving new buffer of chars
  975. if (!EOL)
  976. {
  977. unsigned char Ch;
  978. Receive(&Ch, 1);
  979. Line += static_cast<char>(Ch);
  980. EOL = (static_cast<char>(Ch) == '\n');
  981. }
  982. }
  983. while (!EOL);
  984. // We don't want end-of-line character
  985. Line.SetLength(Line.Length()-1);
  986. UnicodeString Result = ConvertInput(Line);
  987. CaptureOutput(llOutput, Result);
  988. return Result;
  989. }
  990. //---------------------------------------------------------------------------
  991. UnicodeString __fastcall TSecureShell::ConvertInput(const RawByteString & Input)
  992. {
  993. UnicodeString Result;
  994. if (UtfStrings)
  995. {
  996. Result = UnicodeString(UTF8String(Input.c_str()));
  997. }
  998. else
  999. {
  1000. Result = UnicodeString(AnsiString(Input.c_str()));
  1001. }
  1002. return Result;
  1003. }
  1004. //---------------------------------------------------------------------------
  1005. void __fastcall TSecureShell::SendSpecial(int Code)
  1006. {
  1007. LogEvent(FORMAT(L"Sending special code: %d", (Code)));
  1008. CheckConnection();
  1009. FBackend->special(FBackendHandle, (Telnet_Special)Code);
  1010. CheckConnection();
  1011. FLastDataSent = Now();
  1012. }
  1013. //---------------------------------------------------------------------------
  1014. void __fastcall TSecureShell::SendEOF()
  1015. {
  1016. SendSpecial(TS_EOF);
  1017. }
  1018. //---------------------------------------------------------------------------
  1019. unsigned int __fastcall TSecureShell::TimeoutPrompt(TQueryParamsTimerEvent PoolEvent)
  1020. {
  1021. FWaiting++;
  1022. unsigned int Answer;
  1023. try
  1024. {
  1025. TQueryParams Params(qpFatalAbort | qpAllowContinueOnError | qpIgnoreAbort);
  1026. Params.HelpKeyword = HELP_MESSAGE_HOST_IS_NOT_COMMUNICATING;
  1027. Params.Timer = 500;
  1028. Params.TimerEvent = PoolEvent;
  1029. Params.TimerMessage = MainInstructionsFirstParagraph(FMTLOAD(TIMEOUT_STILL_WAITING3, (FSessionData->Timeout)));
  1030. Params.TimerAnswers = qaAbort;
  1031. Params.TimerQueryType = qtInformation;
  1032. if (FConfiguration->SessionReopenAutoStall > 0)
  1033. {
  1034. Params.Timeout = FConfiguration->SessionReopenAutoStall;
  1035. Params.TimeoutAnswer = qaAbort;
  1036. }
  1037. Answer = FUI->QueryUser(MainInstructions(FMTLOAD(CONFIRM_PROLONG_TIMEOUT3, (FSessionData->Timeout))),
  1038. NULL, qaRetry | qaAbort, &Params);
  1039. }
  1040. __finally
  1041. {
  1042. FWaiting--;
  1043. }
  1044. return Answer;
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. void __fastcall TSecureShell::SendBuffer(unsigned int & Result)
  1048. {
  1049. // for comments see PoolForData
  1050. if (!Active)
  1051. {
  1052. Result = qaRetry;
  1053. }
  1054. else
  1055. {
  1056. try
  1057. {
  1058. if (FBackend->sendbuffer(FBackendHandle) <= MAX_BUFSIZE)
  1059. {
  1060. Result = qaOK;
  1061. }
  1062. }
  1063. catch(...)
  1064. {
  1065. Result = qaRetry;
  1066. }
  1067. }
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TSecureShell::DispatchSendBuffer(int BufSize)
  1071. {
  1072. TDateTime Start = Now();
  1073. do
  1074. {
  1075. CheckConnection();
  1076. if (Configuration->ActualLogProtocol >= 1)
  1077. {
  1078. LogEvent(FORMAT(L"There are %u bytes remaining in the send buffer, "
  1079. "need to send at least another %u bytes",
  1080. (BufSize, BufSize - MAX_BUFSIZE)));
  1081. }
  1082. EventSelectLoop(100, false, NULL);
  1083. BufSize = FBackend->sendbuffer(FBackendHandle);
  1084. if (Configuration->ActualLogProtocol >= 1)
  1085. {
  1086. LogEvent(FORMAT(L"There are %u bytes remaining in the send buffer", (BufSize)));
  1087. }
  1088. if (Now() - Start > FSessionData->TimeoutDT)
  1089. {
  1090. LogEvent(L"Waiting for dispatching send buffer timed out, asking user what to do.");
  1091. unsigned int Answer = TimeoutPrompt(SendBuffer);
  1092. switch (Answer)
  1093. {
  1094. case qaRetry:
  1095. Start = Now();
  1096. break;
  1097. case qaOK:
  1098. BufSize = 0;
  1099. break;
  1100. default:
  1101. FAIL;
  1102. // fallthru
  1103. case qaAbort:
  1104. FatalError(MainInstructions(LoadStr(USER_TERMINATED)));
  1105. break;
  1106. }
  1107. }
  1108. }
  1109. while (BufSize > MAX_BUFSIZE);
  1110. }
  1111. //---------------------------------------------------------------------------
  1112. void __fastcall TSecureShell::Send(const unsigned char * Buf, Integer Len)
  1113. {
  1114. CheckConnection();
  1115. int BufSize = FBackend->send(FBackendHandle, const_cast<char *>(reinterpret_cast<const char *>(Buf)), Len);
  1116. if (Configuration->ActualLogProtocol >= 1)
  1117. {
  1118. LogEvent(FORMAT(L"Sent %u bytes", (static_cast<int>(Len))));
  1119. LogEvent(FORMAT(L"There are %u bytes remaining in the send buffer", (BufSize)));
  1120. }
  1121. FLastDataSent = Now();
  1122. // among other forces receive of pending data to free the servers's send buffer
  1123. EventSelectLoop(0, false, NULL);
  1124. if (BufSize > MAX_BUFSIZE)
  1125. {
  1126. DispatchSendBuffer(BufSize);
  1127. }
  1128. CheckConnection();
  1129. }
  1130. //---------------------------------------------------------------------------
  1131. void __fastcall TSecureShell::SendNull()
  1132. {
  1133. LogEvent(L"Sending NULL.");
  1134. unsigned char Null = 0;
  1135. Send(&Null, 1);
  1136. }
  1137. //---------------------------------------------------------------------------
  1138. void __fastcall TSecureShell::SendLine(const UnicodeString & Line)
  1139. {
  1140. CheckConnection();
  1141. RawByteString Buf;
  1142. if (UtfStrings)
  1143. {
  1144. Buf = RawByteString(UTF8String(Line));
  1145. }
  1146. else
  1147. {
  1148. Buf = RawByteString(AnsiString(Line));
  1149. }
  1150. Buf += "\n";
  1151. FLog->Add(llInput, Line);
  1152. Send(reinterpret_cast<const unsigned char *>(Buf.c_str()), Buf.Length());
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. int __fastcall TSecureShell::TranslatePuttyMessage(
  1156. const TPuttyTranslation * Translation, size_t Count, UnicodeString & Message,
  1157. UnicodeString * HelpKeyword)
  1158. {
  1159. int Result = -1;
  1160. for (unsigned int Index = 0; Index < Count; Index++)
  1161. {
  1162. const wchar_t * Original = Translation[Index].Original;
  1163. const wchar_t * Div = wcschr(Original, L'%');
  1164. if (Div == NULL)
  1165. {
  1166. if (wcscmp(Message.c_str(), Original) == 0)
  1167. {
  1168. Message = LoadStr(Translation[Index].Translation);
  1169. Result = int(Index);
  1170. break;
  1171. }
  1172. }
  1173. else
  1174. {
  1175. size_t OriginalLen = wcslen(Original);
  1176. size_t PrefixLen = Div - Original;
  1177. size_t SuffixLen = OriginalLen - PrefixLen - 1;
  1178. if (((size_t)Message.Length() >= OriginalLen - 1) &&
  1179. (wcsncmp(Message.c_str(), Original, PrefixLen) == 0) &&
  1180. (wcsncmp(Message.c_str() + Message.Length() - SuffixLen, Div + 1, SuffixLen) == 0))
  1181. {
  1182. Message = FMTLOAD(Translation[Index].Translation,
  1183. (Message.SubString(PrefixLen + 1, Message.Length() - PrefixLen - SuffixLen).TrimRight()));
  1184. Result = int(Index);
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. if ((HelpKeyword != NULL) && (Result >= 0))
  1190. {
  1191. *HelpKeyword = Translation[Result].HelpKeyword;
  1192. }
  1193. return Result;
  1194. }
  1195. //---------------------------------------------------------------------------
  1196. int __fastcall TSecureShell::TranslateAuthenticationMessage(
  1197. UnicodeString & Message, UnicodeString * HelpKeyword)
  1198. {
  1199. static const TPuttyTranslation Translation[] = {
  1200. { L"Using username \"%\".", AUTH_TRANSL_USERNAME },
  1201. { L"Using keyboard-interactive authentication.", AUTH_TRANSL_KEYB_INTER }, // not used anymore
  1202. { L"Authenticating with public key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  1203. { L"Authenticating with public key \"%\"", AUTH_TRANSL_PUBLIC_KEY },
  1204. { L"Authenticated using RSA key \"%\" from agent", AUTH_TRANSL_PUBLIC_KEY_AGENT },
  1205. { L"Wrong passphrase", AUTH_TRANSL_WRONG_PASSPHRASE },
  1206. { L"Wrong passphrase.", AUTH_TRANSL_WRONG_PASSPHRASE },
  1207. { L"Access denied", AUTH_TRANSL_ACCESS_DENIED },
  1208. { L"Trying public key authentication.", AUTH_TRANSL_TRY_PUBLIC_KEY },
  1209. { L"Server refused our public key.", AUTH_TRANSL_KEY_REFUSED },
  1210. { L"Server refused our key", AUTH_TRANSL_KEY_REFUSED }
  1211. };
  1212. int Result = TranslatePuttyMessage(Translation, LENOF(Translation), Message, HelpKeyword);
  1213. if ((Result == 2) || (Result == 3) || (Result == 4))
  1214. {
  1215. FCollectPrivateKeyUsage = true;
  1216. }
  1217. return Result;
  1218. }
  1219. //---------------------------------------------------------------------------
  1220. void __fastcall TSecureShell::AddStdError(UnicodeString Str)
  1221. {
  1222. FStdError += Str;
  1223. Integer P;
  1224. Str = DeleteChar(Str, L'\r');
  1225. // We send only whole line at once to log, so we have to cache
  1226. // incoming std error data
  1227. FStdErrorTemp += Str;
  1228. UnicodeString Line;
  1229. // Do we have at least one complete line in std error cache?
  1230. while ((P = FStdErrorTemp.Pos(L"\n")) > 0)
  1231. {
  1232. Line = FStdErrorTemp.SubString(1, P-1);
  1233. FStdErrorTemp.Delete(1, P);
  1234. AddStdErrorLine(Line);
  1235. }
  1236. }
  1237. //---------------------------------------------------------------------------
  1238. void __fastcall TSecureShell::AddStdErrorLine(const UnicodeString & Str)
  1239. {
  1240. if (FAuthenticating)
  1241. {
  1242. FAuthenticationLog += (FAuthenticationLog.IsEmpty() ? L"" : L"\n") + Str;
  1243. }
  1244. CaptureOutput(llStdError, Str);
  1245. }
  1246. //---------------------------------------------------------------------------
  1247. const UnicodeString & __fastcall TSecureShell::GetStdError()
  1248. {
  1249. return FStdError;
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. void __fastcall TSecureShell::ClearStdError()
  1253. {
  1254. // Flush std error cache
  1255. if (!FStdErrorTemp.IsEmpty())
  1256. {
  1257. if (FAuthenticating)
  1258. {
  1259. FAuthenticationLog +=
  1260. (FAuthenticationLog.IsEmpty() ? L"" : L"\n") + FStdErrorTemp;
  1261. }
  1262. CaptureOutput(llStdError, FStdErrorTemp);
  1263. FStdErrorTemp = L"";
  1264. }
  1265. FStdError = L"";
  1266. }
  1267. //---------------------------------------------------------------------------
  1268. void __fastcall TSecureShell::CaptureOutput(TLogLineType Type,
  1269. const UnicodeString & Line)
  1270. {
  1271. if (FOnCaptureOutput != NULL)
  1272. {
  1273. FOnCaptureOutput(Line, (Type == llStdError) ? cotError : cotOutput);
  1274. }
  1275. FLog->Add(Type, Line);
  1276. }
  1277. //---------------------------------------------------------------------------
  1278. int __fastcall TSecureShell::TranslateErrorMessage(
  1279. UnicodeString & Message, UnicodeString * HelpKeyword)
  1280. {
  1281. static const TPuttyTranslation Translation[] = {
  1282. { L"Server unexpectedly closed network connection", UNEXPECTED_CLOSE_ERROR, HELP_UNEXPECTED_CLOSE_ERROR },
  1283. { L"Network error: Connection refused", NET_TRANSL_REFUSED2, HELP_NET_TRANSL_REFUSED },
  1284. { L"Network error: Connection reset by peer", NET_TRANSL_RESET, HELP_NET_TRANSL_RESET },
  1285. { L"Network error: Connection timed out", NET_TRANSL_TIMEOUT2, HELP_NET_TRANSL_TIMEOUT },
  1286. { L"Network error: No route to host", NET_TRANSL_NO_ROUTE2, HELP_NET_TRANSL_NO_ROUTE },
  1287. { L"Network error: Software caused connection abort", NET_TRANSL_CONN_ABORTED, HELP_NET_TRANSL_CONN_ABORTED },
  1288. { L"Host does not exist", NET_TRANSL_HOST_NOT_EXIST2, HELP_NET_TRANSL_HOST_NOT_EXIST },
  1289. { L"Incoming packet was garbled on decryption", NET_TRANSL_PACKET_GARBLED, HELP_NET_TRANSL_PACKET_GARBLED },
  1290. };
  1291. int Index = TranslatePuttyMessage(Translation, LENOF(Translation), Message, HelpKeyword);
  1292. if ((Index == 0) || (Index == 1) || (Index == 2) || (Index == 3))
  1293. {
  1294. FNoConnectionResponse = true;
  1295. }
  1296. Message = ReplaceStr(Message, L"%HOST%", FSessionData->HostNameExpanded);
  1297. return Index;
  1298. }
  1299. //---------------------------------------------------------------------------
  1300. void __fastcall TSecureShell::PuttyFatalError(UnicodeString Error)
  1301. {
  1302. UnicodeString HelpKeyword;
  1303. TranslateErrorMessage(Error, &HelpKeyword);
  1304. FatalError(Error, HelpKeyword);
  1305. }
  1306. //---------------------------------------------------------------------------
  1307. void __fastcall TSecureShell::FatalError(UnicodeString Error, UnicodeString HelpKeyword)
  1308. {
  1309. FUI->FatalError(NULL, Error, HelpKeyword);
  1310. }
  1311. //---------------------------------------------------------------------------
  1312. void __fastcall inline TSecureShell::LogEvent(const UnicodeString & Str)
  1313. {
  1314. if (FLog->Logging)
  1315. {
  1316. FLog->Add(llMessage, Str);
  1317. }
  1318. }
  1319. //---------------------------------------------------------------------------
  1320. void __fastcall TSecureShell::SocketEventSelect(SOCKET Socket, HANDLE Event, bool Startup)
  1321. {
  1322. int Events;
  1323. if (Startup)
  1324. {
  1325. Events = (FD_CONNECT | FD_READ | FD_WRITE | FD_OOB | FD_CLOSE | FD_ACCEPT);
  1326. }
  1327. else
  1328. {
  1329. Events = 0;
  1330. }
  1331. if (Configuration->ActualLogProtocol >= 2)
  1332. {
  1333. LogEvent(FORMAT(L"Selecting events %d for socket %d", (int(Events), int(Socket))));
  1334. }
  1335. if (WSAEventSelect(Socket, (WSAEVENT)Event, Events) == SOCKET_ERROR)
  1336. {
  1337. if (Configuration->ActualLogProtocol >= 2)
  1338. {
  1339. LogEvent(FORMAT(L"Error selecting events %d for socket %d", (int(Events), int(Socket))));
  1340. }
  1341. if (Startup)
  1342. {
  1343. FatalError(FMTLOAD(EVENT_SELECT_ERROR, (WSAGetLastError())));
  1344. }
  1345. }
  1346. }
  1347. //---------------------------------------------------------------------------
  1348. void __fastcall TSecureShell::UpdateSocket(SOCKET value, bool Startup)
  1349. {
  1350. if (!FActive && !Startup)
  1351. {
  1352. // no-op
  1353. // Remove the branch eventually:
  1354. // When TCP connection fails, PuTTY does not release the memory allocated for
  1355. // socket. As a simple hack we call sk_tcp_close() in ssh.c to release the memory,
  1356. // until they fix it better. Unfortunately sk_tcp_close calls do_select,
  1357. // so we must filter that out.
  1358. }
  1359. else
  1360. {
  1361. assert(value);
  1362. assert((FActive && (FSocket == value)) || (!FActive && Startup));
  1363. // filter our "local proxy" connection, which have no socket
  1364. if (value != INVALID_SOCKET)
  1365. {
  1366. SocketEventSelect(value, FSocketEvent, Startup);
  1367. }
  1368. else
  1369. {
  1370. assert(FSessionData->ProxyMethod == pmCmd);
  1371. }
  1372. if (Startup)
  1373. {
  1374. FSocket = value;
  1375. FActive = true;
  1376. }
  1377. else
  1378. {
  1379. FSocket = INVALID_SOCKET;
  1380. Discard();
  1381. }
  1382. }
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. void __fastcall TSecureShell::UpdatePortFwdSocket(SOCKET value, bool Startup)
  1386. {
  1387. if (Configuration->ActualLogProtocol >= 2)
  1388. {
  1389. LogEvent(FORMAT(L"Updating forwarding socket %d (%d)", (int(value), int(Startup))));
  1390. }
  1391. SocketEventSelect(value, FSocketEvent, Startup);
  1392. if (Startup)
  1393. {
  1394. FPortFwdSockets.insert(value);
  1395. }
  1396. else
  1397. {
  1398. FPortFwdSockets.erase(value);
  1399. }
  1400. }
  1401. //---------------------------------------------------------------------------
  1402. void __fastcall TSecureShell::SetActive(bool value)
  1403. {
  1404. if (FActive != value)
  1405. {
  1406. if (value)
  1407. {
  1408. Open();
  1409. }
  1410. else
  1411. {
  1412. Close();
  1413. }
  1414. }
  1415. }
  1416. //---------------------------------------------------------------------------
  1417. void __fastcall TSecureShell::FreeBackend()
  1418. {
  1419. if (FBackendHandle != NULL)
  1420. {
  1421. FBackend->free(FBackendHandle);
  1422. FBackendHandle = NULL;
  1423. }
  1424. }
  1425. //---------------------------------------------------------------------------
  1426. void __fastcall TSecureShell::Discard()
  1427. {
  1428. bool WasActive = FActive;
  1429. FActive = false;
  1430. FOpened = false;
  1431. if (WasActive)
  1432. {
  1433. FUI->Closed();
  1434. }
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. void __fastcall TSecureShell::Close()
  1438. {
  1439. LogEvent(L"Closing connection.");
  1440. assert(FActive);
  1441. // this is particularly necessary when using local proxy command
  1442. // (e.g. plink), otherwise it hangs in sk_localproxy_close
  1443. SendEOF();
  1444. FreeBackend();
  1445. Discard();
  1446. }
  1447. //---------------------------------------------------------------------------
  1448. void inline __fastcall TSecureShell::CheckConnection(int Message)
  1449. {
  1450. if (!FActive || get_ssh_state_closed(FBackendHandle))
  1451. {
  1452. UnicodeString Str;
  1453. UnicodeString HelpKeyword;
  1454. if (Message >= 0)
  1455. {
  1456. Str = LoadStr(Message);
  1457. }
  1458. else
  1459. {
  1460. Str = LoadStr(NOT_CONNECTED);
  1461. HelpKeyword = HELP_NOT_CONNECTED;
  1462. }
  1463. Str = MainInstructions(Str);
  1464. int ExitCode = get_ssh_exitcode(FBackendHandle);
  1465. if (ExitCode >= 0)
  1466. {
  1467. Str += L" " + FMTLOAD(SSH_EXITCODE, (ExitCode));
  1468. }
  1469. FatalError(Str, HelpKeyword);
  1470. }
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. void __fastcall TSecureShell::PoolForData(WSANETWORKEVENTS & Events, unsigned int & Result)
  1474. {
  1475. if (!Active)
  1476. {
  1477. // see comment below
  1478. Result = qaRetry;
  1479. }
  1480. else
  1481. {
  1482. try
  1483. {
  1484. if (Configuration->ActualLogProtocol >= 2)
  1485. {
  1486. LogEvent(L"Pooling for data in case they finally arrives");
  1487. }
  1488. // in extreme condition it may happen that send buffer is full, but there
  1489. // will be no data coming and we may not empty the send buffer because we
  1490. // do not process FD_WRITE until we receive any FD_READ
  1491. if (EventSelectLoop(0, false, &Events))
  1492. {
  1493. LogEvent(L"Data has arrived, closing query to user.");
  1494. Result = qaOK;
  1495. }
  1496. }
  1497. catch(...)
  1498. {
  1499. // if we let the exception out, it may popup another message dialog
  1500. // in whole event loop, another call to PoolForData from original dialog
  1501. // would be invoked, leading to an infinite loop.
  1502. // by retrying we hope (that probably fatal) error would repeat in WaitForData.
  1503. // anyway now once no actual work is done in EventSelectLoop,
  1504. // hardly any exception can occur actually
  1505. Result = qaRetry;
  1506. }
  1507. }
  1508. }
  1509. //---------------------------------------------------------------------------
  1510. class TPoolForDataEvent
  1511. {
  1512. public:
  1513. __fastcall TPoolForDataEvent(TSecureShell * SecureShell, WSANETWORKEVENTS & Events) :
  1514. FSecureShell(SecureShell),
  1515. FEvents(Events)
  1516. {
  1517. }
  1518. void __fastcall PoolForData(unsigned int & Result)
  1519. {
  1520. FSecureShell->PoolForData(FEvents, Result);
  1521. }
  1522. private:
  1523. TSecureShell * FSecureShell;
  1524. WSANETWORKEVENTS & FEvents;
  1525. };
  1526. //---------------------------------------------------------------------------
  1527. void __fastcall TSecureShell::WaitForData()
  1528. {
  1529. // see winsftp.c
  1530. bool IncomingData;
  1531. do
  1532. {
  1533. if (Configuration->ActualLogProtocol >= 2)
  1534. {
  1535. LogEvent(L"Looking for incoming data");
  1536. }
  1537. IncomingData = EventSelectLoop(FSessionData->Timeout * MSecsPerSec, true, NULL);
  1538. if (!IncomingData)
  1539. {
  1540. assert(FWaitingForData == 0);
  1541. TAutoNestingCounter NestingCounter(FWaitingForData);
  1542. WSANETWORKEVENTS Events;
  1543. memset(&Events, 0, sizeof(Events));
  1544. TPoolForDataEvent Event(this, Events);
  1545. LogEvent(L"Waiting for data timed out, asking user what to do.");
  1546. unsigned int Answer = TimeoutPrompt(Event.PoolForData);
  1547. switch (Answer)
  1548. {
  1549. case qaRetry:
  1550. // noop
  1551. break;
  1552. case qaOK:
  1553. // read event was already captured in PoolForData(),
  1554. // make sure we do not try to select it again as it would timeout
  1555. // unless another read event occurs
  1556. IncomingData = true;
  1557. HandleNetworkEvents(FSocket, Events);
  1558. break;
  1559. default:
  1560. FAIL;
  1561. // fallthru
  1562. case qaAbort:
  1563. FatalError(MainInstructions(LoadStr(USER_TERMINATED)));
  1564. break;
  1565. }
  1566. }
  1567. }
  1568. while (!IncomingData);
  1569. }
  1570. //---------------------------------------------------------------------------
  1571. bool __fastcall TSecureShell::SshFallbackCmd() const
  1572. {
  1573. return ssh_fallback_cmd(FBackendHandle);
  1574. }
  1575. //---------------------------------------------------------------------------
  1576. bool __fastcall TSecureShell::EnumNetworkEvents(SOCKET Socket, WSANETWORKEVENTS & Events)
  1577. {
  1578. if (Configuration->ActualLogProtocol >= 2)
  1579. {
  1580. LogEvent(FORMAT(L"Enumerating network events for socket %d", (int(Socket))));
  1581. }
  1582. // see winplink.c
  1583. WSANETWORKEVENTS AEvents;
  1584. if (WSAEnumNetworkEvents(Socket, NULL, &AEvents) == 0)
  1585. {
  1586. noise_ultralight(Socket);
  1587. noise_ultralight(AEvents.lNetworkEvents);
  1588. Events.lNetworkEvents |= AEvents.lNetworkEvents;
  1589. for (int Index = 0; Index < FD_MAX_EVENTS; Index++)
  1590. {
  1591. if (AEvents.iErrorCode[Index] != 0)
  1592. {
  1593. Events.iErrorCode[Index] = AEvents.iErrorCode[Index];
  1594. }
  1595. }
  1596. if (Configuration->ActualLogProtocol >= 2)
  1597. {
  1598. LogEvent(FORMAT(L"Enumerated %d network events making %d cumulative events for socket %d",
  1599. (int(AEvents.lNetworkEvents), int(Events.lNetworkEvents), int(Socket))));
  1600. }
  1601. }
  1602. else
  1603. {
  1604. if (Configuration->ActualLogProtocol >= 2)
  1605. {
  1606. LogEvent(FORMAT(L"Error enumerating network events for socket %d", (int(Socket))));
  1607. }
  1608. }
  1609. return
  1610. FLAGSET(Events.lNetworkEvents, FD_READ) ||
  1611. FLAGSET(Events.lNetworkEvents, FD_CLOSE);
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. void __fastcall TSecureShell::HandleNetworkEvents(SOCKET Socket, WSANETWORKEVENTS & Events)
  1615. {
  1616. static const struct { int Bit, Mask; const wchar_t * Desc; } EventTypes[] =
  1617. {
  1618. { FD_READ_BIT, FD_READ, L"read" },
  1619. { FD_WRITE_BIT, FD_WRITE, L"write" },
  1620. { FD_OOB_BIT, FD_OOB, L"oob" },
  1621. { FD_ACCEPT_BIT, FD_ACCEPT, L"accept" },
  1622. { FD_CONNECT_BIT, FD_CONNECT, L"connect" },
  1623. { FD_CLOSE_BIT, FD_CLOSE, L"close" },
  1624. };
  1625. for (unsigned int Event = 0; Event < LENOF(EventTypes); Event++)
  1626. {
  1627. if (FLAGSET(Events.lNetworkEvents, EventTypes[Event].Mask))
  1628. {
  1629. int Err = Events.iErrorCode[EventTypes[Event].Bit];
  1630. if (Configuration->ActualLogProtocol >= 2)
  1631. {
  1632. LogEvent(FORMAT(L"Handling network %s event on socket %d with error %d",
  1633. (EventTypes[Event].Desc, int(Socket), Err)));
  1634. }
  1635. #pragma option push -w-prc
  1636. LPARAM SelectEvent = WSAMAKESELECTREPLY(EventTypes[Event].Mask, Err);
  1637. #pragma option pop
  1638. if (!select_result((WPARAM)Socket, SelectEvent))
  1639. {
  1640. // note that connection was closed definitely,
  1641. // so "check" is actually not required
  1642. CheckConnection();
  1643. }
  1644. }
  1645. }
  1646. }
  1647. //---------------------------------------------------------------------------
  1648. bool __fastcall TSecureShell::ProcessNetworkEvents(SOCKET Socket)
  1649. {
  1650. WSANETWORKEVENTS Events;
  1651. memset(&Events, 0, sizeof(Events));
  1652. bool Result = EnumNetworkEvents(Socket, Events);
  1653. HandleNetworkEvents(Socket, Events);
  1654. return Result;
  1655. }
  1656. //---------------------------------------------------------------------------
  1657. bool __fastcall TSecureShell::EventSelectLoop(unsigned int MSec, bool ReadEventRequired,
  1658. WSANETWORKEVENTS * Events)
  1659. {
  1660. CheckConnection();
  1661. bool Result = false;
  1662. do
  1663. {
  1664. if (Configuration->ActualLogProtocol >= 2)
  1665. {
  1666. LogEvent(L"Looking for network events");
  1667. }
  1668. unsigned int TicksBefore = GetTickCount();
  1669. int HandleCount;
  1670. // note that this returns all handles, not only the session-related handles
  1671. HANDLE * Handles = handle_get_events(&HandleCount);
  1672. try
  1673. {
  1674. Handles = sresize(Handles, HandleCount + 1, HANDLE);
  1675. Handles[HandleCount] = FSocketEvent;
  1676. unsigned int Timeout = MSec;
  1677. if (toplevel_callback_pending())
  1678. {
  1679. Timeout = 0;
  1680. }
  1681. unsigned int WaitResult;
  1682. do
  1683. {
  1684. unsigned int TimeoutStep = std::min(GUIUpdateInterval, Timeout);
  1685. Timeout -= TimeoutStep;
  1686. WaitResult = WaitForMultipleObjects(HandleCount + 1, Handles, FALSE, TimeoutStep);
  1687. ProcessGUI();
  1688. } while ((WaitResult == WAIT_TIMEOUT) && (Timeout > 0));
  1689. if (WaitResult < WAIT_OBJECT_0 + HandleCount)
  1690. {
  1691. if (handle_got_event(Handles[WaitResult - WAIT_OBJECT_0]))
  1692. {
  1693. Result = true;
  1694. }
  1695. }
  1696. else if (WaitResult == WAIT_OBJECT_0 + HandleCount)
  1697. {
  1698. if (Configuration->ActualLogProtocol >= 1)
  1699. {
  1700. LogEvent(L"Detected network event");
  1701. }
  1702. if (Events == NULL)
  1703. {
  1704. if (ProcessNetworkEvents(FSocket))
  1705. {
  1706. Result = true;
  1707. }
  1708. }
  1709. else
  1710. {
  1711. if (EnumNetworkEvents(FSocket, *Events))
  1712. {
  1713. Result = true;
  1714. }
  1715. }
  1716. {
  1717. TSockets::iterator i = FPortFwdSockets.begin();
  1718. while (i != FPortFwdSockets.end())
  1719. {
  1720. ProcessNetworkEvents(*i);
  1721. i++;
  1722. }
  1723. }
  1724. }
  1725. else if (WaitResult == WAIT_TIMEOUT)
  1726. {
  1727. if (Configuration->ActualLogProtocol >= 2)
  1728. {
  1729. LogEvent(L"Timeout waiting for network events");
  1730. }
  1731. MSec = 0;
  1732. }
  1733. else
  1734. {
  1735. if (Configuration->ActualLogProtocol >= 2)
  1736. {
  1737. LogEvent(FORMAT(L"Unknown waiting result %d", (int(WaitResult))));
  1738. }
  1739. MSec = 0;
  1740. }
  1741. }
  1742. __finally
  1743. {
  1744. sfree(Handles);
  1745. }
  1746. run_toplevel_callbacks();
  1747. unsigned int TicksAfter = GetTickCount();
  1748. // ticks wraps once in 49.7 days
  1749. if (TicksBefore < TicksAfter)
  1750. {
  1751. unsigned int Ticks = TicksAfter - TicksBefore;
  1752. if (Ticks > MSec)
  1753. {
  1754. MSec = 0;
  1755. }
  1756. else
  1757. {
  1758. MSec -= Ticks;
  1759. }
  1760. }
  1761. }
  1762. while (ReadEventRequired && (MSec > 0) && !Result);
  1763. return Result;
  1764. }
  1765. //---------------------------------------------------------------------------
  1766. void __fastcall TSecureShell::Idle(unsigned int MSec)
  1767. {
  1768. noise_regular();
  1769. call_ssh_timer(FBackendHandle);
  1770. // if we are actively waiting for data in WaitForData,
  1771. // do not read here, otherwise we swallow read event and never wake
  1772. if (FWaitingForData <= 0)
  1773. {
  1774. EventSelectLoop(MSec, false, NULL);
  1775. }
  1776. }
  1777. //---------------------------------------------------------------------------
  1778. void __fastcall TSecureShell::KeepAlive()
  1779. {
  1780. if (FActive && (FWaiting == 0))
  1781. {
  1782. LogEvent(L"Sending null packet to keep session alive.");
  1783. SendSpecial(TS_PING);
  1784. }
  1785. else
  1786. {
  1787. // defer next keepalive attempt
  1788. FLastDataSent = Now();
  1789. }
  1790. }
  1791. //---------------------------------------------------------------------------
  1792. unsigned long __fastcall TSecureShell::MaxPacketSize()
  1793. {
  1794. if (!FSessionInfoValid)
  1795. {
  1796. UpdateSessionInfo();
  1797. }
  1798. if (FSshVersion == 1)
  1799. {
  1800. return 0;
  1801. }
  1802. else
  1803. {
  1804. if (FMaxPacketSize == NULL)
  1805. {
  1806. FMaxPacketSize = ssh2_remmaxpkt(FBackendHandle);
  1807. }
  1808. return *FMaxPacketSize;
  1809. }
  1810. }
  1811. //---------------------------------------------------------------------------
  1812. UnicodeString __fastcall TSecureShell::FuncToCompression(
  1813. int SshVersion, const void * Compress) const
  1814. {
  1815. enum TCompressionType { ctNone, ctZLib };
  1816. if (SshVersion == 1)
  1817. {
  1818. return get_ssh1_compressing(FBackendHandle) ? L"ZLib" : L"";
  1819. }
  1820. else
  1821. {
  1822. return (ssh_compress *)Compress == &ssh_zlib ? L"ZLib" : L"";
  1823. }
  1824. }
  1825. //---------------------------------------------------------------------------
  1826. TCipher __fastcall TSecureShell::FuncToSsh1Cipher(const void * Cipher)
  1827. {
  1828. const ssh_cipher *CipherFuncs[] =
  1829. {&ssh_3des, &ssh_des, &ssh_blowfish_ssh1};
  1830. const TCipher TCiphers[] = {cip3DES, cipDES, cipBlowfish};
  1831. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1832. TCipher Result = cipWarn;
  1833. for (unsigned int Index = 0; Index < LENOF(TCiphers); Index++)
  1834. {
  1835. if ((ssh_cipher *)Cipher == CipherFuncs[Index])
  1836. {
  1837. Result = TCiphers[Index];
  1838. }
  1839. }
  1840. assert(Result != cipWarn);
  1841. return Result;
  1842. }
  1843. //---------------------------------------------------------------------------
  1844. TCipher __fastcall TSecureShell::FuncToSsh2Cipher(const void * Cipher)
  1845. {
  1846. const ssh2_ciphers *CipherFuncs[] =
  1847. {&ssh2_3des, &ssh2_des, &ssh2_aes, &ssh2_blowfish, &ssh2_arcfour};
  1848. const TCipher TCiphers[] = {cip3DES, cipDES, cipAES, cipBlowfish, cipArcfour};
  1849. assert(LENOF(CipherFuncs) == LENOF(TCiphers));
  1850. TCipher Result = cipWarn;
  1851. for (unsigned int C = 0; C < LENOF(TCiphers); C++)
  1852. {
  1853. for (int F = 0; F < CipherFuncs[C]->nciphers; F++)
  1854. {
  1855. if ((ssh2_cipher *)Cipher == CipherFuncs[C]->list[F])
  1856. {
  1857. Result = TCiphers[C];
  1858. }
  1859. }
  1860. }
  1861. assert(Result != cipWarn);
  1862. return Result;
  1863. }
  1864. //---------------------------------------------------------------------------
  1865. UnicodeString __fastcall TSecureShell::FormatKeyStr(UnicodeString KeyStr)
  1866. {
  1867. int Index = 1;
  1868. int Digits = 0;
  1869. while (Index <= KeyStr.Length())
  1870. {
  1871. if (IsHex(KeyStr[Index]))
  1872. {
  1873. Digits++;
  1874. if (Digits >= 16)
  1875. {
  1876. KeyStr.Insert(L" ", Index + 1);
  1877. Index++;
  1878. Digits = 0;
  1879. }
  1880. }
  1881. else
  1882. {
  1883. Digits = 0;
  1884. }
  1885. Index++;
  1886. }
  1887. return KeyStr;
  1888. }
  1889. //---------------------------------------------------------------------------
  1890. void __fastcall TSecureShell::VerifyHostKey(UnicodeString Host, int Port,
  1891. const UnicodeString KeyType, UnicodeString KeyStr, UnicodeString Fingerprint)
  1892. {
  1893. LogEvent(FORMAT(L"Verifying host key %s %s with fingerprint %s", (KeyType, FormatKeyStr(KeyStr), Fingerprint)));
  1894. GotHostKey();
  1895. wchar_t Delimiter = L';';
  1896. assert(KeyStr.Pos(Delimiter) == 0);
  1897. if (FSessionData->Tunnel)
  1898. {
  1899. Host = FSessionData->OrigHostName;
  1900. Port = FSessionData->OrigPortNumber;
  1901. }
  1902. FSessionInfo.HostKeyFingerprint = Fingerprint;
  1903. UnicodeString NormalizedFingerprint = NormalizeFingerprint(Fingerprint);
  1904. bool Result = false;
  1905. UnicodeString StoredKeys;
  1906. AnsiString AnsiStoredKeys;
  1907. AnsiStoredKeys.SetLength(10240);
  1908. if (retrieve_host_key(AnsiString(Host).c_str(), Port, AnsiString(KeyType).c_str(),
  1909. AnsiStoredKeys.c_str(), AnsiStoredKeys.Length()) == 0)
  1910. {
  1911. StoredKeys = AnsiStoredKeys.c_str();
  1912. UnicodeString Buf = StoredKeys;
  1913. while (!Result && !Buf.IsEmpty())
  1914. {
  1915. UnicodeString StoredKey = CutToChar(Buf, Delimiter, false);
  1916. bool Fingerprint = (StoredKey.SubString(1, 2) != L"0x");
  1917. // its probably a fingerprint (stored by TSessionData::CacheHostKey)
  1918. UnicodeString NormalizedExpectedKey;
  1919. if (Fingerprint)
  1920. {
  1921. NormalizedExpectedKey = NormalizeFingerprint(StoredKey);
  1922. }
  1923. if ((!Fingerprint && (StoredKey == KeyStr)) ||
  1924. (Fingerprint && (NormalizedExpectedKey == NormalizedFingerprint)))
  1925. {
  1926. LogEvent(L"Host key matches cached key");
  1927. Result = true;
  1928. }
  1929. else
  1930. {
  1931. UnicodeString FormattedKey = Fingerprint ? StoredKey : FormatKeyStr(StoredKey);
  1932. LogEvent(FORMAT(L"Host key does not match cached key %s", (FormattedKey)));
  1933. }
  1934. }
  1935. }
  1936. bool ConfiguredKeyNotMatch = false;
  1937. if (!Result && !FSessionData->HostKey.IsEmpty() &&
  1938. (StoredKeys.IsEmpty() || FSessionData->OverrideCachedHostKey))
  1939. {
  1940. UnicodeString Buf = FSessionData->HostKey;
  1941. while (!Result && !Buf.IsEmpty())
  1942. {
  1943. UnicodeString ExpectedKey = CutToChar(Buf, Delimiter, false);
  1944. UnicodeString NormalizedExpectedKey = NormalizeFingerprint(ExpectedKey);
  1945. if (ExpectedKey == L"*")
  1946. {
  1947. UnicodeString Message = LoadStr(ANY_HOSTKEY);
  1948. FUI->Information(Message, true);
  1949. FLog->Add(llException, Message);
  1950. Result = true;
  1951. }
  1952. else if (NormalizedExpectedKey == NormalizedFingerprint)
  1953. {
  1954. LogEvent(L"Host key matches configured key");
  1955. Result = true;
  1956. }
  1957. else
  1958. {
  1959. LogEvent(FORMAT(L"Host key does not match configured key %s", (ExpectedKey)));
  1960. }
  1961. }
  1962. if (!Result)
  1963. {
  1964. ConfiguredKeyNotMatch = true;
  1965. }
  1966. }
  1967. if (!Result)
  1968. {
  1969. bool Verified;
  1970. if (ConfiguredKeyNotMatch || Configuration->DisableAcceptingHostKeys)
  1971. {
  1972. Verified = false;
  1973. }
  1974. else
  1975. {
  1976. TClipboardHandler ClipboardHandler;
  1977. ClipboardHandler.Text = Fingerprint;
  1978. bool Unknown = StoredKeys.IsEmpty();
  1979. int Answers;
  1980. int AliasesCount;
  1981. TQueryButtonAlias Aliases[3];
  1982. Aliases[0].Button = qaRetry;
  1983. Aliases[0].Alias = LoadStr(COPY_KEY_BUTTON);
  1984. Aliases[0].OnClick = &ClipboardHandler.Copy;
  1985. Answers = qaYes | qaCancel | qaRetry;
  1986. AliasesCount = 1;
  1987. if (!Unknown)
  1988. {
  1989. Aliases[1].Button = qaYes;
  1990. Aliases[1].Alias = LoadStr(UPDATE_KEY_BUTTON);
  1991. Aliases[2].Button = qaOK;
  1992. Aliases[2].Alias = LoadStr(ADD_KEY_BUTTON);
  1993. AliasesCount += 2;
  1994. Answers |= qaSkip | qaOK;
  1995. }
  1996. else
  1997. {
  1998. Answers |= qaNo;
  1999. }
  2000. TQueryParams Params;
  2001. Params.NoBatchAnswers = qaYes | qaRetry | qaSkip | qaOK;
  2002. Params.HelpKeyword = (Unknown ? HELP_UNKNOWN_KEY : HELP_DIFFERENT_KEY);
  2003. Params.Aliases = Aliases;
  2004. Params.AliasesCount = AliasesCount;
  2005. unsigned int R = FUI->QueryUser(
  2006. FMTLOAD((Unknown ? UNKNOWN_KEY3 : DIFFERENT_KEY4), (KeyType, Fingerprint)),
  2007. NULL, Answers, &Params, qtWarning);
  2008. switch (R) {
  2009. case qaOK:
  2010. assert(!Unknown);
  2011. KeyStr = (StoredKeys + Delimiter + KeyStr);
  2012. // fall thru
  2013. case qaYes:
  2014. store_host_key(AnsiString(Host).c_str(), Port, AnsiString(KeyType).c_str(), AnsiString(KeyStr).c_str());
  2015. Verified = true;
  2016. break;
  2017. case qaCancel:
  2018. Verified = false;
  2019. break;
  2020. default:
  2021. Verified = true;
  2022. break;
  2023. }
  2024. }
  2025. if (!Verified)
  2026. {
  2027. Configuration->Usage->Inc(L"HostNotVerified");
  2028. UnicodeString Message =
  2029. ConfiguredKeyNotMatch ? FMTLOAD(CONFIGURED_KEY_NOT_MATCH, (FSessionData->HostKey)) : LoadStr(KEY_NOT_VERIFIED);
  2030. Exception * E = new Exception(MainInstructions(Message));
  2031. try
  2032. {
  2033. FUI->FatalError(E, FMTLOAD(HOSTKEY, (Fingerprint)));
  2034. }
  2035. __finally
  2036. {
  2037. delete E;
  2038. }
  2039. }
  2040. }
  2041. }
  2042. //---------------------------------------------------------------------------
  2043. void __fastcall TSecureShell::AskAlg(const UnicodeString AlgType,
  2044. const UnicodeString AlgName)
  2045. {
  2046. UnicodeString Msg;
  2047. if (AlgType == L"key-exchange algorithm")
  2048. {
  2049. Msg = FMTLOAD(KEX_BELOW_TRESHOLD, (AlgName));
  2050. }
  2051. else
  2052. {
  2053. int CipherType;
  2054. if (AlgType == L"cipher")
  2055. {
  2056. CipherType = CIPHER_TYPE_BOTH;
  2057. }
  2058. else if (AlgType == L"client-to-server cipher")
  2059. {
  2060. CipherType = CIPHER_TYPE_CS;
  2061. }
  2062. else if (AlgType == L"server-to-client cipher")
  2063. {
  2064. CipherType = CIPHER_TYPE_SC;
  2065. }
  2066. else
  2067. {
  2068. FAIL;
  2069. }
  2070. Msg = FMTLOAD(CIPHER_BELOW_TRESHOLD, (LoadStr(CipherType), AlgName));
  2071. }
  2072. if (FUI->QueryUser(Msg, NULL, qaYes | qaNo, NULL, qtWarning) == qaNo)
  2073. {
  2074. Abort();
  2075. }
  2076. }
  2077. //---------------------------------------------------------------------------
  2078. void __fastcall TSecureShell::DisplayBanner(const UnicodeString & Banner)
  2079. {
  2080. FUI->DisplayBanner(Banner);
  2081. }
  2082. //---------------------------------------------------------------------------
  2083. void __fastcall TSecureShell::OldKeyfileWarning()
  2084. {
  2085. // actually never called, see Net.cpp
  2086. FUI->QueryUser(LoadStr(OLD_KEY), NULL, qaOK, NULL, qtWarning);
  2087. }
  2088. //---------------------------------------------------------------------------
  2089. bool __fastcall TSecureShell::GetStoredCredentialsTried()
  2090. {
  2091. return FStoredPasswordTried || FStoredPasswordTriedForKI || FStoredPassphraseTried;
  2092. }
  2093. //---------------------------------------------------------------------------
  2094. bool __fastcall TSecureShell::GetReady()
  2095. {
  2096. return FOpened && (FWaiting == 0);
  2097. }
  2098. //---------------------------------------------------------------------------
  2099. void __fastcall TSecureShell::CollectUsage()
  2100. {
  2101. if (FCollectPrivateKeyUsage)
  2102. {
  2103. Configuration->Usage->Inc(L"OpenedSessionsPrivateKey2");
  2104. }
  2105. if (FSshVersion == 1)
  2106. {
  2107. Configuration->Usage->Inc(L"OpenedSessionsSSH1");
  2108. }
  2109. else if (FSshVersion == 2)
  2110. {
  2111. Configuration->Usage->Inc(L"OpenedSessionsSSH2");
  2112. }
  2113. if (SshImplementation == sshiOpenSSH)
  2114. {
  2115. Configuration->Usage->Inc(L"OpenedSessionsSSHOpenSSH");
  2116. }
  2117. else if (SshImplementation == sshiProFTPD)
  2118. {
  2119. Configuration->Usage->Inc(L"OpenedSessionsSSHProFTPD");
  2120. }
  2121. else if (SshImplementation == sshiBitvise)
  2122. {
  2123. Configuration->Usage->Inc(L"OpenedSessionsSSHBitvise");
  2124. }
  2125. else if (SshImplementation == sshiTitan)
  2126. {
  2127. Configuration->Usage->Inc(L"OpenedSessionsSSHTitan");
  2128. }
  2129. else
  2130. {
  2131. Configuration->Usage->Inc(L"OpenedSessionsSSHOther");
  2132. }
  2133. }