PuttyIntf.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "PuttyIntf.h"
  5. #include "Interface.h"
  6. #include "SecureShell.h"
  7. #include "Exceptions.h"
  8. #include "CoreMain.h"
  9. #include "TextsCore.h"
  10. #include <StrUtils.hpp>
  11. #include <Soap.EncdDecd.hpp>
  12. //---------------------------------------------------------------------------
  13. char sshver[50];
  14. extern const char commitid[] = "";
  15. const bool platform_uses_x11_unix_by_default = true;
  16. CRITICAL_SECTION putty_section;
  17. bool SaveRandomSeed;
  18. bool HadRandomSeed;
  19. char appname_[50];
  20. const char *const appname = appname_;
  21. extern const bool share_can_be_downstream = false;
  22. extern const bool share_can_be_upstream = false;
  23. THierarchicalStorage * PuttyStorage = NULL;
  24. //---------------------------------------------------------------------------
  25. extern "C"
  26. {
  27. #include <winstuff.h>
  28. }
  29. const UnicodeString OriginalPuttyRegistryStorageKey(_T(PUTTY_REG_POS));
  30. const UnicodeString KittyRegistryStorageKey(L"Software\\9bis.com\\KiTTY");
  31. const UnicodeString OriginalPuttyExecutable("putty.exe");
  32. const UnicodeString KittyExecutable("kitty.exe");
  33. const UnicodeString PuttyKeyExt(L"ppk");
  34. //---------------------------------------------------------------------------
  35. void __fastcall PuttyInitialize()
  36. {
  37. SaveRandomSeed = true;
  38. InitializeCriticalSection(&putty_section);
  39. HadRandomSeed = FileExists(ApiPath(Configuration->RandomSeedFileName));
  40. // make sure random generator is initialised, so random_save_seed()
  41. // in destructor can proceed
  42. random_ref();
  43. sk_init();
  44. AnsiString VersionString = AnsiString(SshVersionString());
  45. DebugAssert(!VersionString.IsEmpty() && (static_cast<size_t>(VersionString.Length()) < LENOF(sshver)));
  46. strcpy(sshver, VersionString.c_str());
  47. AnsiString AppName = AnsiString(AppNameString());
  48. DebugAssert(!AppName.IsEmpty() && (static_cast<size_t>(AppName.Length()) < LENOF(appname_)));
  49. strcpy(appname_, AppName.c_str());
  50. }
  51. //---------------------------------------------------------------------------
  52. static bool DeleteRandomSeedOnExit()
  53. {
  54. return !HadRandomSeed && !SaveRandomSeed;
  55. }
  56. //---------------------------------------------------------------------------
  57. void __fastcall PuttyFinalize()
  58. {
  59. if (SaveRandomSeed)
  60. {
  61. random_save_seed();
  62. }
  63. random_unref();
  64. // random_ref in PuttyInitialize creates the seed file. Delete it, if we didn't want to create it.
  65. if (DeleteRandomSeedOnExit())
  66. {
  67. DeleteFile(ApiPath(Configuration->RandomSeedFileName));
  68. }
  69. sk_cleanup();
  70. win_misc_cleanup();
  71. win_secur_cleanup();
  72. ec_cleanup();
  73. DeleteCriticalSection(&putty_section);
  74. }
  75. //---------------------------------------------------------------------------
  76. void __fastcall DontSaveRandomSeed()
  77. {
  78. SaveRandomSeed = false;
  79. }
  80. //---------------------------------------------------------------------------
  81. bool RandomSeedExists()
  82. {
  83. return
  84. !DeleteRandomSeedOnExit() &&
  85. FileExists(ApiPath(Configuration->RandomSeedFileName));
  86. }
  87. //---------------------------------------------------------------------------
  88. TSecureShell * GetSecureShell(Plug * plug, bool & pfwd)
  89. {
  90. if (!is_ssh(plug) && !is_pfwd(plug))
  91. {
  92. // If it is not SSH/PFwd plug, then it must be Proxy plug.
  93. // Get SSH/PFwd plug which it wraps.
  94. ProxySocket * AProxySocket = get_proxy_plug_socket(plug);
  95. plug = AProxySocket->plug;
  96. }
  97. pfwd = is_pfwd(plug);
  98. Seat * seat;
  99. if (pfwd)
  100. {
  101. seat = get_pfwd_seat(plug);
  102. }
  103. else
  104. {
  105. seat = get_ssh_seat(plug);
  106. }
  107. DebugAssert(seat != NULL);
  108. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  109. return SecureShell;
  110. }
  111. //---------------------------------------------------------------------------
  112. struct callback_set * get_callback_set(Plug * plug)
  113. {
  114. bool pfwd;
  115. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  116. return SecureShell->GetCallbackSet();
  117. }
  118. //---------------------------------------------------------------------------
  119. struct callback_set * get_seat_callback_set(Seat * seat)
  120. {
  121. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  122. return SecureShell->GetCallbackSet();
  123. }
  124. //---------------------------------------------------------------------------
  125. extern "C" const char * do_select(Plug * plug, SOCKET skt, bool enable)
  126. {
  127. bool pfwd;
  128. TSecureShell * SecureShell = GetSecureShell(plug, pfwd);
  129. if (!pfwd)
  130. {
  131. SecureShell->UpdateSocket(skt, enable);
  132. }
  133. else
  134. {
  135. SecureShell->UpdatePortFwdSocket(skt, enable);
  136. }
  137. return NULL;
  138. }
  139. //---------------------------------------------------------------------------
  140. static size_t output(Seat * seat, bool is_stderr, const void * data, size_t len)
  141. {
  142. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  143. if (static_cast<int>(static_cast<char>(is_stderr)) == -1)
  144. {
  145. SecureShell->CWrite(reinterpret_cast<const char *>(data), len);
  146. }
  147. else if (!is_stderr)
  148. {
  149. SecureShell->FromBackend(reinterpret_cast<const unsigned char *>(data), len);
  150. }
  151. else
  152. {
  153. SecureShell->AddStdError(reinterpret_cast<const char *>(data), len);
  154. }
  155. return 0;
  156. }
  157. //---------------------------------------------------------------------------
  158. static bool eof(Seat *)
  159. {
  160. return false;
  161. }
  162. //---------------------------------------------------------------------------
  163. static int get_userpass_input(Seat * seat, prompts_t * p, bufchain * DebugUsedArg(input))
  164. {
  165. DebugAssert(p != NULL);
  166. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  167. DebugAssert(SecureShell != NULL);
  168. int Result;
  169. TStrings * Prompts = new TStringList();
  170. TStrings * Results = new TStringList();
  171. try
  172. {
  173. UnicodeString Name = UTF8ToString(p->name);
  174. UnicodeString AName = Name;
  175. TPromptKind PromptKind = SecureShell->IdentifyPromptKind(AName);
  176. bool UTF8Prompt = (PromptKind != pkPassphrase);
  177. for (int Index = 0; Index < int(p->n_prompts); Index++)
  178. {
  179. prompt_t * Prompt = p->prompts[Index];
  180. UnicodeString S;
  181. if (UTF8Prompt)
  182. {
  183. S = UTF8ToString(Prompt->prompt);
  184. }
  185. else
  186. {
  187. S = UnicodeString(AnsiString(Prompt->prompt));
  188. }
  189. Prompts->AddObject(S, (TObject *)(FLAGMASK(Prompt->echo, pupEcho)));
  190. // this fails, when new passwords do not match on change password prompt,
  191. // and putty retries the prompt
  192. DebugAssert(strlen(prompt_get_result_ref(Prompt)) == 0);
  193. Results->Add(L"");
  194. }
  195. UnicodeString Instructions = UTF8ToString(p->instruction);
  196. if (SecureShell->PromptUser(p->to_server, Name, p->name_reqd,
  197. Instructions, p->instr_reqd, Prompts, Results))
  198. {
  199. for (int Index = 0; Index < int(p->n_prompts); Index++)
  200. {
  201. prompt_t * Prompt = p->prompts[Index];
  202. RawByteString S;
  203. if (UTF8Prompt)
  204. {
  205. S = RawByteString(UTF8String(Results->Strings[Index]));
  206. }
  207. else
  208. {
  209. S = RawByteString(AnsiString(Results->Strings[Index]));
  210. }
  211. prompt_set_result(Prompt, S.c_str());
  212. }
  213. Result = 1;
  214. }
  215. else
  216. {
  217. Result = 0;
  218. }
  219. }
  220. __finally
  221. {
  222. delete Prompts;
  223. delete Results;
  224. }
  225. return Result;
  226. }
  227. //---------------------------------------------------------------------------
  228. static void connection_fatal(Seat * seat, const char * message)
  229. {
  230. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  231. SecureShell->PuttyFatalError(UnicodeString(AnsiString(message)));
  232. }
  233. //---------------------------------------------------------------------------
  234. int verify_ssh_host_key(Seat * seat, const char * host, int port, const char * keytype,
  235. char * keystr, const char * DebugUsedArg(keydisp), char ** key_fingerprints,
  236. void (*DebugUsedArg(callback))(void *ctx, int result), void * DebugUsedArg(ctx))
  237. {
  238. UnicodeString FingerprintSHA256, FingerprintMD5;
  239. if (key_fingerprints[SSH_FPTYPE_SHA256] != NULL)
  240. {
  241. FingerprintSHA256 = key_fingerprints[SSH_FPTYPE_SHA256];
  242. }
  243. if (DebugAlwaysTrue(key_fingerprints[SSH_FPTYPE_MD5] != NULL))
  244. {
  245. FingerprintMD5 = key_fingerprints[SSH_FPTYPE_MD5];
  246. }
  247. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  248. SecureShell->VerifyHostKey(host, port, keytype, keystr, FingerprintSHA256, FingerprintMD5);
  249. // We should return 0 when key was not confirmed, we throw exception instead.
  250. return 1;
  251. }
  252. //---------------------------------------------------------------------------
  253. bool have_ssh_host_key(Seat * seat, const char * hostname, int port,
  254. const char * keytype)
  255. {
  256. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  257. return SecureShell->HaveHostKey(hostname, port, keytype) ? 1 : 0;
  258. }
  259. //---------------------------------------------------------------------------
  260. int confirm_weak_crypto_primitive(Seat * seat, const char * algtype, const char * algname,
  261. void (*/*callback*/)(void * ctx, int result), void * /*ctx*/)
  262. {
  263. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  264. SecureShell->AskAlg(algtype, algname);
  265. // We should return 0 when alg was not confirmed, we throw exception instead.
  266. return 1;
  267. }
  268. //---------------------------------------------------------------------------
  269. int confirm_weak_cached_hostkey(Seat *, const char * /*algname*/, const char * /*betteralgs*/,
  270. void (*/*callback*/)(void *ctx, int result), void * /*ctx*/)
  271. {
  272. return 1;
  273. }
  274. //---------------------------------------------------------------------------
  275. void old_keyfile_warning(void)
  276. {
  277. // no reference to TSecureShell instance available
  278. }
  279. //---------------------------------------------------------------------------
  280. void display_banner(Seat * seat, const char * banner, int size)
  281. {
  282. TSecureShell * SecureShell = static_cast<ScpSeat *>(seat)->SecureShell;
  283. UnicodeString Banner(UTF8String(banner, size));
  284. SecureShell->DisplayBanner(Banner);
  285. }
  286. //---------------------------------------------------------------------------
  287. static void SSHFatalError(const char * Format, va_list Param)
  288. {
  289. char Buf[200];
  290. vsnprintf(Buf, LENOF(Buf), Format, Param);
  291. Buf[LENOF(Buf) - 1] = '\0';
  292. // Only few calls from putty\winnet.c might be connected with specific
  293. // TSecureShell. Otherwise called only for really fatal errors
  294. // like 'out of memory' from putty\ssh.c.
  295. throw ESshFatal(NULL, Buf);
  296. }
  297. //---------------------------------------------------------------------------
  298. void modalfatalbox(const char * fmt, ...)
  299. {
  300. va_list Param;
  301. va_start(Param, fmt);
  302. SSHFatalError(fmt, Param);
  303. va_end(Param);
  304. }
  305. //---------------------------------------------------------------------------
  306. void nonfatal(const char * fmt, ...)
  307. {
  308. va_list Param;
  309. va_start(Param, fmt);
  310. SSHFatalError(fmt, Param);
  311. va_end(Param);
  312. }
  313. //---------------------------------------------------------------------------
  314. void ldisc_echoedit_update(Ldisc * /*handle*/)
  315. {
  316. DebugFail();
  317. }
  318. //---------------------------------------------------------------------------
  319. unsigned long schedule_timer(int ticks, timer_fn_t /*fn*/, void * /*ctx*/)
  320. {
  321. return ticks + GetTickCount();
  322. }
  323. //---------------------------------------------------------------------------
  324. void expire_timer_context(void * /*ctx*/)
  325. {
  326. // nothing
  327. }
  328. //---------------------------------------------------------------------------
  329. Pinger * pinger_new(Conf * /*conf*/, Backend * /*back*/)
  330. {
  331. return NULL;
  332. }
  333. //---------------------------------------------------------------------------
  334. void pinger_reconfig(Pinger * /*pinger*/, Conf * /*oldconf*/, Conf * /*newconf*/)
  335. {
  336. // nothing
  337. }
  338. //---------------------------------------------------------------------------
  339. void pinger_free(Pinger * /*pinger*/)
  340. {
  341. // nothing
  342. }
  343. //---------------------------------------------------------------------------
  344. void platform_get_x11_auth(struct X11Display * /*display*/, Conf * /*conf*/)
  345. {
  346. // nothing, therefore no auth.
  347. }
  348. //---------------------------------------------------------------------------
  349. // Based on PuTTY's settings.c
  350. char * get_remote_username(Conf * conf)
  351. {
  352. char * username = conf_get_str(conf, CONF_username);
  353. char * result;
  354. if (*username)
  355. {
  356. result = dupstr(username);
  357. }
  358. else
  359. {
  360. result = NULL;
  361. }
  362. return result;
  363. }
  364. //---------------------------------------------------------------------------
  365. static const SeatVtable ScpSeatVtable =
  366. {
  367. output,
  368. eof,
  369. get_userpass_input,
  370. nullseat_notify_remote_exit,
  371. connection_fatal,
  372. nullseat_update_specials_menu,
  373. nullseat_get_ttymode,
  374. nullseat_set_busy_status,
  375. verify_ssh_host_key,
  376. confirm_weak_crypto_primitive,
  377. confirm_weak_cached_hostkey,
  378. nullseat_is_always_utf8,
  379. nullseat_echoedit_update,
  380. nullseat_get_x_display,
  381. nullseat_get_windowid,
  382. nullseat_get_window_pixel_size,
  383. nullseat_stripctrl_new,
  384. nullseat_set_trust_status_vacuously,
  385. nullseat_verbose_yes,
  386. nullseat_interactive_no,
  387. nullseat_get_cursor_position,
  388. };
  389. //---------------------------------------------------------------------------
  390. ScpSeat::ScpSeat(TSecureShell * ASecureShell)
  391. {
  392. SecureShell = ASecureShell;
  393. vt = &ScpSeatVtable;
  394. }
  395. //---------------------------------------------------------------------------
  396. static std::unique_ptr<TCriticalSection> PuttyRegistrySection(TraceInitPtr(new TCriticalSection()));
  397. enum TPuttyRegistryMode { prmPass, prmRedirect, prmCollect, prmFail };
  398. static TPuttyRegistryMode PuttyRegistryMode = prmRedirect;
  399. typedef std::map<UnicodeString, unsigned long> TPuttyRegistryTypes;
  400. TPuttyRegistryTypes PuttyRegistryTypes;
  401. //---------------------------------------------------------------------------
  402. static long OpenWinSCPKey(HKEY Key, const char * SubKey, HKEY * Result, bool CanCreate)
  403. {
  404. long R;
  405. DebugAssert(Key == HKEY_CURRENT_USER);
  406. DebugUsedParam(Key);
  407. UnicodeString RegKey = SubKey;
  408. int PuttyKeyLen = OriginalPuttyRegistryStorageKey.Length();
  409. DebugAssert(RegKey.SubString(1, PuttyKeyLen) == OriginalPuttyRegistryStorageKey);
  410. RegKey = RegKey.SubString(PuttyKeyLen + 1, RegKey.Length() - PuttyKeyLen);
  411. if (!RegKey.IsEmpty())
  412. {
  413. DebugAssert(RegKey[1] == L'\\');
  414. RegKey.Delete(1, 1);
  415. }
  416. if (RegKey.IsEmpty())
  417. {
  418. *Result = static_cast<HKEY>(NULL);
  419. R = ERROR_SUCCESS;
  420. }
  421. else
  422. {
  423. // we expect this to be called only from retrieve_host_key() or store_host_key()
  424. DebugAssert(RegKey == L"SshHostKeys");
  425. DebugAssert(PuttyStorage != NULL);
  426. DebugAssert(PuttyStorage->AccessMode == (CanCreate ? smReadWrite : smRead));
  427. if (PuttyStorage->OpenSubKey(RegKey, CanCreate))
  428. {
  429. *Result = reinterpret_cast<HKEY>(PuttyStorage);
  430. R = ERROR_SUCCESS;
  431. }
  432. else
  433. {
  434. R = ERROR_CANTOPEN;
  435. }
  436. }
  437. return R;
  438. }
  439. //---------------------------------------------------------------------------
  440. long reg_open_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  441. {
  442. if (PuttyRegistryMode == prmPass)
  443. {
  444. return RegOpenKeyA(Key, SubKey, Result);
  445. }
  446. else if (PuttyRegistryMode == prmCollect)
  447. {
  448. *Result = reinterpret_cast<HKEY>(1);
  449. return ERROR_SUCCESS;
  450. }
  451. else if (PuttyRegistryMode == prmFail)
  452. {
  453. return ERROR_CANTOPEN;
  454. }
  455. DebugAssert(PuttyRegistryMode == prmRedirect);
  456. return OpenWinSCPKey(Key, SubKey, Result, false);
  457. }
  458. //---------------------------------------------------------------------------
  459. long reg_create_winscp_key(HKEY Key, const char * SubKey, HKEY * Result)
  460. {
  461. if (PuttyRegistryMode == prmPass)
  462. {
  463. return RegCreateKeyA(Key, SubKey, Result);
  464. }
  465. else if (PuttyRegistryMode == prmCollect)
  466. {
  467. *Result = reinterpret_cast<HKEY>(1);
  468. return ERROR_SUCCESS;
  469. }
  470. DebugAssert(PuttyRegistryMode == prmRedirect);
  471. return OpenWinSCPKey(Key, SubKey, Result, true);
  472. }
  473. //---------------------------------------------------------------------------
  474. long reg_query_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long * Reserved,
  475. unsigned long * Type, unsigned char * Data, unsigned long * DataSize)
  476. {
  477. if (PuttyRegistryMode == prmPass)
  478. {
  479. return RegQueryValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  480. }
  481. else if (PuttyRegistryMode == prmCollect)
  482. {
  483. return ERROR_READ_FAULT;
  484. }
  485. DebugAssert(PuttyRegistryMode == prmRedirect);
  486. long R;
  487. DebugAssert(Configuration != NULL);
  488. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  489. AnsiString Value;
  490. if (Storage == NULL)
  491. {
  492. if (UnicodeString(ValueName) == L"RandSeedFile")
  493. {
  494. Value = AnsiString(Configuration->RandomSeedFileName);
  495. R = ERROR_SUCCESS;
  496. }
  497. else
  498. {
  499. DebugFail();
  500. R = ERROR_READ_FAULT;
  501. }
  502. }
  503. else
  504. {
  505. if (Storage->ValueExists(ValueName))
  506. {
  507. Value = AnsiString(Storage->ReadStringRaw(ValueName, L""));
  508. R = ERROR_SUCCESS;
  509. }
  510. else
  511. {
  512. R = ERROR_READ_FAULT;
  513. }
  514. }
  515. if (R == ERROR_SUCCESS)
  516. {
  517. DebugAssert(Type != NULL);
  518. *Type = REG_SZ;
  519. char * DataStr = reinterpret_cast<char *>(Data);
  520. strncpy(DataStr, Value.c_str(), *DataSize);
  521. DataStr[*DataSize - 1] = '\0';
  522. *DataSize = strlen(DataStr);
  523. }
  524. return R;
  525. }
  526. //---------------------------------------------------------------------------
  527. long reg_set_winscp_value_ex(HKEY Key, const char * ValueName, unsigned long Reserved,
  528. unsigned long Type, const unsigned char * Data, unsigned long DataSize)
  529. {
  530. if (PuttyRegistryMode == prmPass)
  531. {
  532. return RegSetValueExA(Key, ValueName, Reserved, Type, Data, DataSize);
  533. }
  534. else if (PuttyRegistryMode == prmCollect)
  535. {
  536. PuttyRegistryTypes[ValueName] = Type;
  537. return ERROR_SUCCESS;
  538. }
  539. DebugAssert(PuttyRegistryMode == prmRedirect);
  540. DebugAssert(Type == REG_SZ);
  541. DebugUsedParam(Type);
  542. THierarchicalStorage * Storage = reinterpret_cast<THierarchicalStorage *>(Key);
  543. DebugAssert(Storage != NULL);
  544. if (Storage != NULL)
  545. {
  546. UnicodeString Value(reinterpret_cast<const char*>(Data), DataSize - 1);
  547. Storage->WriteStringRaw(ValueName, Value);
  548. }
  549. return ERROR_SUCCESS;
  550. }
  551. //---------------------------------------------------------------------------
  552. long reg_close_winscp_key(HKEY Key)
  553. {
  554. if (PuttyRegistryMode == prmPass)
  555. {
  556. return RegCloseKey(Key);
  557. }
  558. else if (PuttyRegistryMode == prmCollect)
  559. {
  560. return ERROR_SUCCESS;
  561. }
  562. DebugAssert(PuttyRegistryMode == prmRedirect);
  563. return ERROR_SUCCESS;
  564. }
  565. //---------------------------------------------------------------------------
  566. TKeyType KeyType(UnicodeString FileName)
  567. {
  568. DebugAssert(ktUnopenable == SSH_KEYTYPE_UNOPENABLE);
  569. DebugAssert(ktSSHCom == SSH_KEYTYPE_SSHCOM);
  570. DebugAssert(ktSSH2PublicOpenSSH == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH);
  571. UTF8String UtfFileName = UTF8String(FileName);
  572. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  573. TKeyType Result = (TKeyType)key_type(KeyFile);
  574. filename_free(KeyFile);
  575. return Result;
  576. }
  577. //---------------------------------------------------------------------------
  578. bool IsKeyEncrypted(TKeyType KeyType, const UnicodeString & FileName, UnicodeString & Comment)
  579. {
  580. UTF8String UtfFileName = UTF8String(FileName);
  581. bool Result;
  582. char * CommentStr = NULL;
  583. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  584. try
  585. {
  586. switch (KeyType)
  587. {
  588. case ktSSH2:
  589. Result = (ppk_encrypted_f(KeyFile, &CommentStr) != 0);
  590. break;
  591. case ktOpenSSHPEM:
  592. case ktOpenSSHNew:
  593. case ktSSHCom:
  594. Result = (import_encrypted(KeyFile, KeyType, &CommentStr) != NULL);
  595. break;
  596. default:
  597. DebugFail();
  598. Result = false;
  599. break;
  600. }
  601. }
  602. __finally
  603. {
  604. filename_free(KeyFile);
  605. }
  606. if (CommentStr != NULL)
  607. {
  608. Comment = UnicodeString(AnsiString(CommentStr));
  609. // ktOpenSSH has no comment, PuTTY defaults to file path
  610. if (Comment == FileName)
  611. {
  612. Comment = ExtractFileName(FileName);
  613. }
  614. sfree(CommentStr);
  615. }
  616. return Result;
  617. }
  618. //---------------------------------------------------------------------------
  619. TPrivateKey * LoadKey(TKeyType KeyType, const UnicodeString & FileName, const UnicodeString & Passphrase)
  620. {
  621. UTF8String UtfFileName = UTF8String(FileName);
  622. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  623. struct ssh2_userkey * Ssh2Key = NULL;
  624. const char * ErrorStr = NULL;
  625. AnsiString AnsiPassphrase = Passphrase;
  626. try
  627. {
  628. switch (KeyType)
  629. {
  630. case ktSSH2:
  631. Ssh2Key = ppk_load_f(KeyFile, AnsiPassphrase.c_str(), &ErrorStr);
  632. break;
  633. case ktOpenSSHPEM:
  634. case ktOpenSSHNew:
  635. case ktSSHCom:
  636. Ssh2Key = import_ssh2(KeyFile, KeyType, AnsiPassphrase.c_str(), &ErrorStr);
  637. break;
  638. default:
  639. DebugFail();
  640. break;
  641. }
  642. }
  643. __finally
  644. {
  645. Shred(AnsiPassphrase);
  646. filename_free(KeyFile);
  647. }
  648. if (Ssh2Key == NULL)
  649. {
  650. UnicodeString Error = AnsiString(ErrorStr);
  651. // While theoretically we may get "unable to open key file" and
  652. // so we should check system error code,
  653. // we actully never get here unless we call KeyType previously
  654. // and handle ktUnopenable accordingly.
  655. throw Exception(Error);
  656. }
  657. else if (Ssh2Key == SSH2_WRONG_PASSPHRASE)
  658. {
  659. throw Exception(LoadStr(AUTH_TRANSL_WRONG_PASSPHRASE));
  660. }
  661. return reinterpret_cast<TPrivateKey *>(Ssh2Key);
  662. }
  663. //---------------------------------------------------------------------------
  664. void ChangeKeyComment(TPrivateKey * PrivateKey, const UnicodeString & Comment)
  665. {
  666. AnsiString AnsiComment(Comment);
  667. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  668. sfree(Ssh2Key->comment);
  669. Ssh2Key->comment = dupstr(AnsiComment.c_str());
  670. }
  671. //---------------------------------------------------------------------------
  672. void SaveKey(TKeyType KeyType, const UnicodeString & FileName,
  673. const UnicodeString & Passphrase, TPrivateKey * PrivateKey)
  674. {
  675. UTF8String UtfFileName = UTF8String(FileName);
  676. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  677. try
  678. {
  679. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  680. AnsiString AnsiPassphrase = Passphrase;
  681. char * PassphrasePtr = (AnsiPassphrase.IsEmpty() ? NULL : AnsiPassphrase.c_str());
  682. switch (KeyType)
  683. {
  684. case ktSSH2:
  685. {
  686. ppk_save_parameters Params = ppk_save_default_parameters;
  687. if (Configuration->KeyVersion != 0)
  688. {
  689. Params.fmt_version = Configuration->KeyVersion;
  690. }
  691. if (!ppk_save_f(KeyFile, Ssh2Key, PassphrasePtr, &Params))
  692. {
  693. int Error = errno;
  694. throw EOSExtException(FMTLOAD(KEY_SAVE_ERROR, (FileName)), Error);
  695. }
  696. }
  697. break;
  698. default:
  699. DebugFail();
  700. break;
  701. }
  702. }
  703. __finally
  704. {
  705. filename_free(KeyFile);
  706. }
  707. }
  708. //---------------------------------------------------------------------------
  709. void FreeKey(TPrivateKey * PrivateKey)
  710. {
  711. struct ssh2_userkey * Ssh2Key = reinterpret_cast<struct ssh2_userkey *>(PrivateKey);
  712. ssh_key_free(Ssh2Key->key);
  713. sfree(Ssh2Key->comment);
  714. sfree(Ssh2Key);
  715. }
  716. //---------------------------------------------------------------------------
  717. RawByteString LoadPublicKey(const UnicodeString & FileName, UnicodeString & Algorithm, UnicodeString & Comment)
  718. {
  719. RawByteString Result;
  720. UTF8String UtfFileName = UTF8String(FileName);
  721. Filename * KeyFile = filename_from_str(UtfFileName.c_str());
  722. try
  723. {
  724. char * AlgorithmStr = NULL;
  725. char * CommentStr = NULL;
  726. const char * ErrorStr = NULL;
  727. strbuf * PublicKeyBuf = strbuf_new();
  728. if (!ppk_loadpub_f(KeyFile, &AlgorithmStr, BinarySink_UPCAST(PublicKeyBuf), &CommentStr, &ErrorStr))
  729. {
  730. UnicodeString Error = UnicodeString(AnsiString(ErrorStr));
  731. throw Exception(Error);
  732. }
  733. Algorithm = UnicodeString(AnsiString(AlgorithmStr));
  734. sfree(AlgorithmStr);
  735. Comment = UnicodeString(AnsiString(CommentStr));
  736. sfree(CommentStr);
  737. Result = RawByteString(reinterpret_cast<char *>(PublicKeyBuf->s), PublicKeyBuf->len);
  738. strbuf_free(PublicKeyBuf);
  739. }
  740. __finally
  741. {
  742. filename_free(KeyFile);
  743. }
  744. return Result;
  745. }
  746. //---------------------------------------------------------------------------
  747. UnicodeString GetPublicKeyLine(const UnicodeString & FileName, UnicodeString & Comment)
  748. {
  749. UnicodeString Algorithm;
  750. RawByteString PublicKey = LoadPublicKey(FileName, Algorithm, Comment);
  751. UnicodeString PublicKeyBase64 = EncodeBase64(PublicKey.c_str(), PublicKey.Length());
  752. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\r", L"");
  753. PublicKeyBase64 = ReplaceStr(PublicKeyBase64, L"\n", L"");
  754. UnicodeString Result = FORMAT(L"%s %s %s", (Algorithm, PublicKeyBase64, Comment));
  755. return Result;
  756. }
  757. //---------------------------------------------------------------------------
  758. bool __fastcall HasGSSAPI(UnicodeString CustomPath)
  759. {
  760. static int has = -1;
  761. if (has < 0)
  762. {
  763. Conf * conf = conf_new();
  764. ssh_gss_liblist * List = NULL;
  765. try
  766. {
  767. Filename * filename = filename_from_str(UTF8String(CustomPath).c_str());
  768. conf_set_filename(conf, CONF_ssh_gss_custom, filename);
  769. filename_free(filename);
  770. List = ssh_gss_setup(conf, NULL);
  771. for (int Index = 0; (has <= 0) && (Index < List->nlibraries); Index++)
  772. {
  773. ssh_gss_library * library = &List->libraries[Index];
  774. Ssh_gss_ctx ctx;
  775. memset(&ctx, 0, sizeof(ctx));
  776. has =
  777. ((library->acquire_cred(library, &ctx, NULL) == SSH_GSS_OK) &&
  778. (library->release_cred(library, &ctx) == SSH_GSS_OK)) ? 1 : 0;
  779. }
  780. }
  781. __finally
  782. {
  783. ssh_gss_cleanup(List);
  784. conf_free(conf);
  785. }
  786. if (has < 0)
  787. {
  788. has = 0;
  789. }
  790. }
  791. return (has > 0);
  792. }
  793. //---------------------------------------------------------------------------
  794. static void __fastcall DoNormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName, UnicodeString & KeyType)
  795. {
  796. const int MaxCount = 10;
  797. const ssh_keyalg * SignKeys[MaxCount];
  798. int Count = LENOF(SignKeys);
  799. // We may use find_pubkey_alg, but it gets complicated with normalized fingerprint
  800. // as the names have different number of dashes
  801. get_hostkey_algs(&Count, SignKeys);
  802. for (int Index = 0; Index < Count; Index++)
  803. {
  804. const ssh_keyalg * SignKey = SignKeys[Index];
  805. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  806. if (StartsStr(Name + L" ", Fingerprint))
  807. {
  808. UnicodeString Rest = Fingerprint.SubString(Name.Length() + 2, Fingerprint.Length() - Name.Length() - 1);
  809. int Space = Rest.Pos(L" ");
  810. // If not a number, it's an invalid input,
  811. // either something completelly wrong, or it can be OpenSSH base64 public key,
  812. // that got here from TPasteKeyHandler::Paste
  813. if (IsNumber(Rest.SubString(1, Space - 1)))
  814. {
  815. KeyName = Name;
  816. Fingerprint = Rest.SubString(Space + 1, Fingerprint.Length() - Space);
  817. Fingerprint = Base64ToUrlSafe(Fingerprint);
  818. Fingerprint = MD5ToUrlSafe(Fingerprint);
  819. KeyType = UnicodeString(SignKey->cache_id);
  820. return;
  821. }
  822. }
  823. else if (StartsStr(Name + NormalizedFingerprintSeparator, Fingerprint))
  824. {
  825. KeyType = UnicodeString(SignKey->cache_id);
  826. KeyName = Name;
  827. Fingerprint.Delete(1, Name.Length() + 1);
  828. return;
  829. }
  830. }
  831. }
  832. //---------------------------------------------------------------------------
  833. void __fastcall NormalizeFingerprint(UnicodeString & Fingerprint, UnicodeString & KeyName)
  834. {
  835. UnicodeString KeyType;
  836. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  837. }
  838. //---------------------------------------------------------------------------
  839. UnicodeString __fastcall KeyTypeFromFingerprint(UnicodeString Fingerprint)
  840. {
  841. UnicodeString KeyType;
  842. UnicodeString KeyName; // unused
  843. DoNormalizeFingerprint(Fingerprint, KeyName, KeyType);
  844. return KeyType;
  845. }
  846. //---------------------------------------------------------------------------
  847. UnicodeString __fastcall GetPuTTYVersion()
  848. {
  849. // "Release 0.64"
  850. // "Pre-release 0.65:2015-07-20.95501a1"
  851. // "Development snapshot 2015-12-22.51465fa"
  852. UnicodeString Result = get_putty_version();
  853. // Skip "Release", "Pre-release", "Development snapshot"
  854. int P = Result.LastDelimiter(L" ");
  855. Result.Delete(1, P);
  856. return Result;
  857. }
  858. //---------------------------------------------------------------------------
  859. UnicodeString __fastcall Sha256(const char * Data, size_t Size)
  860. {
  861. unsigned char Digest[32];
  862. hash_simple(&ssh_sha256, make_ptrlen(Data, Size), Digest);
  863. UnicodeString Result(BytesToHex(Digest, LENOF(Digest)));
  864. return Result;
  865. }
  866. //---------------------------------------------------------------------------
  867. void __fastcall DllHijackingProtection()
  868. {
  869. dll_hijacking_protection();
  870. }
  871. //---------------------------------------------------------------------------
  872. UnicodeString __fastcall ParseOpenSshPubLine(const UnicodeString & Line, const struct ssh_keyalg *& Algorithm)
  873. {
  874. UTF8String UtfLine = UTF8String(Line);
  875. char * AlgorithmName = NULL;
  876. char * CommentPtr = NULL;
  877. const char * ErrorStr = NULL;
  878. strbuf * PubBlobBuf = strbuf_new();
  879. BinarySource Source[1];
  880. BinarySource_BARE_INIT(Source, UtfLine.c_str(), UtfLine.Length());
  881. UnicodeString Result;
  882. if (!openssh_loadpub(Source, &AlgorithmName, BinarySink_UPCAST(PubBlobBuf), &CommentPtr, &ErrorStr))
  883. {
  884. throw Exception(UnicodeString(ErrorStr));
  885. }
  886. else
  887. {
  888. try
  889. {
  890. Algorithm = find_pubkey_alg(AlgorithmName);
  891. if (Algorithm == NULL)
  892. {
  893. throw Exception(FORMAT(L"Unknown public key algorithm \"%s\".", (AlgorithmName)));
  894. }
  895. ptrlen PtrLen = { PubBlobBuf->s, PubBlobBuf->len };
  896. ssh_key * Key = Algorithm->new_pub(Algorithm, PtrLen);
  897. if (Key == NULL)
  898. {
  899. throw Exception(L"Invalid public key.");
  900. }
  901. char * FmtKey = Algorithm->cache_str(Key);
  902. Result = UnicodeString(FmtKey);
  903. sfree(FmtKey);
  904. Algorithm->freekey(Key);
  905. }
  906. __finally
  907. {
  908. strbuf_free(PubBlobBuf);
  909. sfree(AlgorithmName);
  910. sfree(CommentPtr);
  911. }
  912. }
  913. return Result;
  914. }
  915. //---------------------------------------------------------------------------
  916. UnicodeString __fastcall GetKeyTypeHuman(const UnicodeString & KeyType)
  917. {
  918. UnicodeString Result;
  919. if (KeyType == ssh_dss.cache_id)
  920. {
  921. Result = L"DSA";
  922. }
  923. else if ((KeyType == ssh_rsa.cache_id) ||
  924. (KeyType == L"rsa")) // SSH1
  925. {
  926. Result = L"RSA";
  927. }
  928. else if (KeyType == ssh_ecdsa_ed25519.cache_id)
  929. {
  930. Result = L"Ed25519";
  931. }
  932. else if (KeyType == ssh_ecdsa_nistp256.cache_id)
  933. {
  934. Result = L"ECDSA/nistp256";
  935. }
  936. else if (KeyType == ssh_ecdsa_nistp384.cache_id)
  937. {
  938. Result = L"ECDSA/nistp384";
  939. }
  940. else if (KeyType == ssh_ecdsa_nistp521.cache_id)
  941. {
  942. Result = L"ECDSA/nistp521";
  943. }
  944. else
  945. {
  946. DebugFail();
  947. Result = KeyType;
  948. }
  949. return Result;
  950. }
  951. //---------------------------------------------------------------------------
  952. bool IsOpenSSH(const UnicodeString & SshImplementation)
  953. {
  954. return
  955. // e.g. "OpenSSH_5.3"
  956. (SshImplementation.Pos(L"OpenSSH") == 1) ||
  957. // Sun SSH is based on OpenSSH (suffers the same bugs)
  958. (SshImplementation.Pos(L"Sun_SSH") == 1);
  959. }
  960. //---------------------------------------------------------------------------
  961. TStrings * SshCipherList()
  962. {
  963. std::unique_ptr<TStrings> Result(new TStringList());
  964. // Same order as DefaultCipherList
  965. const ssh2_ciphers * Ciphers[] = { &ssh2_aes, &ssh2_ccp, &ssh2_blowfish, &ssh2_3des, &ssh2_arcfour, &ssh2_des };
  966. for (unsigned int Index = 0; Index < LENOF(Ciphers); Index++)
  967. {
  968. for (int Index2 = 0; Index2 < Ciphers[Index]->nciphers; Index2++)
  969. {
  970. UnicodeString Name = UnicodeString(Ciphers[Index]->list[Index2]->ssh2_id);
  971. Result->Add(Name);
  972. }
  973. }
  974. return Result.release();
  975. }
  976. //---------------------------------------------------------------------------
  977. TStrings * SshKexList()
  978. {
  979. std::unique_ptr<TStrings> Result(new TStringList());
  980. // Same order as DefaultKexList
  981. const ssh_kexes * Kexes[] = { &ssh_ecdh_kex, &ssh_diffiehellman_gex, &ssh_diffiehellman_group14, &ssh_rsa_kex, &ssh_diffiehellman_group1 };
  982. for (unsigned int Index = 0; Index < LENOF(Kexes); Index++)
  983. {
  984. for (int Index2 = 0; Index2 < Kexes[Index]->nkexes; Index2++)
  985. {
  986. UnicodeString Name = UnicodeString(Kexes[Index]->list[Index2]->name);
  987. Result->Add(Name);
  988. }
  989. }
  990. return Result.release();
  991. }
  992. //---------------------------------------------------------------------------
  993. TStrings * SshHostKeyList()
  994. {
  995. std::unique_ptr<TStrings> Result(new TStringList());
  996. const int MaxCount = 10;
  997. const ssh_keyalg * SignKeys[MaxCount];
  998. int Count = LENOF(SignKeys);
  999. get_hostkey_algs(&Count, SignKeys);
  1000. for (int Index = 0; Index < Count; Index++)
  1001. {
  1002. const ssh_keyalg * SignKey = SignKeys[Index];
  1003. UnicodeString Name = UnicodeString(SignKey->ssh_id);
  1004. Result->Add(Name);
  1005. }
  1006. return Result.release();
  1007. }
  1008. //---------------------------------------------------------------------------
  1009. TStrings * SshMacList()
  1010. {
  1011. std::unique_ptr<TStrings> Result(new TStringList());
  1012. const struct ssh2_macalg ** Macs = NULL;
  1013. int Count = 0;
  1014. get_macs(&Count, &Macs);
  1015. for (int Index = 0; Index < Count; Index++)
  1016. {
  1017. UnicodeString Name = UnicodeString(Macs[Index]->name);
  1018. UnicodeString S = Name;
  1019. UnicodeString ETMName = UnicodeString(Macs[Index]->etm_name);
  1020. if (!ETMName.IsEmpty())
  1021. {
  1022. S = FORMAT(L"%s (%s)", (S, ETMName));
  1023. }
  1024. Result->Add(S);
  1025. }
  1026. return Result.release();
  1027. }
  1028. //---------------------------------------------------------------------------
  1029. UnicodeString GetCipherName(const ssh_cipher * Cipher)
  1030. {
  1031. return UnicodeString(UTF8String(Cipher->vt->text_name));
  1032. }
  1033. //---------------------------------------------------------------------------
  1034. UnicodeString GetCompressorName(const ssh_compressor * Compressor)
  1035. {
  1036. UnicodeString Result;
  1037. if (Compressor != NULL)
  1038. {
  1039. Result = UnicodeString(UTF8String(Compressor->vt->name));
  1040. }
  1041. return Result;
  1042. }
  1043. //---------------------------------------------------------------------------
  1044. UnicodeString GetDecompressorName(const ssh_decompressor * Decompressor)
  1045. {
  1046. UnicodeString Result;
  1047. if (Decompressor != NULL)
  1048. {
  1049. Result = UnicodeString(UTF8String(Decompressor->vt->name));
  1050. }
  1051. return Result;
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void WritePuttySettings(THierarchicalStorage * Storage, const UnicodeString & ASettings)
  1055. {
  1056. if (PuttyRegistryTypes.empty())
  1057. {
  1058. TGuard Guard(PuttyRegistrySection.get());
  1059. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1060. PuttyRegistryMode = prmCollect;
  1061. Conf * conf = conf_new();
  1062. try
  1063. {
  1064. do_defaults(NULL, conf);
  1065. save_settings(NULL, conf);
  1066. }
  1067. __finally
  1068. {
  1069. conf_free(conf);
  1070. }
  1071. }
  1072. std::unique_ptr<TStrings> Settings(new TStringList());
  1073. UnicodeString Buf = ASettings;
  1074. UnicodeString Setting;
  1075. while (CutToken(Buf, Setting))
  1076. {
  1077. Settings->Add(Setting);
  1078. }
  1079. for (int Index = 0; Index < Settings->Count; Index++)
  1080. {
  1081. UnicodeString Name = Settings->Names[Index];
  1082. TPuttyRegistryTypes::const_iterator IType = PuttyRegistryTypes.find(Name);
  1083. if (IType != PuttyRegistryTypes.end())
  1084. {
  1085. UnicodeString Value = Settings->ValueFromIndex[Index];
  1086. int I;
  1087. if (IType->second == REG_SZ)
  1088. {
  1089. Storage->WriteStringRaw(Name, Value);
  1090. }
  1091. else if (DebugAlwaysTrue(IType->second == REG_DWORD) &&
  1092. TryStrToInt(Value, I))
  1093. {
  1094. Storage->WriteInteger(Name, I);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. void PuttyDefaults(Conf * conf)
  1101. {
  1102. TGuard Guard(PuttyRegistrySection.get());
  1103. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1104. PuttyRegistryMode = prmFail;
  1105. do_defaults(NULL, conf);
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void SavePuttyDefaults(const UnicodeString & Name)
  1109. {
  1110. TGuard Guard(PuttyRegistrySection.get());
  1111. TValueRestorer<TPuttyRegistryMode> PuttyRegistryModeRestorer(PuttyRegistryMode);
  1112. PuttyRegistryMode = prmPass;
  1113. Conf * conf = conf_new();
  1114. try
  1115. {
  1116. PuttyDefaults(conf);
  1117. AnsiString PuttyName = PuttyStr(Name);
  1118. save_settings(PuttyName.c_str(), conf);
  1119. }
  1120. __finally
  1121. {
  1122. conf_free(conf);
  1123. }
  1124. }
  1125. //---------------------------------------------------------------------------
  1126. //---------------------------------------------------------------------------