2 * Pageant: the PuTTY Authentication Agent.
13 #define IDI_MAINICON 200
14 #define IDI_TRAYICON 201
16 #define WM_XUSER (WM_USER + 0x2000)
17 #define WM_SYSTRAY (WM_XUSER + 6)
18 #define WM_SYSTRAY2 (WM_XUSER + 7)
20 #define AGENT_COPYDATA_ID 0x804e50ba /* random goop */
23 * FIXME: maybe some day we can sort this out ...
25 #define AGENT_MAX_MSGLEN 8192
27 #define IDM_CLOSE 0x0010
28 #define IDM_VIEWKEYS 0x0020
29 #define IDM_ADDKEY 0x0030
30 #define IDM_ABOUT 0x0040
32 #define APPNAME "Pageant"
34 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1
35 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2
36 #define SSH_AGENTC_RSA_CHALLENGE 3
37 #define SSH_AGENT_RSA_RESPONSE 4
38 #define SSH_AGENT_FAILURE 5
39 #define SSH_AGENT_SUCCESS 6
40 #define SSH_AGENTC_ADD_RSA_IDENTITY 7
41 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8
45 static HINSTANCE instance;
49 static HMENU systray_menu;
51 static tree234 *rsakeys;
53 static int has_security;
55 typedef DWORD (WINAPI *gsi_fn_t)
56 (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
57 PSID *, PSID *, PACL *, PACL *,
58 PSECURITY_DESCRIPTOR *);
59 static gsi_fn_t getsecurityinfo;
63 * We need this to link with the RSA code, because rsaencrypt()
64 * pads its data with random bytes. Since we only use rsadecrypt(),
65 * which is deterministic, this should never be called.
67 * If it _is_ called, there is a _serious_ problem, because it
68 * won't generate true random numbers. So we must scream, panic,
69 * and exit immediately if that should happen.
71 int random_byte(void) {
72 MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
77 * This function is needed to link with the DES code. We need not
78 * have it do anything at all.
80 void logevent(char *msg) {
83 #define GET_32BIT(cp) \
84 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
85 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
86 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
87 ((unsigned long)(unsigned char)(cp)[3]))
89 #define PUT_32BIT(cp, value) { \
90 (cp)[0] = (unsigned char)((value) >> 24); \
91 (cp)[1] = (unsigned char)((value) >> 16); \
92 (cp)[2] = (unsigned char)((value) >> 8); \
93 (cp)[3] = (unsigned char)(value); }
95 #define PASSPHRASE_MAXLEN 512
97 struct PassphraseProcStruct {
103 * Dialog-box function for the Licence box.
105 static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
106 WPARAM wParam, LPARAM lParam) {
111 switch (LOWORD(wParam)) {
125 * Dialog-box function for the About box.
127 static int CALLBACK AboutProc (HWND hwnd, UINT msg,
128 WPARAM wParam, LPARAM lParam) {
131 SetDlgItemText (hwnd, 100, ver);
134 switch (LOWORD(wParam)) {
137 DestroyWindow (hwnd);
140 EnableWindow(hwnd, 0);
141 DialogBox (instance, MAKEINTRESOURCE(214), NULL, LicenceProc);
142 EnableWindow(hwnd, 1);
143 SetActiveWindow(hwnd);
149 DestroyWindow (hwnd);
156 * Dialog-box function for the passphrase box.
158 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
159 WPARAM wParam, LPARAM lParam) {
160 static char *passphrase;
161 struct PassphraseProcStruct *p;
165 SetForegroundWindow(hwnd);
166 SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
167 SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
168 p = (struct PassphraseProcStruct *)lParam;
169 passphrase = p->passphrase;
171 SetDlgItemText(hwnd, 101, p->comment);
175 switch (LOWORD(wParam)) {
185 case 102: /* edit box */
186 if (HIWORD(wParam) == EN_CHANGE) {
187 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
188 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
201 * Update the visible key list.
203 static void keylist_update(void) {
208 SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0);
209 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
210 char listentry[512], *p;
212 * Replace two spaces in the fingerprint with tabs, for
213 * nice alignment in the box.
215 rsa_fingerprint(listentry, sizeof(listentry), key);
216 p = strchr(listentry, ' '); if (p) *p = '\t';
217 p = strchr(listentry, ' '); if (p) *p = '\t';
218 SendDlgItemMessage (keylist, 100, LB_ADDSTRING,
219 0, (LPARAM)listentry);
221 SendDlgItemMessage (keylist, 100, LB_SETCURSEL, (WPARAM) -1, 0);
226 * This function loads a key from a file and adds it.
228 static void add_keyfile(char *filename) {
229 char passphrase[PASSPHRASE_MAXLEN];
235 struct PassphraseProcStruct pps;
237 needs_pass = rsakey_encrypted(filename, &comment);
239 key = malloc(sizeof(*key));
240 pps.passphrase = passphrase;
241 pps.comment = comment;
245 dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
246 NULL, PassphraseProc,
249 if (comment) free(comment);
251 return; /* operation cancelled */
255 ret = loadrsakey(filename, key, NULL, passphrase);
258 if (comment) free(comment);
260 MessageBox(NULL, "Couldn't load private key.", APPNAME,
261 MB_OK | MB_ICONERROR);
265 if (add234(rsakeys, key) != key)
266 free(key); /* already present, don't waste RAM */
270 * This is the main agent function that answers messages.
272 static void answer_msg(void *msg) {
273 unsigned char *p = msg;
274 unsigned char *ret = msg;
278 * Get the message type.
284 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
286 * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
294 * Count up the number and length of keys we hold.
297 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
299 len += 4; /* length field */
300 len += ssh1_bignum_length(key->exponent);
301 len += ssh1_bignum_length(key->modulus);
302 len += 4 + strlen(key->comment);
306 * Packet header is the obvious five bytes, plus four
307 * bytes for the key count.
310 if (len > AGENT_MAX_MSGLEN)
311 goto failure; /* aaargh! too much stuff! */
312 PUT_32BIT(ret, len-4);
313 ret[4] = SSH_AGENT_RSA_IDENTITIES_ANSWER;
314 PUT_32BIT(ret+5, nkeys);
316 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
317 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus));
319 p += ssh1_write_bignum(p, key->exponent);
320 p += ssh1_write_bignum(p, key->modulus);
321 PUT_32BIT(p, strlen(key->comment));
322 memcpy(p+4, key->comment, strlen(key->comment));
323 p += 4 + strlen(key->comment);
327 case SSH_AGENTC_RSA_CHALLENGE:
329 * Reply with either SSH_AGENT_RSA_RESPONSE or
330 * SSH_AGENT_FAILURE, depending on whether we have that key
334 struct RSAKey reqkey, *key;
335 Bignum challenge, response;
336 unsigned char response_source[48], response_md5[16];
337 struct MD5Context md5c;
341 p += ssh1_read_bignum(p, &reqkey.exponent);
342 p += ssh1_read_bignum(p, &reqkey.modulus);
343 p += ssh1_read_bignum(p, &challenge);
344 memcpy(response_source+32, p, 16); p += 16;
345 if (GET_32BIT(p) != 1 ||
346 (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
347 freebn(reqkey.exponent);
348 freebn(reqkey.modulus);
352 response = rsadecrypt(challenge, key);
353 for (i = 0; i < 32; i++)
354 response_source[i] = bignum_byte(response, 31-i);
357 MD5Update(&md5c, response_source, 48);
358 MD5Final(response_md5, &md5c);
359 memset(response_source, 0, 48); /* burn the evidence */
360 freebn(response); /* and that evidence */
361 freebn(challenge); /* yes, and that evidence */
362 freebn(reqkey.exponent); /* and free some memory ... */
363 freebn(reqkey.modulus); /* ... while we're at it. */
366 * Packet is the obvious five byte header, plus sixteen
370 PUT_32BIT(ret, len-4);
371 ret[4] = SSH_AGENT_RSA_RESPONSE;
372 memcpy(ret+5, response_md5, 16);
375 case SSH_AGENTC_ADD_RSA_IDENTITY:
377 * Add to the list and return SSH_AGENT_SUCCESS, or
378 * SSH_AGENT_FAILURE if the key was malformed.
383 key = malloc(sizeof(struct RSAKey));
384 memset(key, 0, sizeof(key));
385 p += makekey(p, key, NULL, 1);
386 p += makeprivate(p, key);
387 p += ssh1_read_bignum(p, NULL); /* p^-1 mod q */
388 p += ssh1_read_bignum(p, NULL); /* p */
389 p += ssh1_read_bignum(p, NULL); /* q */
390 comment = malloc(GET_32BIT(p));
392 memcpy(comment, p+4, GET_32BIT(p));
393 key->comment = comment;
396 ret[4] = SSH_AGENT_FAILURE;
397 if (add234(rsakeys, key) == key) {
399 ret[4] = SSH_AGENT_SUCCESS;
406 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
408 * Remove from the list and return SSH_AGENT_SUCCESS, or
409 * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
413 struct RSAKey reqkey, *key;
415 p += makekey(p, &reqkey, NULL, 0);
416 key = find234(rsakeys, &reqkey, NULL);
417 freebn(reqkey.exponent);
418 freebn(reqkey.modulus);
420 ret[4] = SSH_AGENT_FAILURE;
422 del234(rsakeys, key);
425 ret[4] = SSH_AGENT_SUCCESS;
432 * Unrecognised message. Return SSH_AGENT_FAILURE.
435 ret[4] = SSH_AGENT_FAILURE;
441 * Key comparison function for the 2-3-4 tree of RSA keys.
443 static int cmpkeys(void *av, void *bv) {
444 struct RSAKey *a = (struct RSAKey *)av;
445 struct RSAKey *b = (struct RSAKey *)bv;
452 * Compare by length of moduli.
454 alen = ssh1_bignum_bitcount(am);
455 blen = ssh1_bignum_bitcount(bm);
456 if (alen > blen) return +1; else if (alen < blen) return -1;
458 * Now compare by moduli themselves.
460 alen = (alen + 7) / 8; /* byte count */
463 abyte = bignum_byte(am, alen);
464 bbyte = bignum_byte(bm, alen);
465 if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
473 static void error(char *s) {
474 MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
478 * Prompt for a key file to add, and add it.
480 static void prompt_add_keyfile(void) {
482 char filename[FILENAME_MAX];
483 memset(&of, 0, sizeof(of));
484 #ifdef OPENFILENAME_SIZE_VERSION_400
485 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
487 of.lStructSize = sizeof(of);
490 of.lpstrFilter = "All Files\0*\0\0\0";
491 of.lpstrCustomFilter = NULL;
493 of.lpstrFile = filename; *filename = '\0';
494 of.nMaxFile = sizeof(filename);
495 of.lpstrFileTitle = NULL;
496 of.lpstrInitialDir = NULL;
497 of.lpstrTitle = "Select Private Key File";
499 if (GetOpenFileName(&of)) {
500 add_keyfile(filename);
506 * Dialog-box function for the key list box.
508 static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
509 WPARAM wParam, LPARAM lParam) {
517 static int tabs[2] = {25, 175};
518 SendDlgItemMessage (hwnd, 100, LB_SETTABSTOPS, 2,
524 switch (LOWORD(wParam)) {
530 case 101: /* add key */
531 if (HIWORD(wParam) == BN_CLICKED ||
532 HIWORD(wParam) == BN_DOUBLECLICKED) {
533 prompt_add_keyfile();
536 case 102: /* remove key */
537 if (HIWORD(wParam) == BN_CLICKED ||
538 HIWORD(wParam) == BN_DOUBLECLICKED) {
539 int n = SendDlgItemMessage (hwnd, 100, LB_GETCURSEL, 0, 0);
544 for (key = first234(rsakeys, &e); key; key = next234(&e))
547 del234(rsakeys, key);
548 freersakey(key); free(key);
562 static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
563 WPARAM wParam, LPARAM lParam) {
565 static int menuinprogress;
569 if (lParam == WM_RBUTTONUP) {
571 GetCursorPos(&cursorpos);
572 PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
573 } else if (lParam == WM_LBUTTONDBLCLK) {
574 /* Equivalent to IDM_VIEWKEYS. */
575 PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
579 if (!menuinprogress) {
581 SetForegroundWindow(hwnd);
582 ret = TrackPopupMenu(systray_menu,
583 TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
585 wParam, lParam, 0, hwnd, NULL);
591 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
593 SendMessage(hwnd, WM_CLOSE, 0, 0);
597 keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
599 ShowWindow (keylist, SW_SHOWNORMAL);
601 * Sometimes the window comes up minimised / hidden
602 * for no obvious reason. Prevent this.
604 SetForegroundWindow(keylist);
605 SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
606 SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
610 prompt_add_keyfile();
614 aboutbox = CreateDialog (instance, MAKEINTRESOURCE(213),
616 ShowWindow (aboutbox, SW_SHOWNORMAL);
618 * Sometimes the window comes up minimised / hidden
619 * for no obvious reason. Prevent this.
621 SetForegroundWindow(aboutbox);
622 SetWindowPos (aboutbox, HWND_TOP, 0, 0, 0, 0,
623 SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
636 HANDLE filemap, proc;
637 PSID mapowner, procowner;
638 PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
641 cds = (COPYDATASTRUCT *)lParam;
642 if (cds->dwData != AGENT_COPYDATA_ID)
643 return 0; /* not our message, mate */
644 mapname = (char *)cds->lpData;
645 if (mapname[cds->cbData - 1] != '\0')
646 return 0; /* failure to be ASCIZ! */
648 debug(("mapname is :%s:\r\n", mapname));
650 filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
652 debug(("filemap is %p\r\n", filemap));
654 if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
658 if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
659 GetCurrentProcessId())) == NULL) {
661 debug(("couldn't get handle for process\r\n"));
665 if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
666 OWNER_SECURITY_INFORMATION,
667 &procowner, NULL, NULL, NULL,
668 &psd2) != ERROR_SUCCESS) {
670 debug(("couldn't get owner info for process\r\n"));
673 return 0; /* unable to get security info */
676 if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
677 OWNER_SECURITY_INFORMATION,
678 &mapowner, NULL, NULL, NULL,
679 &psd1) != ERROR_SUCCESS)) {
681 debug(("couldn't get owner info for filemap: %d\r\n", rc));
686 debug(("got security stuff\r\n"));
688 if (!EqualSid(mapowner, procowner))
689 return 0; /* security ID mismatch! */
691 debug(("security stuff matched\r\n"));
697 debug(("security APIs not present\r\n"));
701 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
703 debug(("p is %p\r\n", p));
704 {int i; for(i=0;i<5;i++)debug(("p[%d]=%02x\r\n", i, ((unsigned char *)p)[i]));}
710 CloseHandle(filemap);
715 return DefWindowProc (hwnd, message, wParam, lParam);
718 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
725 * Determine whether we're an NT system (should have security
726 * APIs) or a non-NT system (don't do security).
728 memset(&osi, 0, sizeof(OSVERSIONINFO));
729 osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
730 if (GetVersionEx(&osi) && osi.dwPlatformId==VER_PLATFORM_WIN32_NT) {
733 has_security = FALSE;
738 * Attempt to ge the security API we need.
740 advapi = LoadLibrary("ADVAPI32.DLL");
741 getsecurityinfo = (gsi_fn_t)GetProcAddress(advapi, "GetSecurityInfo");
742 if (!getsecurityinfo) {
744 "Unable to access security APIs. Pageant will\n"
745 "not run, in case it causes a security breach.",
746 "Pageant Fatal Error", MB_ICONERROR | MB_OK);
751 "This program has been compiled for Win9X and will\n"
752 "not run on NT, in case it causes a security breach.",
753 "Pageant Fatal Error", MB_ICONERROR | MB_OK);
760 * First bomb out totally if we are already running.
762 if (FindWindow("Pageant", "Pageant")) {
763 MessageBox(NULL, "Pageant is already running", "Pageant Error",
764 MB_ICONERROR | MB_OK);
765 if (advapi) FreeLibrary(advapi);
773 wndclass.lpfnWndProc = WndProc;
774 wndclass.cbClsExtra = 0;
775 wndclass.cbWndExtra = 0;
776 wndclass.hInstance = inst;
777 wndclass.hIcon = LoadIcon (inst,
778 MAKEINTRESOURCE(IDI_MAINICON));
779 wndclass.hCursor = LoadCursor (NULL, IDC_IBEAM);
780 wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
781 wndclass.lpszMenuName = NULL;
782 wndclass.lpszClassName = APPNAME;
784 RegisterClass (&wndclass);
787 hwnd = keylist = NULL;
789 hwnd = CreateWindow (APPNAME, APPNAME,
790 WS_OVERLAPPEDWINDOW | WS_VSCROLL,
791 CW_USEDEFAULT, CW_USEDEFAULT,
792 100, 100, NULL, NULL, inst, NULL);
794 /* Set up a system tray icon */
800 #ifdef NIM_SETVERSION
802 res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
805 tnid.cbSize = sizeof(NOTIFYICONDATA);
807 tnid.uID = 1; /* unique within this systray use */
808 tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
809 tnid.uCallbackMessage = WM_SYSTRAY;
810 tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
811 strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
813 res = Shell_NotifyIcon(NIM_ADD, &tnid);
818 systray_menu = CreatePopupMenu();
819 /* accelerators used: vkxa */
820 AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "&View Keys");
821 AppendMenu (systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key");
822 AppendMenu (systray_menu, MF_ENABLED, IDM_ABOUT, "&About");
823 AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
826 ShowWindow (hwnd, SW_HIDE);
829 * Initialise storage for RSA keys.
831 rsakeys = newtree234(cmpkeys);
834 * Process the command line and add RSA keys as listed on it.
841 while (*p && isspace(*p)) p++;
842 if (*p && !isspace(*p)) {
843 char *q = p, *pp = p;
844 while (*p && (inquotes || !isspace(*p)))
847 inquotes = !inquotes;
865 while (GetMessage(&msg, NULL, 0, 0) == 1) {
866 TranslateMessage(&msg);
867 DispatchMessage(&msg);
870 /* Clean up the system tray icon */
874 tnid.cbSize = sizeof(NOTIFYICONDATA);
878 Shell_NotifyIcon(NIM_DELETE, &tnid);
880 DestroyMenu(systray_menu);
883 if (advapi) FreeLibrary(advapi);