2 * Pageant: the PuTTY Authentication Agent.
7 #include <stdio.h> /* FIXME */
8 #include "putty.h" /* FIXME */
12 #define IDI_MAINICON 200
13 #define IDI_TRAYICON 201
15 #define WM_XUSER (WM_USER + 0x2000)
16 #define WM_SYSTRAY (WM_XUSER + 6)
17 #define WM_SYSTRAY2 (WM_XUSER + 7)
19 #define AGENT_COPYDATA_ID 0x804e50ba /* random goop */
22 * FIXME: maybe some day we can sort this out ...
24 #define AGENT_MAX_MSGLEN 8192
26 #define IDM_CLOSE 0x0010
27 #define IDM_VIEWKEYS 0x0020
29 #define APPNAME "Pageant"
31 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1
32 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2
33 #define SSH_AGENTC_RSA_CHALLENGE 3
34 #define SSH_AGENT_RSA_RESPONSE 4
35 #define SSH_AGENT_FAILURE 5
36 #define SSH_AGENT_SUCCESS 6
37 #define SSH_AGENTC_ADD_RSA_IDENTITY 7
38 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8
48 typedef DWORD (WINAPI *gsi_fn_t)
49 (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
50 PSID *, PSID *, PACL *, PACL *,
51 PSECURITY_DESCRIPTOR *);
52 gsi_fn_t getsecurityinfo;
55 * We need this to link with the RSA code, because rsaencrypt()
56 * pads its data with random bytes. Since we only use rsadecrypt(),
57 * which is deterministic, this should never be called.
59 * If it _is_ called, there is a _serious_ problem, because it
60 * won't generate true random numbers. So we must scream, panic,
61 * and exit immediately if that should happen.
63 int random_byte(void) {
64 MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
69 * This function is needed to link with the DES code. We need not
70 * have it do anything at all.
72 void logevent(char *msg) {
75 #define GET_32BIT(cp) \
76 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
77 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
78 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
79 ((unsigned long)(unsigned char)(cp)[3]))
81 #define PUT_32BIT(cp, value) { \
82 (cp)[0] = (unsigned char)((value) >> 24); \
83 (cp)[1] = (unsigned char)((value) >> 16); \
84 (cp)[2] = (unsigned char)((value) >> 8); \
85 (cp)[3] = (unsigned char)(value); }
87 #define PASSPHRASE_MAXLEN 512
90 * Dialog-box function for the passphrase box.
92 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
93 WPARAM wParam, LPARAM lParam) {
94 static char *passphrase;
98 passphrase = (char *)lParam;
102 switch (LOWORD(wParam)) {
112 case 102: /* edit box */
113 if (HIWORD(wParam) == EN_CHANGE) {
114 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
115 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
128 * Update the visible key list.
130 void keylist_update(void) {
135 SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0);
136 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
137 SendDlgItemMessage (keylist, 100, LB_ADDSTRING,
138 0, (LPARAM) key->comment);
140 SendDlgItemMessage (keylist, 100, LB_SETCURSEL, (WPARAM) -1, 0);
145 * This function loads a key from a file and adds it.
147 void add_keyfile(char *filename) {
148 char passphrase[PASSPHRASE_MAXLEN];
154 /* FIXME: we can acquire comment here and use it in dialog */
155 needs_pass = rsakey_encrypted(filename, NULL);
157 key = malloc(sizeof(*key));
161 dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
162 NULL, PassphraseProc,
166 return; /* operation cancelled */
170 ret = loadrsakey(filename, key, passphrase);
174 MessageBox(NULL, "Couldn't load public key.", APPNAME,
175 MB_OK | MB_ICONERROR);
179 if (add234(rsakeys, key) != key)
180 free(key); /* already present, don't waste RAM */
184 * This is the main agent function that answers messages.
186 void answer_msg(void *msg) {
187 unsigned char *p = msg;
188 unsigned char *ret = msg;
192 * Get the message type.
198 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
200 * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
208 * Count up the number and length of keys we hold.
211 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
213 len += 4; /* length field */
214 len += ssh1_bignum_length(key->exponent);
215 len += ssh1_bignum_length(key->modulus);
216 len += 4 + strlen(key->comment);
220 * Packet header is the obvious five bytes, plus four
221 * bytes for the key count.
224 if (len > AGENT_MAX_MSGLEN)
225 goto failure; /* aaargh! too much stuff! */
226 PUT_32BIT(ret, len-4);
227 ret[4] = SSH_AGENT_RSA_IDENTITIES_ANSWER;
228 PUT_32BIT(ret+5, nkeys);
230 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
231 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus));
233 p += ssh1_write_bignum(p, key->exponent);
234 p += ssh1_write_bignum(p, key->modulus);
235 PUT_32BIT(p, strlen(key->comment));
236 memcpy(p+4, key->comment, strlen(key->comment));
237 p += 4 + strlen(key->comment);
241 case SSH_AGENTC_RSA_CHALLENGE:
243 * Reply with either SSH_AGENT_RSA_RESPONSE or
244 * SSH_AGENT_FAILURE, depending on whether we have that key
248 struct RSAKey reqkey, *key;
249 Bignum challenge, response;
250 unsigned char response_source[48], response_md5[16];
251 struct MD5Context md5c;
255 p += ssh1_read_bignum(p, &reqkey.exponent);
256 p += ssh1_read_bignum(p, &reqkey.modulus);
257 p += ssh1_read_bignum(p, &challenge);
258 memcpy(response_source+32, p, 16); p += 16;
259 if (GET_32BIT(p) != 1 ||
260 (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
261 freebn(reqkey.exponent);
262 freebn(reqkey.modulus);
266 response = rsadecrypt(challenge, key);
267 for (i = 0; i < 32; i++)
268 response_source[i] = bignum_byte(response, 31-i);
271 MD5Update(&md5c, response_source, 48);
272 MD5Final(response_md5, &md5c);
273 memset(response_source, 0, 48); /* burn the evidence */
274 freebn(response); /* and that evidence */
275 freebn(challenge); /* yes, and that evidence */
276 freebn(reqkey.exponent); /* and free some memory ... */
277 freebn(reqkey.modulus); /* ... while we're at it. */
280 * Packet is the obvious five byte header, plus sixteen
284 PUT_32BIT(ret, len-4);
285 ret[4] = SSH_AGENT_RSA_RESPONSE;
286 memcpy(ret+5, response_md5, 16);
289 case SSH_AGENTC_ADD_RSA_IDENTITY:
291 * Add to the list and return SSH_AGENT_SUCCESS, or
292 * SSH_AGENT_FAILURE if the key was malformed.
297 key = malloc(sizeof(struct RSAKey));
298 memset(key, 0, sizeof(key));
299 p += makekey(p, key, NULL, 1);
300 p += makeprivate(p, key);
301 p += ssh1_read_bignum(p, NULL); /* p^-1 mod q */
302 p += ssh1_read_bignum(p, NULL); /* p */
303 p += ssh1_read_bignum(p, NULL); /* q */
304 comment = malloc(GET_32BIT(p));
306 memcpy(comment, p+4, GET_32BIT(p));
307 key->comment = comment;
310 ret[4] = SSH_AGENT_FAILURE;
311 if (add234(rsakeys, key) == key) {
313 ret[4] = SSH_AGENT_SUCCESS;
319 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
321 * Remove from the list and return SSH_AGENT_SUCCESS, or
322 * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
326 struct RSAKey reqkey, *key;
328 p += makekey(p, &reqkey, NULL, 0);
329 key = find234(rsakeys, &reqkey, NULL);
330 freebn(reqkey.exponent);
331 freebn(reqkey.modulus);
333 ret[4] = SSH_AGENT_FAILURE;
335 del234(rsakeys, key);
337 ret[4] = SSH_AGENT_SUCCESS;
344 * Unrecognised message. Return SSH_AGENT_FAILURE.
347 ret[4] = SSH_AGENT_FAILURE;
353 * Key comparison function for the 2-3-4 tree of RSA keys.
355 int cmpkeys(void *av, void *bv) {
356 struct RSAKey *a = (struct RSAKey *)av;
357 struct RSAKey *b = (struct RSAKey *)bv;
364 * Compare by length of moduli.
366 alen = ssh1_bignum_bitcount(am);
367 blen = ssh1_bignum_bitcount(bm);
368 if (alen > blen) return +1; else if (alen < blen) return -1;
370 * Now compare by moduli themselves.
372 alen = (alen + 7) / 8; /* byte count */
375 abyte = bignum_byte(am, alen);
376 bbyte = bignum_byte(bm, alen);
377 if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
385 static void error(char *s) {
386 MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
390 * Dialog-box function for the key list box.
392 static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
393 WPARAM wParam, LPARAM lParam) {
397 char filename[FILENAME_MAX];
401 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
402 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
403 0, (LPARAM) key->comment);
407 switch (LOWORD(wParam)) {
413 case 101: /* add key */
414 if (HIWORD(wParam) == BN_CLICKED ||
415 HIWORD(wParam) == BN_DOUBLECLICKED) {
416 memset(&of, 0, sizeof(of));
417 #ifdef OPENFILENAME_SIZE_VERSION_400
418 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
420 of.lStructSize = sizeof(of);
423 of.lpstrFilter = "All Files\0*\0\0\0";
424 of.lpstrCustomFilter = NULL;
426 of.lpstrFile = filename; *filename = '\0';
427 of.nMaxFile = sizeof(filename);
428 of.lpstrFileTitle = NULL;
429 of.lpstrInitialDir = NULL;
430 of.lpstrTitle = "Select Public Key File";
432 if (GetOpenFileName(&of)) {
433 add_keyfile(filename);
438 case 102: /* remove key */
439 if (HIWORD(wParam) == BN_CLICKED ||
440 HIWORD(wParam) == BN_DOUBLECLICKED) {
441 int n = SendDlgItemMessage (hwnd, 100, LB_GETCURSEL, 0, 0);
442 if (n == LB_ERR || n == 0) {
446 for (key = first234(rsakeys, &e); key; key = next234(&e))
449 del234(rsakeys, key);
450 freersakey(key); free(key);
451 SendDlgItemMessage(hwnd, 100, LB_RESETCONTENT, 0, 0);
452 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
453 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
454 0, (LPARAM) key->comment);
456 SendDlgItemMessage (hwnd, 100, LB_SETCURSEL, (WPARAM) -1, 0);
469 static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
470 WPARAM wParam, LPARAM lParam) {
472 static int menuinprogress;
476 if (lParam == WM_RBUTTONUP) {
478 GetCursorPos(&cursorpos);
479 PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
480 } else if (lParam == WM_LBUTTONDBLCLK) {
481 /* Equivalent to IDM_VIEWKEYS. */
482 PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
486 if (!menuinprogress) {
488 SetForegroundWindow(hwnd);
489 ret = TrackPopupMenu(systray_menu,
490 TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
492 wParam, lParam, 0, hwnd, NULL);
498 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
500 SendMessage(hwnd, WM_CLOSE, 0, 0);
504 keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
506 ShowWindow (keylist, SW_SHOWNORMAL);
508 * Sometimes the window comes up minimised / hidden
509 * for no obvious reason. Prevent this.
511 SetForegroundWindow(keylist);
512 SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
513 SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
526 HANDLE filemap, proc;
527 PSID mapowner, procowner;
528 PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
531 cds = (COPYDATASTRUCT *)lParam;
532 if (cds->dwData != AGENT_COPYDATA_ID)
533 return 0; /* not our message, mate */
534 mapname = (char *)cds->lpData;
535 if (mapname[cds->cbData - 1] != '\0')
536 return 0; /* failure to be ASCIZ! */
538 debug(("mapname is :%s:\r\n", mapname));
540 filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
542 debug(("filemap is %p\r\n", filemap));
544 if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
547 if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
548 GetCurrentProcessId())) == NULL) {
550 debug(("couldn't get handle for process\r\n"));
554 if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
555 OWNER_SECURITY_INFORMATION,
556 &procowner, NULL, NULL, NULL,
557 &psd2) != ERROR_SUCCESS) {
559 debug(("couldn't get owner info for process\r\n"));
562 return 0; /* unable to get security info */
565 if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
566 OWNER_SECURITY_INFORMATION,
567 &mapowner, NULL, NULL, NULL,
568 &psd1) != ERROR_SUCCESS)) {
570 debug(("couldn't get owner info for filemap: %d\r\n", rc));
575 debug(("got security stuff\r\n"));
577 if (!EqualSid(mapowner, procowner))
578 return 0; /* security ID mismatch! */
580 debug(("security stuff matched\r\n"));
586 debug(("security APIs not present\r\n"));
589 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
591 debug(("p is %p\r\n", p));
592 {int i; for(i=0;i<5;i++)debug(("p[%d]=%02x\r\n", i, ((unsigned char *)p)[i]));}
598 CloseHandle(filemap);
603 return DefWindowProc (hwnd, message, wParam, lParam);
606 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
613 * Determine whether we're an NT system (should have security
614 * APIs) or a non-NT system (don't do security).
616 memset(&osi, 0, sizeof(OSVERSIONINFO));
617 osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
618 if (GetVersionEx(&osi) && osi.dwPlatformId==VER_PLATFORM_WIN32_NT) {
621 has_security = FALSE;
625 * Attempt to ge the security API we need.
627 advapi = LoadLibrary("ADVAPI32.DLL");
628 getsecurityinfo = (gsi_fn_t)GetProcAddress(advapi, "GetSecurityInfo");
629 if (!getsecurityinfo) {
631 "Unable to access security APIs. Pageant will\n"
632 "not run, in case it causes a security breach.",
633 "Pageant Fatal Error", MB_ICONERROR | MB_OK);
640 * First bomb out totally if we are already running.
642 if (FindWindow("Pageant", "Pageant")) {
643 MessageBox(NULL, "Pageant is already running", "Pageant Error",
644 MB_ICONERROR | MB_OK);
645 if (advapi) FreeLibrary(advapi);
653 wndclass.lpfnWndProc = WndProc;
654 wndclass.cbClsExtra = 0;
655 wndclass.cbWndExtra = 0;
656 wndclass.hInstance = inst;
657 wndclass.hIcon = LoadIcon (inst,
658 MAKEINTRESOURCE(IDI_MAINICON));
659 wndclass.hCursor = LoadCursor (NULL, IDC_IBEAM);
660 wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
661 wndclass.lpszMenuName = NULL;
662 wndclass.lpszClassName = APPNAME;
664 RegisterClass (&wndclass);
667 hwnd = keylist = NULL;
669 hwnd = CreateWindow (APPNAME, APPNAME,
670 WS_OVERLAPPEDWINDOW | WS_VSCROLL,
671 CW_USEDEFAULT, CW_USEDEFAULT,
672 100, 100, NULL, NULL, inst, NULL);
674 /* Set up a system tray icon */
680 #ifdef NIM_SETVERSION
682 res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
685 tnid.cbSize = sizeof(NOTIFYICONDATA);
687 tnid.uID = 1; /* unique within this systray use */
688 tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
689 tnid.uCallbackMessage = WM_SYSTRAY;
690 tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
691 strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
693 res = Shell_NotifyIcon(NIM_ADD, &tnid);
698 systray_menu = CreatePopupMenu();
699 AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "&View Keys");
700 AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
703 ShowWindow (hwnd, SW_HIDE);
706 * Initialise storage for RSA keys.
708 rsakeys = newtree234(cmpkeys);
711 * Process the command line and add RSA keys as listed on it.
718 while (*p && isspace(*p)) p++;
719 if (*p && !isspace(*p)) {
720 char *q = p, *pp = p;
721 while (*p && (inquotes || !isspace(*p)))
724 inquotes = !inquotes;
742 while (GetMessage(&msg, NULL, 0, 0) == 1) {
743 TranslateMessage(&msg);
744 DispatchMessage(&msg);
747 /* Clean up the system tray icon */
751 tnid.cbSize = sizeof(NOTIFYICONDATA);
755 Shell_NotifyIcon(NIM_DELETE, &tnid);
757 DestroyMenu(systray_menu);
760 if (advapi) FreeLibrary(advapi);