SecureShell.cpp 95 KB

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