SecureShell.cpp 82 KB

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