1
0

SecureShell.cpp 80 KB

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