SecureShell.cpp 80 KB

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