SecureShell.cpp 68 KB

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