pageant.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  1. /*
  2. * Pageant: the PuTTY Authentication Agent.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stddef.h>
  7. #include <ctype.h>
  8. #include <assert.h>
  9. #include <tchar.h>
  10. #include "putty.h"
  11. #include "ssh.h"
  12. #include "misc.h"
  13. #include "tree234.h"
  14. #include "security-api.h"
  15. #include "cryptoapi.h"
  16. #include "pageant.h"
  17. #include "licence.h"
  18. #include "pageant-rc.h"
  19. #include <shellapi.h>
  20. #include <aclapi.h>
  21. #ifdef DEBUG_IPC
  22. #define _WIN32_WINNT 0x0500 /* for ConvertSidToStringSid */
  23. #include <sddl.h>
  24. #endif
  25. #define WM_SYSTRAY (WM_APP + 6)
  26. #define WM_SYSTRAY2 (WM_APP + 7)
  27. #define APPNAME "Pageant"
  28. /* Titles and class names for invisible windows. IPCWINTITLE and
  29. * IPCCLASSNAME are critical to backwards compatibility: WM_COPYDATA
  30. * based Pageant clients will call FindWindow with those parameters
  31. * and expect to find the Pageant IPC receiver. */
  32. #define TRAYWINTITLE "Pageant"
  33. #define TRAYCLASSNAME "PageantSysTray"
  34. #define IPCWINTITLE "Pageant"
  35. #define IPCCLASSNAME "Pageant"
  36. static HWND traywindow;
  37. static HWND keylist;
  38. static HWND aboutbox;
  39. static HMENU systray_menu, session_menu;
  40. static bool already_running;
  41. static FingerprintType fptype = SSH_FPTYPE_DEFAULT;
  42. static char *putty_path;
  43. static bool restrict_putty_acl = false;
  44. /* CWD for "add key" file requester. */
  45. static filereq *keypath = NULL;
  46. /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
  47. * wParam are used by Windows, and should be masked off, so we shouldn't
  48. * attempt to store information in them. Hence all these identifiers have
  49. * the low 4 bits clear. Also, identifiers should < 0xF000. */
  50. #define IDM_CLOSE 0x0010
  51. #define IDM_VIEWKEYS 0x0020
  52. #define IDM_ADDKEY 0x0030
  53. #define IDM_ADDKEY_ENCRYPTED 0x0040
  54. #define IDM_REMOVE_ALL 0x0050
  55. #define IDM_REENCRYPT_ALL 0x0060
  56. #define IDM_HELP 0x0070
  57. #define IDM_ABOUT 0x0080
  58. #define IDM_PUTTY 0x0090
  59. #define IDM_SESSIONS_BASE 0x1000
  60. #define IDM_SESSIONS_MAX 0x2000
  61. #define PUTTY_REGKEY "Software\\SimonTatham\\PuTTY\\Sessions"
  62. #define PUTTY_DEFAULT "Default%20Settings"
  63. static int initial_menuitems_count;
  64. /*
  65. * Print a modal (Really Bad) message box and perform a fatal exit.
  66. */
  67. void modalfatalbox(const char *fmt, ...)
  68. {
  69. va_list ap;
  70. char *buf;
  71. va_start(ap, fmt);
  72. buf = dupvprintf(fmt, ap);
  73. va_end(ap);
  74. MessageBox(traywindow, buf, "Pageant Fatal Error",
  75. MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
  76. sfree(buf);
  77. exit(1);
  78. }
  79. struct PassphraseProcStruct {
  80. bool modal;
  81. const char *help_topic;
  82. PageantClientDialogId *dlgid;
  83. char *passphrase;
  84. const char *comment;
  85. };
  86. /*
  87. * Dialog-box function for the Licence box.
  88. */
  89. static INT_PTR CALLBACK LicenceProc(HWND hwnd, UINT msg,
  90. WPARAM wParam, LPARAM lParam)
  91. {
  92. switch (msg) {
  93. case WM_INITDIALOG:
  94. SetDlgItemText(hwnd, IDC_LICENCE_TEXTBOX, LICENCE_TEXT("\r\n\r\n"));
  95. return 1;
  96. case WM_COMMAND:
  97. switch (LOWORD(wParam)) {
  98. case IDOK:
  99. case IDCANCEL:
  100. EndDialog(hwnd, 1);
  101. return 0;
  102. }
  103. return 0;
  104. case WM_CLOSE:
  105. EndDialog(hwnd, 1);
  106. return 0;
  107. }
  108. return 0;
  109. }
  110. /*
  111. * Dialog-box function for the About box.
  112. */
  113. static INT_PTR CALLBACK AboutProc(HWND hwnd, UINT msg,
  114. WPARAM wParam, LPARAM lParam)
  115. {
  116. switch (msg) {
  117. case WM_INITDIALOG: {
  118. char *buildinfo_text = buildinfo("\r\n");
  119. char *text = dupprintf(
  120. "Pageant\r\n\r\n%s\r\n\r\n%s\r\n\r\n%s",
  121. ver, buildinfo_text,
  122. "\251 " SHORT_COPYRIGHT_DETAILS ". All rights reserved.");
  123. sfree(buildinfo_text);
  124. SetDlgItemText(hwnd, IDC_ABOUT_TEXTBOX, text);
  125. MakeDlgItemBorderless(hwnd, IDC_ABOUT_TEXTBOX);
  126. sfree(text);
  127. return 1;
  128. }
  129. case WM_COMMAND:
  130. switch (LOWORD(wParam)) {
  131. case IDOK:
  132. case IDCANCEL:
  133. aboutbox = NULL;
  134. DestroyWindow(hwnd);
  135. return 0;
  136. case IDC_ABOUT_LICENCE:
  137. EnableWindow(hwnd, 0);
  138. DialogBox(hinst, MAKEINTRESOURCE(IDD_LICENCE), hwnd, LicenceProc);
  139. EnableWindow(hwnd, 1);
  140. SetActiveWindow(hwnd);
  141. return 0;
  142. case IDC_ABOUT_WEBSITE:
  143. /* Load web browser */
  144. ShellExecute(hwnd, "open",
  145. "https://www.chiark.greenend.org.uk/~sgtatham/putty/",
  146. 0, 0, SW_SHOWDEFAULT);
  147. return 0;
  148. }
  149. return 0;
  150. case WM_CLOSE:
  151. aboutbox = NULL;
  152. DestroyWindow(hwnd);
  153. return 0;
  154. }
  155. return 0;
  156. }
  157. static HWND modal_passphrase_hwnd = NULL;
  158. static HWND nonmodal_passphrase_hwnd = NULL;
  159. static void end_passphrase_dialog(HWND hwnd, INT_PTR result)
  160. {
  161. struct PassphraseProcStruct *p = (struct PassphraseProcStruct *)
  162. GetWindowLongPtr(hwnd, GWLP_USERDATA);
  163. if (p->modal) {
  164. EndDialog(hwnd, result);
  165. } else {
  166. /*
  167. * Destroy this passphrase dialog box before passing the
  168. * results back to the main pageant.c, to avoid re-entrancy
  169. * issues.
  170. *
  171. * If we successfully got a passphrase from the user, but it
  172. * was _wrong_, then pageant_passphrase_request_success will
  173. * respond by calling back - synchronously - to our
  174. * ask_passphrase() implementation, which will expect the
  175. * previous value of nonmodal_passphrase_hwnd to have already
  176. * been cleaned up.
  177. */
  178. SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) NULL);
  179. DestroyWindow(hwnd);
  180. nonmodal_passphrase_hwnd = NULL;
  181. if (result)
  182. pageant_passphrase_request_success(
  183. p->dlgid, ptrlen_from_asciz(p->passphrase));
  184. else
  185. pageant_passphrase_request_refused(p->dlgid);
  186. burnstr(p->passphrase);
  187. sfree(p);
  188. }
  189. }
  190. /*
  191. * Dialog-box function for the passphrase box.
  192. */
  193. static INT_PTR CALLBACK PassphraseProc(HWND hwnd, UINT msg,
  194. WPARAM wParam, LPARAM lParam)
  195. {
  196. struct PassphraseProcStruct *p;
  197. if (msg == WM_INITDIALOG) {
  198. p = (struct PassphraseProcStruct *) lParam;
  199. SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) p);
  200. } else {
  201. p = (struct PassphraseProcStruct *)
  202. GetWindowLongPtr(hwnd, GWLP_USERDATA);
  203. }
  204. switch (msg) {
  205. case WM_INITDIALOG: {
  206. if (p->modal)
  207. modal_passphrase_hwnd = hwnd;
  208. /*
  209. * Centre the window.
  210. */
  211. RECT rs, rd;
  212. HWND hw;
  213. hw = GetDesktopWindow();
  214. if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
  215. MoveWindow(hwnd,
  216. (rs.right + rs.left + rd.left - rd.right) / 2,
  217. (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
  218. rd.right - rd.left, rd.bottom - rd.top, true);
  219. SetForegroundWindow(hwnd);
  220. SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
  221. SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
  222. if (!p->modal)
  223. SetActiveWindow(hwnd); /* this won't have happened automatically */
  224. if (p->comment)
  225. SetDlgItemText(hwnd, IDC_PASSPHRASE_FINGERPRINT, p->comment);
  226. burnstr(p->passphrase);
  227. p->passphrase = dupstr("");
  228. SetDlgItemText(hwnd, IDC_PASSPHRASE_EDITBOX, p->passphrase);
  229. if (!p->help_topic || !has_help()) {
  230. HWND item = GetDlgItem(hwnd, IDHELP);
  231. if (item)
  232. DestroyWindow(item);
  233. }
  234. return 0;
  235. }
  236. case WM_COMMAND:
  237. switch (LOWORD(wParam)) {
  238. case IDOK:
  239. if (p->passphrase)
  240. end_passphrase_dialog(hwnd, 1);
  241. else
  242. MessageBeep(0);
  243. return 0;
  244. case IDCANCEL:
  245. end_passphrase_dialog(hwnd, 0);
  246. return 0;
  247. case IDHELP:
  248. if (p->help_topic)
  249. launch_help(hwnd, p->help_topic);
  250. return 0;
  251. case IDC_PASSPHRASE_EDITBOX:
  252. if ((HIWORD(wParam) == EN_CHANGE) && p->passphrase) {
  253. burnstr(p->passphrase);
  254. p->passphrase = GetDlgItemText_alloc(
  255. hwnd, IDC_PASSPHRASE_EDITBOX);
  256. }
  257. return 0;
  258. }
  259. return 0;
  260. case WM_CLOSE:
  261. end_passphrase_dialog(hwnd, 0);
  262. return 0;
  263. }
  264. return 0;
  265. }
  266. /*
  267. * Warn about the obsolescent key file format.
  268. */
  269. void old_keyfile_warning(void)
  270. {
  271. static const char mbtitle[] = "PuTTY Key File Warning";
  272. static const char message[] =
  273. "You are loading an SSH-2 private key which has an\n"
  274. "old version of the file format. This means your key\n"
  275. "file is not fully tamperproof. Future versions of\n"
  276. "PuTTY may stop supporting this private key format,\n"
  277. "so we recommend you convert your key to the new\n"
  278. "format.\n"
  279. "\n"
  280. "You can perform this conversion by loading the key\n"
  281. "into PuTTYgen and then saving it again.";
  282. MessageBox(NULL, message, mbtitle, MB_OK);
  283. }
  284. struct keylist_update_ctx {
  285. HDC hdc;
  286. int algbitswidth, algwidth, bitswidth, hashwidth;
  287. bool enable_remove_controls;
  288. bool enable_reencrypt_controls;
  289. };
  290. struct keylist_display_data {
  291. strbuf *alg, *bits, *hash, *comment, *info;
  292. };
  293. static void keylist_update_callback(
  294. void *vctx, char **fingerprints, const char *comment, uint32_t ext_flags,
  295. struct pageant_pubkey *key)
  296. {
  297. struct keylist_update_ctx *ctx = (struct keylist_update_ctx *)vctx;
  298. FingerprintType this_type = ssh2_pick_fingerprint(fingerprints, fptype);
  299. ptrlen fingerprint = ptrlen_from_asciz(fingerprints[this_type]);
  300. struct keylist_display_data *disp = snew(struct keylist_display_data);
  301. disp->alg = strbuf_new();
  302. disp->bits = strbuf_new();
  303. disp->hash = strbuf_new();
  304. disp->comment = strbuf_new();
  305. disp->info = strbuf_new();
  306. /* There is at least one key, so the controls for removing keys
  307. * should be enabled */
  308. ctx->enable_remove_controls = true;
  309. switch (key->ssh_version) {
  310. case 1: {
  311. /*
  312. * Expect the fingerprint to contain two words: bit count and
  313. * hash.
  314. */
  315. put_dataz(disp->alg, "SSH-1");
  316. put_datapl(disp->bits, ptrlen_get_word(&fingerprint, " "));
  317. put_datapl(disp->hash, ptrlen_get_word(&fingerprint, " "));
  318. break;
  319. }
  320. case 2: {
  321. /*
  322. * Expect the fingerprint to contain three words: algorithm
  323. * name, bit count, hash.
  324. */
  325. const ssh_keyalg *alg = pubkey_blob_to_alg(
  326. ptrlen_from_strbuf(key->blob));
  327. ptrlen keytype_word = ptrlen_get_word(&fingerprint, " ");
  328. if (alg) {
  329. /* Use our own human-legible algorithm names if available,
  330. * because they fit better in the space. (Certificate key
  331. * algorithm names in particular are terribly long.) */
  332. char *alg_desc = ssh_keyalg_desc(alg);
  333. put_dataz(disp->alg, alg_desc);
  334. sfree(alg_desc);
  335. } else {
  336. put_datapl(disp->alg, keytype_word);
  337. }
  338. ptrlen bits_word = ptrlen_get_word(&fingerprint, " ");
  339. if (alg && ssh_keyalg_variable_size(alg))
  340. put_datapl(disp->bits, bits_word);
  341. put_datapl(disp->hash, ptrlen_get_word(&fingerprint, " "));
  342. }
  343. }
  344. put_dataz(disp->comment, comment);
  345. SIZE sz;
  346. if (disp->bits->len) {
  347. GetTextExtentPoint32(ctx->hdc, disp->alg->s, disp->alg->len, &sz);
  348. if (ctx->algwidth < sz.cx) ctx->algwidth = sz.cx;
  349. GetTextExtentPoint32(ctx->hdc, disp->bits->s, disp->bits->len, &sz);
  350. if (ctx->bitswidth < sz.cx) ctx->bitswidth = sz.cx;
  351. } else {
  352. GetTextExtentPoint32(ctx->hdc, disp->alg->s, disp->alg->len, &sz);
  353. if (ctx->algbitswidth < sz.cx) ctx->algbitswidth = sz.cx;
  354. }
  355. GetTextExtentPoint32(ctx->hdc, disp->hash->s, disp->hash->len, &sz);
  356. if (ctx->hashwidth < sz.cx) ctx->hashwidth = sz.cx;
  357. if (ext_flags & LIST_EXTENDED_FLAG_HAS_NO_CLEARTEXT_KEY) {
  358. put_fmt(disp->info, "(encrypted)");
  359. } else if (ext_flags & LIST_EXTENDED_FLAG_HAS_ENCRYPTED_KEY_FILE) {
  360. put_fmt(disp->info, "(re-encryptable)");
  361. /* At least one key can be re-encrypted */
  362. ctx->enable_reencrypt_controls = true;
  363. }
  364. /* This list box is owner-drawn but doesn't have LBS_HASSTRINGS,
  365. * so we can use LB_ADDSTRING to hand the list box our display
  366. * info pointer */
  367. SendDlgItemMessage(keylist, IDC_KEYLIST_LISTBOX,
  368. LB_ADDSTRING, 0, (LPARAM)disp);
  369. }
  370. /* Column start positions for the list box, in pixels (not dialog units). */
  371. static int colpos_bits, colpos_hash, colpos_comment;
  372. /*
  373. * Update the visible key list.
  374. */
  375. void keylist_update(void)
  376. {
  377. if (keylist) {
  378. /*
  379. * Clear the previous list box content and free their display
  380. * structures.
  381. */
  382. {
  383. int nitems = SendDlgItemMessage(keylist, IDC_KEYLIST_LISTBOX,
  384. LB_GETCOUNT, 0, 0);
  385. for (int i = 0; i < nitems; i++) {
  386. struct keylist_display_data *disp =
  387. (struct keylist_display_data *)SendDlgItemMessage(
  388. keylist, IDC_KEYLIST_LISTBOX, LB_GETITEMDATA, i, 0);
  389. strbuf_free(disp->alg);
  390. strbuf_free(disp->bits);
  391. strbuf_free(disp->hash);
  392. strbuf_free(disp->comment);
  393. strbuf_free(disp->info);
  394. sfree(disp);
  395. }
  396. }
  397. SendDlgItemMessage(keylist, IDC_KEYLIST_LISTBOX,
  398. LB_RESETCONTENT, 0, 0);
  399. char *errmsg;
  400. struct keylist_update_ctx ctx[1];
  401. ctx->enable_remove_controls = false;
  402. ctx->enable_reencrypt_controls = false;
  403. ctx->algbitswidth = ctx->algwidth = 0;
  404. ctx->bitswidth = ctx->hashwidth = 0;
  405. ctx->hdc = GetDC(keylist);
  406. SelectObject(ctx->hdc, (HFONT)SendMessage(keylist, WM_GETFONT, 0, 0));
  407. int status = pageant_enum_keys(keylist_update_callback, ctx, &errmsg);
  408. SIZE sz;
  409. GetTextExtentPoint32(ctx->hdc, "MM", 2, &sz);
  410. int gutter = sz.cx;
  411. DeleteDC(ctx->hdc);
  412. colpos_hash = ctx->algwidth + ctx->bitswidth + 2*gutter;
  413. if (colpos_hash < ctx->algbitswidth + gutter)
  414. colpos_hash = ctx->algbitswidth + gutter;
  415. colpos_bits = colpos_hash - ctx->bitswidth - gutter;
  416. colpos_comment = colpos_hash + ctx->hashwidth + gutter;
  417. assert(status == PAGEANT_ACTION_OK);
  418. assert(!errmsg);
  419. SendDlgItemMessage(keylist, IDC_KEYLIST_LISTBOX,
  420. LB_SETCURSEL, (WPARAM) - 1, 0);
  421. EnableWindow(GetDlgItem(keylist, IDC_KEYLIST_REMOVE),
  422. ctx->enable_remove_controls);
  423. EnableWindow(GetDlgItem(keylist, IDC_KEYLIST_REENCRYPT),
  424. ctx->enable_reencrypt_controls);
  425. }
  426. }
  427. static void win_add_keyfile(Filename *filename, bool encrypted)
  428. {
  429. char *err;
  430. int ret;
  431. /*
  432. * Try loading the key without a passphrase. (Or rather, without a
  433. * _new_ passphrase; pageant_add_keyfile will take care of trying
  434. * all the passphrases we've already stored.)
  435. */
  436. ret = pageant_add_keyfile(filename, NULL, &err, encrypted);
  437. if (ret == PAGEANT_ACTION_OK) {
  438. goto done;
  439. } else if (ret == PAGEANT_ACTION_FAILURE) {
  440. goto error;
  441. }
  442. /*
  443. * OK, a passphrase is needed, and we've been given the key
  444. * comment to use in the passphrase prompt.
  445. */
  446. while (1) {
  447. INT_PTR dlgret;
  448. struct PassphraseProcStruct pps;
  449. pps.modal = true;
  450. pps.help_topic = NULL; /* this dialog has no help button */
  451. pps.dlgid = NULL;
  452. pps.passphrase = NULL;
  453. pps.comment = err;
  454. dlgret = DialogBoxParam(
  455. hinst, MAKEINTRESOURCE(IDD_LOAD_PASSPHRASE),
  456. NULL, PassphraseProc, (LPARAM) &pps);
  457. modal_passphrase_hwnd = NULL;
  458. if (!dlgret) {
  459. burnstr(pps.passphrase);
  460. goto done; /* operation cancelled */
  461. }
  462. sfree(err);
  463. assert(pps.passphrase != NULL);
  464. ret = pageant_add_keyfile(filename, pps.passphrase, &err, false);
  465. burnstr(pps.passphrase);
  466. if (ret == PAGEANT_ACTION_OK) {
  467. goto done;
  468. } else if (ret == PAGEANT_ACTION_FAILURE) {
  469. goto error;
  470. }
  471. }
  472. error:
  473. message_box(traywindow, err, APPNAME, MB_OK | MB_ICONERROR, false,
  474. HELPCTXID(errors_cantloadkey));
  475. done:
  476. sfree(err);
  477. return;
  478. }
  479. /*
  480. * Prompt for a key file to add, and add it.
  481. */
  482. static void prompt_add_keyfile(bool encrypted)
  483. {
  484. OPENFILENAME of;
  485. char *filelist = snewn(8192, char);
  486. if (!keypath) keypath = filereq_new();
  487. memset(&of, 0, sizeof(of));
  488. of.hwndOwner = traywindow;
  489. of.lpstrFilter = FILTER_KEY_FILES_C;
  490. of.lpstrCustomFilter = NULL;
  491. of.nFilterIndex = 1;
  492. of.lpstrFile = filelist;
  493. *filelist = '\0';
  494. of.nMaxFile = 8192;
  495. of.lpstrFileTitle = NULL;
  496. of.lpstrTitle = "Select Private Key File";
  497. of.Flags = OFN_ALLOWMULTISELECT | OFN_EXPLORER;
  498. if (request_file(keypath, &of, true, false)) {
  499. if (strlen(filelist) > of.nFileOffset) {
  500. /* Only one filename returned? */
  501. Filename *fn = filename_from_str(filelist);
  502. win_add_keyfile(fn, encrypted);
  503. filename_free(fn);
  504. } else {
  505. /* we are returned a bunch of strings, end to
  506. * end. first string is the directory, the
  507. * rest the filenames. terminated with an
  508. * empty string.
  509. */
  510. char *dir = filelist;
  511. char *filewalker = filelist + strlen(dir) + 1;
  512. while (*filewalker != '\0') {
  513. char *filename = dupcat(dir, "\\", filewalker);
  514. Filename *fn = filename_from_str(filename);
  515. win_add_keyfile(fn, encrypted);
  516. filename_free(fn);
  517. sfree(filename);
  518. filewalker += strlen(filewalker) + 1;
  519. }
  520. }
  521. keylist_update();
  522. pageant_forget_passphrases();
  523. }
  524. sfree(filelist);
  525. }
  526. /*
  527. * Dialog-box function for the key list box.
  528. */
  529. static INT_PTR CALLBACK KeyListProc(HWND hwnd, UINT msg,
  530. WPARAM wParam, LPARAM lParam)
  531. {
  532. static const struct {
  533. const char *name;
  534. FingerprintType value;
  535. } fptypes[] = {
  536. {"SHA256", SSH_FPTYPE_SHA256},
  537. {"MD5", SSH_FPTYPE_MD5},
  538. {"SHA256 including certificate", SSH_FPTYPE_SHA256_CERT},
  539. {"MD5 including certificate", SSH_FPTYPE_MD5_CERT},
  540. };
  541. switch (msg) {
  542. case WM_INITDIALOG: {
  543. /*
  544. * Centre the window.
  545. */
  546. RECT rs, rd;
  547. HWND hw;
  548. hw = GetDesktopWindow();
  549. if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd))
  550. MoveWindow(hwnd,
  551. (rs.right + rs.left + rd.left - rd.right) / 2,
  552. (rs.bottom + rs.top + rd.top - rd.bottom) / 2,
  553. rd.right - rd.left, rd.bottom - rd.top, true);
  554. if (has_help())
  555. SetWindowLongPtr(hwnd, GWL_EXSTYLE,
  556. GetWindowLongPtr(hwnd, GWL_EXSTYLE) |
  557. WS_EX_CONTEXTHELP);
  558. else {
  559. HWND item = GetDlgItem(hwnd, IDC_KEYLIST_HELP);
  560. if (item)
  561. DestroyWindow(item);
  562. }
  563. keylist = hwnd;
  564. int selection = 0;
  565. for (size_t i = 0; i < lenof(fptypes); i++) {
  566. SendDlgItemMessage(hwnd, IDC_KEYLIST_FPTYPE, CB_ADDSTRING,
  567. 0, (LPARAM)fptypes[i].name);
  568. if (fptype == fptypes[i].value)
  569. selection = (int)i;
  570. }
  571. SendDlgItemMessage(hwnd, IDC_KEYLIST_FPTYPE,
  572. CB_SETCURSEL, 0, selection);
  573. keylist_update();
  574. return 0;
  575. }
  576. case WM_MEASUREITEM: {
  577. assert(wParam == IDC_KEYLIST_LISTBOX);
  578. MEASUREITEMSTRUCT *mi = (MEASUREITEMSTRUCT *)lParam;
  579. /*
  580. * Our list box is owner-drawn, but we put normal text in it.
  581. * So the line height is the same as it would normally be,
  582. * which is 8 dialog units.
  583. */
  584. RECT r;
  585. r.left = r.right = r.top = 0;
  586. r.bottom = 8;
  587. MapDialogRect(hwnd, &r);
  588. mi->itemHeight = r.bottom;
  589. return 0;
  590. }
  591. case WM_DRAWITEM: {
  592. assert(wParam == IDC_KEYLIST_LISTBOX);
  593. DRAWITEMSTRUCT *di = (DRAWITEMSTRUCT *)lParam;
  594. if (di->itemAction == ODA_FOCUS) {
  595. /* Just toggle the focus rectangle either on or off. This
  596. * is an XOR-type function, so it's the same call in
  597. * either case. */
  598. DrawFocusRect(di->hDC, &di->rcItem);
  599. } else {
  600. /* Draw the full text. */
  601. bool selected = (di->itemState & ODS_SELECTED);
  602. COLORREF newfg = GetSysColor(
  603. selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
  604. COLORREF newbg = GetSysColor(
  605. selected ? COLOR_HIGHLIGHT : COLOR_WINDOW);
  606. COLORREF oldfg = SetTextColor(di->hDC, newfg);
  607. COLORREF oldbg = SetBkColor(di->hDC, newbg);
  608. HFONT font = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0);
  609. HFONT oldfont = SelectObject(di->hDC, font);
  610. /* ExtTextOut("") is an easy way to just draw the
  611. * background rectangle */
  612. ExtTextOut(di->hDC, di->rcItem.left, di->rcItem.top,
  613. ETO_OPAQUE | ETO_CLIPPED, &di->rcItem, "", 0, NULL);
  614. struct keylist_display_data *disp =
  615. (struct keylist_display_data *)di->itemData;
  616. RECT r;
  617. /* Apparently real list boxes start drawing at x=1, not x=0 */
  618. r.left = r.top = r.bottom = 0;
  619. r.right = 1;
  620. MapDialogRect(hwnd, &r);
  621. ExtTextOut(di->hDC, di->rcItem.left + r.right, di->rcItem.top,
  622. ETO_CLIPPED, &di->rcItem, disp->alg->s,
  623. disp->alg->len, NULL);
  624. if (disp->bits->len) {
  625. ExtTextOut(di->hDC, di->rcItem.left + r.right + colpos_bits,
  626. di->rcItem.top, ETO_CLIPPED, &di->rcItem,
  627. disp->bits->s, disp->bits->len, NULL);
  628. }
  629. ExtTextOut(di->hDC, di->rcItem.left + r.right + colpos_hash,
  630. di->rcItem.top, ETO_CLIPPED, &di->rcItem,
  631. disp->hash->s, disp->hash->len, NULL);
  632. strbuf *sb = strbuf_new();
  633. put_datapl(sb, ptrlen_from_strbuf(disp->comment));
  634. if (disp->info->len) {
  635. put_byte(sb, '\t');
  636. put_datapl(sb, ptrlen_from_strbuf(disp->info));
  637. }
  638. TabbedTextOut(di->hDC, di->rcItem.left + r.right + colpos_comment,
  639. di->rcItem.top, sb->s, sb->len, 0, NULL, 0);
  640. strbuf_free(sb);
  641. SetTextColor(di->hDC, oldfg);
  642. SetBkColor(di->hDC, oldbg);
  643. SelectObject(di->hDC, oldfont);
  644. if (di->itemState & ODS_FOCUS)
  645. DrawFocusRect(di->hDC, &di->rcItem);
  646. }
  647. return 0;
  648. }
  649. case WM_COMMAND:
  650. switch (LOWORD(wParam)) {
  651. case IDOK:
  652. case IDCANCEL:
  653. keylist = NULL;
  654. DestroyWindow(hwnd);
  655. return 0;
  656. case IDC_KEYLIST_ADDKEY:
  657. case IDC_KEYLIST_ADDKEY_ENC:
  658. if (HIWORD(wParam) == BN_CLICKED ||
  659. HIWORD(wParam) == BN_DOUBLECLICKED) {
  660. if (modal_passphrase_hwnd) {
  661. MessageBeep(MB_ICONERROR);
  662. SetForegroundWindow(modal_passphrase_hwnd);
  663. break;
  664. }
  665. prompt_add_keyfile(LOWORD(wParam) == IDC_KEYLIST_ADDKEY_ENC);
  666. }
  667. return 0;
  668. case IDC_KEYLIST_REMOVE:
  669. case IDC_KEYLIST_REENCRYPT:
  670. if (HIWORD(wParam) == BN_CLICKED ||
  671. HIWORD(wParam) == BN_DOUBLECLICKED) {
  672. int i;
  673. int rCount, sCount;
  674. int *selectedArray;
  675. /* our counter within the array of selected items */
  676. int itemNum;
  677. /* get the number of items selected in the list */
  678. int numSelected = SendDlgItemMessage(
  679. hwnd, IDC_KEYLIST_LISTBOX, LB_GETSELCOUNT, 0, 0);
  680. /* none selected? that was silly */
  681. if (numSelected == 0) {
  682. MessageBeep(0);
  683. break;
  684. }
  685. /* get item indices in an array */
  686. selectedArray = snewn(numSelected, int);
  687. SendDlgItemMessage(hwnd, IDC_KEYLIST_LISTBOX, LB_GETSELITEMS,
  688. numSelected, (WPARAM)selectedArray);
  689. itemNum = numSelected - 1;
  690. rCount = pageant_count_ssh1_keys();
  691. sCount = pageant_count_ssh2_keys();
  692. /* go through the non-rsakeys until we've covered them all,
  693. * and/or we're out of selected items to check. note that
  694. * we go *backwards*, to avoid complications from deleting
  695. * things hence altering the offset of subsequent items
  696. */
  697. for (i = sCount - 1; (itemNum >= 0) && (i >= 0); i--) {
  698. if (selectedArray[itemNum] == rCount + i) {
  699. switch (LOWORD(wParam)) {
  700. case IDC_KEYLIST_REMOVE:
  701. pageant_delete_nth_ssh2_key(i);
  702. break;
  703. case IDC_KEYLIST_REENCRYPT:
  704. pageant_reencrypt_nth_ssh2_key(i);
  705. break;
  706. }
  707. itemNum--;
  708. }
  709. }
  710. /* do the same for the rsa keys */
  711. for (i = rCount - 1; (itemNum >= 0) && (i >= 0); i--) {
  712. if (selectedArray[itemNum] == i) {
  713. switch (LOWORD(wParam)) {
  714. case IDC_KEYLIST_REMOVE:
  715. pageant_delete_nth_ssh1_key(i);
  716. break;
  717. case IDC_KEYLIST_REENCRYPT:
  718. /* SSH-1 keys can't be re-encrypted */
  719. break;
  720. }
  721. itemNum--;
  722. }
  723. }
  724. sfree(selectedArray);
  725. keylist_update();
  726. }
  727. return 0;
  728. case IDC_KEYLIST_HELP:
  729. if (HIWORD(wParam) == BN_CLICKED ||
  730. HIWORD(wParam) == BN_DOUBLECLICKED) {
  731. launch_help(hwnd, WINHELP_CTX_pageant_general);
  732. }
  733. return 0;
  734. case IDC_KEYLIST_FPTYPE:
  735. if (HIWORD(wParam) == CBN_SELCHANGE) {
  736. int selection = SendDlgItemMessage(
  737. hwnd, IDC_KEYLIST_FPTYPE, CB_GETCURSEL, 0, 0);
  738. if (selection >= 0 && (size_t)selection < lenof(fptypes)) {
  739. fptype = fptypes[selection].value;
  740. keylist_update();
  741. }
  742. }
  743. return 0;
  744. }
  745. return 0;
  746. case WM_HELP: {
  747. int id = ((LPHELPINFO)lParam)->iCtrlId;
  748. const char *topic = NULL;
  749. switch (id) {
  750. case IDC_KEYLIST_LISTBOX:
  751. case IDC_KEYLIST_FPTYPE:
  752. case IDC_KEYLIST_FPTYPE_STATIC:
  753. topic = WINHELP_CTX_pageant_keylist; break;
  754. case IDC_KEYLIST_ADDKEY: topic = WINHELP_CTX_pageant_addkey; break;
  755. case IDC_KEYLIST_REMOVE: topic = WINHELP_CTX_pageant_remkey; break;
  756. case IDC_KEYLIST_ADDKEY_ENC:
  757. case IDC_KEYLIST_REENCRYPT:
  758. topic = WINHELP_CTX_pageant_deferred; break;
  759. }
  760. if (topic) {
  761. launch_help(hwnd, topic);
  762. } else {
  763. MessageBeep(0);
  764. }
  765. break;
  766. }
  767. case WM_CLOSE:
  768. keylist = NULL;
  769. DestroyWindow(hwnd);
  770. return 0;
  771. }
  772. return 0;
  773. }
  774. /* Set up a system tray icon */
  775. static BOOL AddTrayIcon(HWND hwnd)
  776. {
  777. BOOL res;
  778. NOTIFYICONDATA tnid;
  779. HICON hicon;
  780. #ifdef NIM_SETVERSION
  781. tnid.uVersion = 0;
  782. res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
  783. #endif
  784. tnid.cbSize = sizeof(NOTIFYICONDATA);
  785. tnid.hWnd = hwnd;
  786. tnid.uID = 1; /* unique within this systray use */
  787. tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
  788. tnid.uCallbackMessage = WM_SYSTRAY;
  789. tnid.hIcon = hicon = LoadIcon(hinst, MAKEINTRESOURCE(201));
  790. strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
  791. res = Shell_NotifyIcon(NIM_ADD, &tnid);
  792. if (hicon) DestroyIcon(hicon);
  793. return res;
  794. }
  795. /* Update the saved-sessions menu. */
  796. static void update_sessions(void)
  797. {
  798. int num_entries;
  799. HKEY hkey;
  800. TCHAR buf[MAX_PATH + 1];
  801. MENUITEMINFO mii;
  802. strbuf *sb;
  803. int index_key, index_menu;
  804. if (!putty_path)
  805. return;
  806. if (ERROR_SUCCESS != RegOpenKey(HKEY_CURRENT_USER, PUTTY_REGKEY, &hkey))
  807. return;
  808. for (num_entries = GetMenuItemCount(session_menu);
  809. num_entries > initial_menuitems_count;
  810. num_entries--)
  811. RemoveMenu(session_menu, 0, MF_BYPOSITION);
  812. index_key = 0;
  813. index_menu = 0;
  814. sb = strbuf_new();
  815. while (ERROR_SUCCESS == RegEnumKey(hkey, index_key, buf, MAX_PATH)) {
  816. if (strcmp(buf, PUTTY_DEFAULT) != 0) {
  817. strbuf_clear(sb);
  818. unescape_registry_key(buf, sb);
  819. memset(&mii, 0, sizeof(mii));
  820. mii.cbSize = sizeof(mii);
  821. mii.fMask = MIIM_TYPE | MIIM_STATE | MIIM_ID;
  822. mii.fType = MFT_STRING;
  823. mii.fState = MFS_ENABLED;
  824. mii.wID = (index_menu * 16) + IDM_SESSIONS_BASE;
  825. mii.dwTypeData = sb->s;
  826. InsertMenuItem(session_menu, index_menu, true, &mii);
  827. index_menu++;
  828. }
  829. index_key++;
  830. }
  831. strbuf_free(sb);
  832. RegCloseKey(hkey);
  833. if (index_menu == 0) {
  834. mii.cbSize = sizeof(mii);
  835. mii.fMask = MIIM_TYPE | MIIM_STATE;
  836. mii.fType = MFT_STRING;
  837. mii.fState = MFS_GRAYED;
  838. mii.dwTypeData = _T("(No sessions)");
  839. InsertMenuItem(session_menu, index_menu, true, &mii);
  840. }
  841. }
  842. /*
  843. * Versions of Pageant prior to 0.61 expected this SID on incoming
  844. * communications. For backwards compatibility, and more particularly
  845. * for compatibility with derived works of PuTTY still using the old
  846. * Pageant client code, we accept it as an alternative to the one
  847. * returned from get_user_sid().
  848. */
  849. PSID get_default_sid(void)
  850. {
  851. HANDLE proc = NULL;
  852. DWORD sidlen;
  853. PSECURITY_DESCRIPTOR psd = NULL;
  854. PSID sid = NULL, copy = NULL, ret = NULL;
  855. if ((proc = OpenProcess(MAXIMUM_ALLOWED, false,
  856. GetCurrentProcessId())) == NULL)
  857. goto cleanup;
  858. if (p_GetSecurityInfo(proc, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,
  859. &sid, NULL, NULL, NULL, &psd) != ERROR_SUCCESS)
  860. goto cleanup;
  861. sidlen = GetLengthSid(sid);
  862. copy = (PSID)smalloc(sidlen);
  863. if (!CopySid(sidlen, copy, sid))
  864. goto cleanup;
  865. /* Success. Move sid into the return value slot, and null it out
  866. * to stop the cleanup code freeing it. */
  867. ret = copy;
  868. copy = NULL;
  869. cleanup:
  870. if (proc != NULL)
  871. CloseHandle(proc);
  872. if (psd != NULL)
  873. LocalFree(psd);
  874. if (copy != NULL)
  875. sfree(copy);
  876. return ret;
  877. }
  878. struct WmCopydataTransaction {
  879. char *length, *body;
  880. size_t bodysize, bodylen;
  881. HANDLE ev_msg_ready, ev_reply_ready;
  882. } wmct;
  883. static struct PageantClient wmcpc;
  884. static void wm_copydata_got_msg(void *vctx)
  885. {
  886. pageant_handle_msg(&wmcpc, NULL, make_ptrlen(wmct.body, wmct.bodylen));
  887. }
  888. static void wm_copydata_got_response(
  889. PageantClient *pc, PageantClientRequestId *reqid, ptrlen response)
  890. {
  891. if (response.len > wmct.bodysize) {
  892. /* Output would overflow message buffer. Replace with a
  893. * failure message. */
  894. static const unsigned char failure[] = { SSH_AGENT_FAILURE };
  895. response = make_ptrlen(failure, lenof(failure));
  896. assert(response.len <= wmct.bodysize);
  897. }
  898. PUT_32BIT_MSB_FIRST(wmct.length, response.len);
  899. memcpy(wmct.body, response.ptr, response.len);
  900. SetEvent(wmct.ev_reply_ready);
  901. }
  902. static bool ask_passphrase_common(PageantClientDialogId *dlgid,
  903. const char *comment)
  904. {
  905. /* Pageant core should be serialising requests, so we never expect
  906. * a passphrase prompt to exist already at this point */
  907. assert(!nonmodal_passphrase_hwnd);
  908. struct PassphraseProcStruct *pps = snew(struct PassphraseProcStruct);
  909. pps->modal = false;
  910. pps->help_topic = WINHELP_CTX_pageant_deferred;
  911. pps->dlgid = dlgid;
  912. pps->passphrase = NULL;
  913. pps->comment = comment;
  914. nonmodal_passphrase_hwnd = CreateDialogParam(
  915. hinst, MAKEINTRESOURCE(IDD_ONDEMAND_PASSPHRASE),
  916. NULL, PassphraseProc, (LPARAM)pps);
  917. /*
  918. * Try to put this passphrase prompt into the foreground.
  919. *
  920. * This will probably not succeed in giving it the actual keyboard
  921. * focus, because Windows is quite opposed to applications being
  922. * able to suddenly steal the focus on their own initiative.
  923. *
  924. * That makes sense in a lot of situations, as a defensive
  925. * measure. If you were about to type a password or other secret
  926. * data into the window you already had focused, and some
  927. * malicious app stole the focus, it might manage to trick you
  928. * into typing your secrets into _it_ instead.
  929. *
  930. * In this case it's possible to regard the same defensive measure
  931. * as counterproductive, because the effect if we _do_ steal focus
  932. * is that you type something into our passphrase prompt that
  933. * isn't the passphrase, and we fail to decrypt the key, and no
  934. * harm is done. Whereas the effect of the user wrongly _assuming_
  935. * the new passphrase prompt has the focus is much worse: now you
  936. * type your highly secret passphrase into some other window you
  937. * didn't mean to trust with that information - such as the
  938. * agent-forwarded PuTTY in which you just ran an ssh command,
  939. * which the _whole point_ was to avoid telling your passphrase to!
  940. *
  941. * On the other hand, I'm sure _every_ application author can come
  942. * up with an argument for why they think _they_ should be allowed
  943. * to steal the focus. Probably most of them include the claim
  944. * that no harm is done if their application receives data
  945. * intended for something else, and of course that's not always
  946. * true!
  947. *
  948. * In any case, I don't know of anything I can do about it, or
  949. * anything I _should_ do about it if I could. If anyone thinks
  950. * they can improve on all this, patches are welcome.
  951. */
  952. SetForegroundWindow(nonmodal_passphrase_hwnd);
  953. return true;
  954. }
  955. static bool wm_copydata_ask_passphrase(
  956. PageantClient *pc, PageantClientDialogId *dlgid, const char *comment)
  957. {
  958. return ask_passphrase_common(dlgid, comment);
  959. }
  960. static const PageantClientVtable wmcpc_vtable = {
  961. .log = NULL, /* no logging in this client */
  962. .got_response = wm_copydata_got_response,
  963. .ask_passphrase = wm_copydata_ask_passphrase,
  964. };
  965. static char *answer_filemapping_message(const char *mapname)
  966. {
  967. HANDLE maphandle = INVALID_HANDLE_VALUE;
  968. void *mapaddr = NULL;
  969. char *err = NULL;
  970. size_t mapsize;
  971. unsigned msglen;
  972. PSID mapsid = NULL;
  973. PSID expectedsid = NULL;
  974. PSID expectedsid_bc = NULL;
  975. PSECURITY_DESCRIPTOR psd = NULL;
  976. wmct.length = wmct.body = NULL;
  977. #ifdef DEBUG_IPC
  978. debug("mapname = \"%s\"\n", mapname);
  979. #endif
  980. maphandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, false, mapname);
  981. if (maphandle == NULL || maphandle == INVALID_HANDLE_VALUE) {
  982. err = dupprintf("OpenFileMapping(\"%s\"): %s",
  983. mapname, win_strerror(GetLastError()));
  984. goto cleanup;
  985. }
  986. #ifdef DEBUG_IPC
  987. debug("maphandle = %p\n", maphandle);
  988. #endif
  989. if (should_have_security()) {
  990. DWORD retd;
  991. if ((expectedsid = get_user_sid()) == NULL) {
  992. err = dupstr("unable to get user SID");
  993. goto cleanup;
  994. }
  995. if ((expectedsid_bc = get_default_sid()) == NULL) {
  996. err = dupstr("unable to get default SID");
  997. goto cleanup;
  998. }
  999. if ((retd = p_GetSecurityInfo(
  1000. maphandle, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,
  1001. &mapsid, NULL, NULL, NULL, &psd) != ERROR_SUCCESS)) {
  1002. err = dupprintf("unable to get owner of file mapping: "
  1003. "GetSecurityInfo returned: %s",
  1004. win_strerror(retd));
  1005. goto cleanup;
  1006. }
  1007. #ifdef DEBUG_IPC
  1008. {
  1009. LPTSTR ours, ours2, theirs;
  1010. ConvertSidToStringSid(mapsid, &theirs);
  1011. ConvertSidToStringSid(expectedsid, &ours);
  1012. ConvertSidToStringSid(expectedsid_bc, &ours2);
  1013. debug("got sids:\n oursnew=%s\n oursold=%s\n"
  1014. " theirs=%s\n", ours, ours2, theirs);
  1015. LocalFree(ours);
  1016. LocalFree(ours2);
  1017. LocalFree(theirs);
  1018. }
  1019. #endif
  1020. if (!EqualSid(mapsid, expectedsid) &&
  1021. !EqualSid(mapsid, expectedsid_bc)) {
  1022. err = dupstr("wrong owning SID of file mapping");
  1023. goto cleanup;
  1024. }
  1025. } else {
  1026. #ifdef DEBUG_IPC
  1027. debug("security APIs not present\n");
  1028. #endif
  1029. }
  1030. mapaddr = MapViewOfFile(maphandle, FILE_MAP_WRITE, 0, 0, 0);
  1031. if (!mapaddr) {
  1032. err = dupprintf("unable to obtain view of file mapping: %s",
  1033. win_strerror(GetLastError()));
  1034. goto cleanup;
  1035. }
  1036. #ifdef DEBUG_IPC
  1037. debug("mapped address = %p\n", mapaddr);
  1038. #endif
  1039. {
  1040. MEMORY_BASIC_INFORMATION mbi;
  1041. size_t mbiSize = VirtualQuery(mapaddr, &mbi, sizeof(mbi));
  1042. if (mbiSize == 0) {
  1043. err = dupprintf("unable to query view of file mapping: %s",
  1044. win_strerror(GetLastError()));
  1045. goto cleanup;
  1046. }
  1047. if (mbiSize < (offsetof(MEMORY_BASIC_INFORMATION, RegionSize) +
  1048. sizeof(mbi.RegionSize))) {
  1049. err = dupstr("VirtualQuery returned too little data to get "
  1050. "region size");
  1051. goto cleanup;
  1052. }
  1053. mapsize = mbi.RegionSize;
  1054. }
  1055. #ifdef DEBUG_IPC
  1056. debug("region size = %"SIZEu"\n", mapsize);
  1057. #endif
  1058. if (mapsize < 5) {
  1059. err = dupstr("mapping smaller than smallest possible request");
  1060. goto cleanup;
  1061. }
  1062. wmct.length = (char *)mapaddr;
  1063. msglen = GET_32BIT_MSB_FIRST(wmct.length);
  1064. #ifdef DEBUG_IPC
  1065. debug("msg length=%08x, msg type=%02x\n",
  1066. msglen, (unsigned)((unsigned char *) mapaddr)[4]);
  1067. #endif
  1068. wmct.body = wmct.length + 4;
  1069. wmct.bodysize = mapsize - 4;
  1070. if (msglen > wmct.bodysize) {
  1071. /* Incoming length field is too large. Emit a failure response
  1072. * without even trying to handle the request.
  1073. *
  1074. * (We know this must fit, because we checked mapsize >= 5
  1075. * above.) */
  1076. PUT_32BIT_MSB_FIRST(wmct.length, 1);
  1077. *wmct.body = SSH_AGENT_FAILURE;
  1078. } else {
  1079. wmct.bodylen = msglen;
  1080. SetEvent(wmct.ev_msg_ready);
  1081. WaitForSingleObject(wmct.ev_reply_ready, INFINITE);
  1082. }
  1083. cleanup:
  1084. /* expectedsid has the lifetime of the program, so we don't free it */
  1085. sfree(expectedsid_bc);
  1086. if (psd)
  1087. LocalFree(psd);
  1088. if (mapaddr)
  1089. UnmapViewOfFile(mapaddr);
  1090. if (maphandle != NULL && maphandle != INVALID_HANDLE_VALUE)
  1091. CloseHandle(maphandle);
  1092. return err;
  1093. }
  1094. static void create_keylist_window(void)
  1095. {
  1096. if (keylist)
  1097. return;
  1098. keylist = CreateDialog(hinst, MAKEINTRESOURCE(IDD_KEYLIST),
  1099. NULL, KeyListProc);
  1100. ShowWindow(keylist, SW_SHOWNORMAL);
  1101. }
  1102. static LRESULT CALLBACK TrayWndProc(HWND hwnd, UINT message,
  1103. WPARAM wParam, LPARAM lParam)
  1104. {
  1105. static bool menuinprogress;
  1106. static UINT msgTaskbarCreated = 0;
  1107. switch (message) {
  1108. case WM_CREATE:
  1109. msgTaskbarCreated = RegisterWindowMessage(_T("TaskbarCreated"));
  1110. break;
  1111. default:
  1112. if (message==msgTaskbarCreated) {
  1113. /*
  1114. * Explorer has been restarted, so the tray icon will
  1115. * have been lost.
  1116. */
  1117. AddTrayIcon(hwnd);
  1118. }
  1119. break;
  1120. case WM_SYSTRAY:
  1121. if (lParam == WM_RBUTTONUP) {
  1122. POINT cursorpos;
  1123. GetCursorPos(&cursorpos);
  1124. PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
  1125. } else if (lParam == WM_LBUTTONDBLCLK) {
  1126. /* Run the default menu item. */
  1127. UINT menuitem = GetMenuDefaultItem(systray_menu, false, 0);
  1128. if (menuitem != -1)
  1129. PostMessage(hwnd, WM_COMMAND, menuitem, 0);
  1130. }
  1131. break;
  1132. case WM_SYSTRAY2:
  1133. if (!menuinprogress) {
  1134. menuinprogress = true;
  1135. update_sessions();
  1136. SetForegroundWindow(hwnd);
  1137. TrackPopupMenu(systray_menu,
  1138. TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
  1139. TPM_RIGHTBUTTON,
  1140. wParam, lParam, 0, hwnd, NULL);
  1141. menuinprogress = false;
  1142. }
  1143. break;
  1144. case WM_COMMAND:
  1145. case WM_SYSCOMMAND: {
  1146. unsigned command = wParam & ~0xF; /* low 4 bits reserved to Windows */
  1147. switch (command) {
  1148. case IDM_PUTTY: {
  1149. TCHAR cmdline[10];
  1150. cmdline[0] = '\0';
  1151. if (restrict_putty_acl)
  1152. strcat(cmdline, "&R");
  1153. if ((INT_PTR)ShellExecute(hwnd, NULL, putty_path, cmdline,
  1154. _T(""), SW_SHOW) <= 32) {
  1155. MessageBox(NULL, "Unable to execute PuTTY!",
  1156. "Error", MB_OK | MB_ICONERROR);
  1157. }
  1158. break;
  1159. }
  1160. case IDM_CLOSE:
  1161. if (modal_passphrase_hwnd)
  1162. SendMessage(modal_passphrase_hwnd, WM_CLOSE, 0, 0);
  1163. SendMessage(hwnd, WM_CLOSE, 0, 0);
  1164. break;
  1165. case IDM_VIEWKEYS:
  1166. create_keylist_window();
  1167. /*
  1168. * Sometimes the window comes up minimised / hidden for
  1169. * no obvious reason. Prevent this. This also brings it
  1170. * to the front if it's already present (the user
  1171. * selected View Keys because they wanted to _see_ the
  1172. * thing).
  1173. */
  1174. SetForegroundWindow(keylist);
  1175. SetWindowPos(keylist, HWND_TOP, 0, 0, 0, 0,
  1176. SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
  1177. break;
  1178. case IDM_ADDKEY:
  1179. case IDM_ADDKEY_ENCRYPTED:
  1180. if (modal_passphrase_hwnd) {
  1181. MessageBeep(MB_ICONERROR);
  1182. SetForegroundWindow(modal_passphrase_hwnd);
  1183. break;
  1184. }
  1185. prompt_add_keyfile(command == IDM_ADDKEY_ENCRYPTED);
  1186. break;
  1187. case IDM_REMOVE_ALL:
  1188. pageant_delete_all();
  1189. keylist_update();
  1190. break;
  1191. case IDM_REENCRYPT_ALL:
  1192. pageant_reencrypt_all();
  1193. keylist_update();
  1194. break;
  1195. case IDM_ABOUT:
  1196. if (!aboutbox) {
  1197. aboutbox = CreateDialog(hinst, MAKEINTRESOURCE(IDD_ABOUT),
  1198. NULL, AboutProc);
  1199. ShowWindow(aboutbox, SW_SHOWNORMAL);
  1200. /*
  1201. * Sometimes the window comes up minimised / hidden
  1202. * for no obvious reason. Prevent this.
  1203. */
  1204. SetForegroundWindow(aboutbox);
  1205. SetWindowPos(aboutbox, HWND_TOP, 0, 0, 0, 0,
  1206. SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
  1207. }
  1208. break;
  1209. case IDM_HELP:
  1210. launch_help(hwnd, WINHELP_CTX_pageant_general);
  1211. break;
  1212. default: {
  1213. if (wParam >= IDM_SESSIONS_BASE && wParam <= IDM_SESSIONS_MAX) {
  1214. MENUITEMINFO mii;
  1215. TCHAR buf[MAX_PATH + 1];
  1216. TCHAR param[MAX_PATH + 1];
  1217. memset(&mii, 0, sizeof(mii));
  1218. mii.cbSize = sizeof(mii);
  1219. mii.fMask = MIIM_TYPE;
  1220. mii.cch = MAX_PATH;
  1221. mii.dwTypeData = buf;
  1222. GetMenuItemInfo(session_menu, wParam, false, &mii);
  1223. param[0] = '\0';
  1224. if (restrict_putty_acl)
  1225. strcat(param, "&R");
  1226. strcat(param, "@");
  1227. strcat(param, mii.dwTypeData);
  1228. if ((INT_PTR)ShellExecute(hwnd, NULL, putty_path, param,
  1229. _T(""), SW_SHOW) <= 32) {
  1230. MessageBox(NULL, "Unable to execute PuTTY!", "Error",
  1231. MB_OK | MB_ICONERROR);
  1232. }
  1233. }
  1234. break;
  1235. }
  1236. }
  1237. break;
  1238. }
  1239. case WM_NETEVENT:
  1240. winselgui_response(wParam, lParam);
  1241. return 0;
  1242. case WM_DESTROY:
  1243. quit_help(hwnd);
  1244. PostQuitMessage(0);
  1245. return 0;
  1246. }
  1247. return DefWindowProc(hwnd, message, wParam, lParam);
  1248. }
  1249. static LRESULT CALLBACK wm_copydata_WndProc(HWND hwnd, UINT message,
  1250. WPARAM wParam, LPARAM lParam)
  1251. {
  1252. switch (message) {
  1253. case WM_COPYDATA: {
  1254. COPYDATASTRUCT *cds;
  1255. char *mapname, *err;
  1256. cds = (COPYDATASTRUCT *) lParam;
  1257. if (cds->dwData != AGENT_COPYDATA_ID)
  1258. return 0; /* not our message, mate */
  1259. mapname = (char *) cds->lpData;
  1260. if (mapname[cds->cbData - 1] != '\0')
  1261. return 0; /* failure to be ASCIZ! */
  1262. err = answer_filemapping_message(mapname);
  1263. if (err) {
  1264. #ifdef DEBUG_IPC
  1265. debug("IPC failed: %s\n", err);
  1266. #endif
  1267. sfree(err);
  1268. return 0;
  1269. }
  1270. return 1;
  1271. }
  1272. }
  1273. return DefWindowProc(hwnd, message, wParam, lParam);
  1274. }
  1275. static DWORD WINAPI wm_copydata_threadfunc(void *param)
  1276. {
  1277. HINSTANCE inst = *(HINSTANCE *)param;
  1278. HWND ipchwnd = CreateWindow(IPCCLASSNAME, IPCWINTITLE,
  1279. WS_OVERLAPPEDWINDOW | WS_VSCROLL,
  1280. CW_USEDEFAULT, CW_USEDEFAULT,
  1281. 100, 100, NULL, NULL, inst, NULL);
  1282. ShowWindow(ipchwnd, SW_HIDE);
  1283. MSG msg;
  1284. while (GetMessage(&msg, NULL, 0, 0) == 1) {
  1285. TranslateMessage(&msg);
  1286. DispatchMessage(&msg);
  1287. }
  1288. return 0;
  1289. }
  1290. /*
  1291. * Fork and Exec the command in cmdline. [DBW]
  1292. */
  1293. void spawn_cmd(const char *cmdline, const char *args, int show)
  1294. {
  1295. if (ShellExecute(NULL, _T("open"), cmdline,
  1296. args, NULL, show) <= (HINSTANCE) 32) {
  1297. char *msg;
  1298. msg = dupprintf("Failed to run \"%s\": %s", cmdline,
  1299. win_strerror(GetLastError()));
  1300. MessageBox(NULL, msg, APPNAME, MB_OK | MB_ICONEXCLAMATION);
  1301. sfree(msg);
  1302. }
  1303. }
  1304. void noise_ultralight(NoiseSourceId id, unsigned long data)
  1305. {
  1306. /* Pageant doesn't use random numbers, so we ignore this */
  1307. }
  1308. void cleanup_exit(int code)
  1309. {
  1310. shutdown_help();
  1311. exit(code);
  1312. }
  1313. static bool winpgnt_listener_ask_passphrase(
  1314. PageantListenerClient *plc, PageantClientDialogId *dlgid,
  1315. const char *comment)
  1316. {
  1317. return ask_passphrase_common(dlgid, comment);
  1318. }
  1319. struct winpgnt_client {
  1320. PageantListenerClient plc;
  1321. };
  1322. static const PageantListenerClientVtable winpgnt_vtable = {
  1323. .log = NULL, /* no logging */
  1324. .ask_passphrase = winpgnt_listener_ask_passphrase,
  1325. };
  1326. static struct winpgnt_client wpc[1];
  1327. HINSTANCE hinst;
  1328. static NORETURN void opt_error(const char *fmt, ...)
  1329. {
  1330. va_list ap;
  1331. va_start(ap, fmt);
  1332. char *msg = dupvprintf(fmt, ap);
  1333. va_end(ap);
  1334. MessageBox(NULL, msg, "Pageant command line error", MB_ICONERROR | MB_OK);
  1335. exit(1);
  1336. }
  1337. #ifdef LEGACY_WINDOWS
  1338. BOOL sw_PeekMessage(LPMSG msg, HWND hwnd, UINT min, UINT max, UINT remove)
  1339. {
  1340. static bool unicode_unavailable = false;
  1341. if (!unicode_unavailable) {
  1342. BOOL ret = PeekMessageW(msg, hwnd, min, max, remove);
  1343. if (!ret && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
  1344. unicode_unavailable = true; /* don't try again */
  1345. else
  1346. return ret;
  1347. }
  1348. return PeekMessageA(msg, hwnd, min, max, remove);
  1349. }
  1350. #else
  1351. #define sw_PeekMessage PeekMessageW
  1352. #endif
  1353. int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
  1354. {
  1355. MSG msg;
  1356. const char *command = NULL;
  1357. const char *unixsocket = NULL;
  1358. bool show_keylist_on_startup = false;
  1359. int argc;
  1360. char **argv, **argstart;
  1361. const char *openssh_config_file = NULL;
  1362. typedef struct CommandLineKey {
  1363. Filename *fn;
  1364. bool add_encrypted;
  1365. } CommandLineKey;
  1366. CommandLineKey *clkeys = NULL;
  1367. size_t nclkeys = 0, clkeysize = 0;
  1368. dll_hijacking_protection();
  1369. hinst = inst;
  1370. if (should_have_security()) {
  1371. /*
  1372. * Attempt to get the security API we need.
  1373. */
  1374. if (!got_advapi()) {
  1375. MessageBox(NULL,
  1376. "Unable to access security APIs. Pageant will\n"
  1377. "not run, in case it causes a security breach.",
  1378. "Pageant Fatal Error", MB_ICONERROR | MB_OK);
  1379. return 1;
  1380. }
  1381. }
  1382. /*
  1383. * See if we can find our Help file.
  1384. */
  1385. init_help();
  1386. /*
  1387. * Look for the PuTTY binary (we will enable the saved session
  1388. * submenu if we find it).
  1389. */
  1390. {
  1391. char b[2048], *p, *q, *r;
  1392. FILE *fp;
  1393. GetModuleFileName(NULL, b, sizeof(b) - 16);
  1394. r = b;
  1395. p = strrchr(b, '\\');
  1396. if (p && p >= r) r = p+1;
  1397. q = strrchr(b, ':');
  1398. if (q && q >= r) r = q+1;
  1399. strcpy(r, "putty.exe");
  1400. if ( (fp = fopen(b, "r")) != NULL) {
  1401. putty_path = dupstr(b);
  1402. fclose(fp);
  1403. } else
  1404. putty_path = NULL;
  1405. }
  1406. /*
  1407. * Process the command line, handling anything that can be done
  1408. * immediately, but deferring adding keys until after we've
  1409. * started up the main agent. Details of keys to be added are
  1410. * stored in the 'clkeys' array.
  1411. */
  1412. split_into_argv(cmdline, false, &argc, &argv, &argstart);
  1413. bool add_keys_encrypted = false;
  1414. AuxMatchOpt amo = aux_match_opt_init(argc, argv, 0, opt_error);
  1415. while (!aux_match_done(&amo)) {
  1416. char *val;
  1417. #define match_opt(...) aux_match_opt( \
  1418. &amo, NULL, __VA_ARGS__, (const char *)NULL)
  1419. #define match_optval(...) aux_match_opt( \
  1420. &amo, &val, __VA_ARGS__, (const char *)NULL)
  1421. if (aux_match_arg(&amo, &val)) {
  1422. /*
  1423. * Non-option arguments are expected to be key files, and
  1424. * added to clkeys.
  1425. */
  1426. sgrowarray(clkeys, clkeysize, nclkeys);
  1427. CommandLineKey *clkey = &clkeys[nclkeys++];
  1428. clkey->fn = filename_from_str(val);
  1429. clkey->add_encrypted = add_keys_encrypted;
  1430. } else if (match_opt("-pgpfp")) {
  1431. pgp_fingerprints_msgbox(NULL);
  1432. return 1;
  1433. } else if (match_opt("-restrict-acl", "-restrict_acl",
  1434. "-restrictacl")) {
  1435. restrict_process_acl();
  1436. } else if (match_opt("-restrict-putty-acl", "-restrict_putty_acl")) {
  1437. restrict_putty_acl = true;
  1438. } else if (match_opt("-no-decrypt", "-no_decrypt",
  1439. "-nodecrypt", "-encrypted")) {
  1440. add_keys_encrypted = true;
  1441. } else if (match_opt("-keylist")) {
  1442. show_keylist_on_startup = true;
  1443. } else if (match_optval("-openssh-config", "-openssh_config")) {
  1444. openssh_config_file = val;
  1445. } else if (match_optval("-unix")) {
  1446. unixsocket = val;
  1447. } else if (match_opt("-c")) {
  1448. /*
  1449. * If we see `-c', then the rest of the command line
  1450. * should be treated as a command to be spawned.
  1451. */
  1452. if (amo.index < amo.argc)
  1453. command = argstart[amo.index];
  1454. else
  1455. command = "";
  1456. break;
  1457. } else {
  1458. opt_error("unrecognised option '%s'\n", amo.argv[amo.index]);
  1459. }
  1460. }
  1461. /*
  1462. * Create and lock an interprocess mutex while we figure out
  1463. * whether we're going to be the Pageant server or a client. That
  1464. * way, two Pageant processes started up simultaneously will be
  1465. * able to agree on which one becomes the server without a race
  1466. * condition.
  1467. */
  1468. HANDLE mutex;
  1469. {
  1470. char *err;
  1471. char *mutexname = agent_mutex_name();
  1472. mutex = lock_interprocess_mutex(mutexname, &err);
  1473. sfree(mutexname);
  1474. if (!mutex) {
  1475. MessageBox(NULL, err, "Pageant Error", MB_ICONERROR | MB_OK);
  1476. return 1;
  1477. }
  1478. }
  1479. /*
  1480. * Find out if Pageant is already running.
  1481. */
  1482. already_running = agent_exists();
  1483. /*
  1484. * If it isn't, we're going to be the primary Pageant that stays
  1485. * running, so set up all the machinery to answer requests.
  1486. */
  1487. if (!already_running) {
  1488. /*
  1489. * Set up the window class for the hidden window that receives
  1490. * all the messages to do with our presence in the system tray.
  1491. */
  1492. if (!prev) {
  1493. WNDCLASS wndclass;
  1494. memset(&wndclass, 0, sizeof(wndclass));
  1495. wndclass.lpfnWndProc = TrayWndProc;
  1496. wndclass.hInstance = inst;
  1497. wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
  1498. wndclass.lpszClassName = TRAYCLASSNAME;
  1499. RegisterClass(&wndclass);
  1500. }
  1501. keylist = NULL;
  1502. traywindow = CreateWindow(TRAYCLASSNAME, TRAYWINTITLE,
  1503. WS_OVERLAPPEDWINDOW | WS_VSCROLL,
  1504. CW_USEDEFAULT, CW_USEDEFAULT,
  1505. 100, 100, NULL, NULL, inst, NULL);
  1506. winselgui_set_hwnd(traywindow);
  1507. /*
  1508. * Initialise the cross-platform Pageant code.
  1509. */
  1510. pageant_init();
  1511. /*
  1512. * Set up a named-pipe listener.
  1513. */
  1514. wpc->plc.vt = &winpgnt_vtable;
  1515. wpc->plc.suppress_logging = true;
  1516. if (should_have_security()) {
  1517. Plug *pl_plug;
  1518. struct pageant_listen_state *pl =
  1519. pageant_listener_new(&pl_plug, &wpc->plc);
  1520. char *pipename = agent_named_pipe_name();
  1521. Socket *sock = new_named_pipe_listener(pipename, pl_plug);
  1522. if (sk_socket_error(sock)) {
  1523. char *err = dupprintf("Unable to open named pipe at %s "
  1524. "for SSH agent:\n%s", pipename,
  1525. sk_socket_error(sock));
  1526. MessageBox(NULL, err, "Pageant Error", MB_ICONERROR | MB_OK);
  1527. return 1;
  1528. }
  1529. pageant_listener_got_socket(pl, sock);
  1530. /*
  1531. * If we've been asked to write out an OpenSSH config file
  1532. * pointing at the named pipe, do so.
  1533. */
  1534. if (openssh_config_file) {
  1535. FILE *fp = fopen(openssh_config_file, "w");
  1536. if (!fp) {
  1537. char *err = dupprintf("Unable to write OpenSSH config "
  1538. "file to %s", openssh_config_file);
  1539. MessageBox(NULL, err, "Pageant Error",
  1540. MB_ICONERROR | MB_OK);
  1541. return 1;
  1542. }
  1543. fputs("IdentityAgent \"", fp);
  1544. /* Some versions of Windows OpenSSH prefer / to \ as the path
  1545. * separator; others don't mind, but as far as we know, no
  1546. * version _objects_ to /, so we use it unconditionally. */
  1547. for (const char *p = pipename; *p; p++) {
  1548. char c = *p;
  1549. if (c == '\\')
  1550. c = '/';
  1551. fputc(c, fp);
  1552. }
  1553. fputs("\"\n", fp);
  1554. fclose(fp);
  1555. }
  1556. sfree(pipename);
  1557. }
  1558. /*
  1559. * Set up an AF_UNIX listener too, if we were asked to.
  1560. */
  1561. if (unixsocket) {
  1562. sk_init();
  1563. /* FIXME: diagnose any error except file-not-found. Also,
  1564. * check the file type if possible? */
  1565. remove(unixsocket);
  1566. Plug *pl_plug;
  1567. struct pageant_listen_state *pl =
  1568. pageant_listener_new(&pl_plug, &wpc->plc);
  1569. Socket *sock = sk_newlistener_unix(unixsocket, pl_plug);
  1570. if (sk_socket_error(sock)) {
  1571. char *err = dupprintf("Unable to open AF_UNIX socket at %s "
  1572. "for SSH agent:\n%s", unixsocket,
  1573. sk_socket_error(sock));
  1574. MessageBox(NULL, err, "Pageant Error", MB_ICONERROR | MB_OK);
  1575. return 1;
  1576. }
  1577. pageant_listener_got_socket(pl, sock);
  1578. }
  1579. /*
  1580. * Set up the window class for the hidden window that receives
  1581. * the WM_COPYDATA message used by the old-style Pageant IPC
  1582. * system.
  1583. */
  1584. if (!prev) {
  1585. WNDCLASS wndclass;
  1586. memset(&wndclass, 0, sizeof(wndclass));
  1587. wndclass.lpfnWndProc = wm_copydata_WndProc;
  1588. wndclass.hInstance = inst;
  1589. wndclass.lpszClassName = IPCCLASSNAME;
  1590. RegisterClass(&wndclass);
  1591. }
  1592. /*
  1593. * And launch the subthread which will open that hidden window and
  1594. * handle WM_COPYDATA messages on it.
  1595. */
  1596. wmcpc.vt = &wmcpc_vtable;
  1597. wmcpc.suppress_logging = true;
  1598. pageant_register_client(&wmcpc);
  1599. DWORD wm_copydata_threadid;
  1600. wmct.ev_msg_ready = CreateEvent(NULL, false, false, NULL);
  1601. wmct.ev_reply_ready = CreateEvent(NULL, false, false, NULL);
  1602. HANDLE hThread = CreateThread(NULL, 0, wm_copydata_threadfunc,
  1603. &inst, 0, &wm_copydata_threadid);
  1604. if (hThread)
  1605. CloseHandle(hThread); /* we don't need the thread handle */
  1606. add_handle_wait(wmct.ev_msg_ready, wm_copydata_got_msg, NULL);
  1607. }
  1608. /*
  1609. * Now we're either a fully set up Pageant server, or we know one
  1610. * is running somewhere else. Either way, now it's safe to unlock
  1611. * the mutex.
  1612. */
  1613. unlock_interprocess_mutex(mutex);
  1614. /*
  1615. * Add any keys provided on the command line.
  1616. */
  1617. for (size_t i = 0; i < nclkeys; i++) {
  1618. CommandLineKey *clkey = &clkeys[i];
  1619. win_add_keyfile(clkey->fn, clkey->add_encrypted);
  1620. filename_free(clkey->fn);
  1621. }
  1622. sfree(clkeys);
  1623. /* And forget any passphrases we stashed during that loop. */
  1624. pageant_forget_passphrases();
  1625. /*
  1626. * Now our keys are present, spawn a command, if we were asked to.
  1627. */
  1628. if (command) {
  1629. char *args;
  1630. if (command[0] == '"')
  1631. args = strchr(++command, '"');
  1632. else
  1633. args = strchr(command, ' ');
  1634. if (args) {
  1635. *args++ = 0;
  1636. while (*args && isspace((unsigned char)*args)) args++;
  1637. }
  1638. spawn_cmd(command, args, show);
  1639. }
  1640. /*
  1641. * If Pageant was already running, we leave now. If we haven't
  1642. * even taken any auxiliary action (spawned a command or added
  1643. * keys), complain.
  1644. */
  1645. if (already_running) {
  1646. if (!command && !nclkeys) {
  1647. MessageBox(NULL, "Pageant is already running", "Pageant Error",
  1648. MB_ICONERROR | MB_OK);
  1649. }
  1650. return 0;
  1651. }
  1652. /* Set up a system tray icon */
  1653. AddTrayIcon(traywindow);
  1654. /* Accelerators used: nsvkxa */
  1655. systray_menu = CreatePopupMenu();
  1656. if (putty_path) {
  1657. session_menu = CreateMenu();
  1658. AppendMenu(systray_menu, MF_ENABLED, IDM_PUTTY, "&New Session");
  1659. AppendMenu(systray_menu, MF_POPUP | MF_ENABLED,
  1660. (UINT_PTR) session_menu, "&Saved Sessions");
  1661. AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
  1662. }
  1663. AppendMenu(systray_menu, MF_ENABLED, IDM_VIEWKEYS,
  1664. "&View Keys");
  1665. AppendMenu(systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key");
  1666. AppendMenu(systray_menu, MF_ENABLED, IDM_ADDKEY_ENCRYPTED,
  1667. "Add key (encrypted)");
  1668. AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
  1669. AppendMenu(systray_menu, MF_ENABLED, IDM_REMOVE_ALL,
  1670. "Remove All Keys");
  1671. AppendMenu(systray_menu, MF_ENABLED, IDM_REENCRYPT_ALL,
  1672. "Re-encrypt All Keys");
  1673. AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
  1674. if (has_help())
  1675. AppendMenu(systray_menu, MF_ENABLED, IDM_HELP, "&Help");
  1676. AppendMenu(systray_menu, MF_ENABLED, IDM_ABOUT, "&About");
  1677. AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
  1678. AppendMenu(systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
  1679. initial_menuitems_count = GetMenuItemCount(session_menu);
  1680. /* Set the default menu item. */
  1681. SetMenuDefaultItem(systray_menu, IDM_VIEWKEYS, false);
  1682. ShowWindow(traywindow, SW_HIDE);
  1683. /* Open the visible key list window, if we've been asked to. */
  1684. if (show_keylist_on_startup)
  1685. create_keylist_window();
  1686. /*
  1687. * Main message loop.
  1688. */
  1689. while (true) {
  1690. int n;
  1691. HandleWaitList *hwl = get_handle_wait_list();
  1692. DWORD timeout = toplevel_callback_pending() ? 0 : INFINITE;
  1693. n = MsgWaitForMultipleObjects(hwl->nhandles, hwl->handles, false,
  1694. timeout, QS_ALLINPUT);
  1695. if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)hwl->nhandles)
  1696. handle_wait_activate(hwl, n - WAIT_OBJECT_0);
  1697. handle_wait_list_free(hwl);
  1698. while (sw_PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
  1699. if (msg.message == WM_QUIT)
  1700. goto finished; /* two-level break */
  1701. if (IsWindow(keylist) && IsDialogMessage(keylist, &msg))
  1702. continue;
  1703. if (IsWindow(aboutbox) && IsDialogMessage(aboutbox, &msg))
  1704. continue;
  1705. if (IsWindow(nonmodal_passphrase_hwnd) &&
  1706. IsDialogMessage(nonmodal_passphrase_hwnd, &msg))
  1707. continue;
  1708. TranslateMessage(&msg);
  1709. DispatchMessage(&msg);
  1710. }
  1711. run_toplevel_callbacks();
  1712. }
  1713. finished:
  1714. /* Clean up the system tray icon */
  1715. {
  1716. NOTIFYICONDATA tnid;
  1717. tnid.cbSize = sizeof(NOTIFYICONDATA);
  1718. tnid.hWnd = traywindow;
  1719. tnid.uID = 1;
  1720. Shell_NotifyIcon(NIM_DELETE, &tnid);
  1721. DestroyMenu(systray_menu);
  1722. }
  1723. if (keypath) filereq_free(keypath);
  1724. if (openssh_config_file) {
  1725. /*
  1726. * Leave this file around, but empty it, so that it doesn't
  1727. * refer to a pipe we aren't listening on any more.
  1728. */
  1729. FILE *fp = fopen(openssh_config_file, "w");
  1730. if (fp)
  1731. fclose(fp);
  1732. }
  1733. cleanup_exit(msg.wParam);
  1734. return msg.wParam; /* just in case optimiser complains */
  1735. }