SecureShell.cpp 74 KB

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