Oops - puttytel now needs a stub random_destroy_seed() to compile
[u/mdw/putty] / pageant.c
CommitLineData
5c58ad2d 1/*
2 * Pageant: the PuTTY Authentication Agent.
3 */
4
5#include <windows.h>
d70f60ae 6#include <aclapi.h>
5c58ad2d 7#include <stdio.h> /* FIXME */
8#include "putty.h" /* FIXME */
9#include "ssh.h"
10#include "tree234.h"
11
12#define IDI_MAINICON 200
13#define IDI_TRAYICON 201
14
15#define WM_XUSER (WM_USER + 0x2000)
16#define WM_SYSTRAY (WM_XUSER + 6)
17#define WM_SYSTRAY2 (WM_XUSER + 7)
d70f60ae 18
19#define AGENT_COPYDATA_ID 0x804e50ba /* random goop */
20
21/*
22 * FIXME: maybe some day we can sort this out ...
23 */
24#define AGENT_MAX_MSGLEN 8192
5c58ad2d 25
26#define IDM_CLOSE 0x0010
27#define IDM_VIEWKEYS 0x0020
28
29#define APPNAME "Pageant"
30
5c58ad2d 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
39
40HINSTANCE instance;
41HWND hwnd;
42HWND keylist;
43HMENU systray_menu;
44
45tree234 *rsakeys;
46
47/*
48 * We need this to link with the RSA code, because rsaencrypt()
49 * pads its data with random bytes. Since we only use rsadecrypt(),
50 * which is deterministic, this should never be called.
51 *
52 * If it _is_ called, there is a _serious_ problem, because it
53 * won't generate true random numbers. So we must scream, panic,
54 * and exit immediately if that should happen.
55 */
56int random_byte(void) {
57 MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
58 exit(0);
59}
60
61/*
62 * This function is needed to link with the DES code. We need not
63 * have it do anything at all.
64 */
65void logevent(char *msg) {
66}
67
68#define GET_32BIT(cp) \
69 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
70 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
71 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
72 ((unsigned long)(unsigned char)(cp)[3]))
73
74#define PUT_32BIT(cp, value) { \
75 (cp)[0] = (unsigned char)((value) >> 24); \
76 (cp)[1] = (unsigned char)((value) >> 16); \
77 (cp)[2] = (unsigned char)((value) >> 8); \
78 (cp)[3] = (unsigned char)(value); }
79
80#define PASSPHRASE_MAXLEN 512
81
82/*
83 * Dialog-box function for the passphrase box.
84 */
85static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
86 WPARAM wParam, LPARAM lParam) {
87 static char *passphrase;
88
89 switch (msg) {
90 case WM_INITDIALOG:
91 passphrase = (char *)lParam;
92 *passphrase = 0;
93 return 0;
94 case WM_COMMAND:
95 switch (LOWORD(wParam)) {
96 case IDOK:
97 if (*passphrase)
98 EndDialog (hwnd, 1);
99 else
100 MessageBeep (0);
101 return 0;
102 case IDCANCEL:
103 EndDialog (hwnd, 0);
104 return 0;
105 case 102: /* edit box */
106 if (HIWORD(wParam) == EN_CHANGE) {
107 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
108 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
109 }
110 return 0;
111 }
112 return 0;
113 case WM_CLOSE:
114 EndDialog (hwnd, 0);
115 return 0;
116 }
117 return 0;
118}
119
120/*
121 * This function loads a key from a file and adds it.
122 */
123void add_keyfile(char *filename) {
124 char passphrase[PASSPHRASE_MAXLEN];
125 struct RSAKey *key;
126 int needs_pass;
127 int ret;
128 int attempts;
129
a52f067e 130 /* FIXME: we can acquire comment here and use it in dialog */
131 needs_pass = rsakey_encrypted(filename, NULL);
5c58ad2d 132 attempts = 0;
133 key = malloc(sizeof(*key));
134 do {
135 if (needs_pass) {
136 int dlgret;
137 dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
138 NULL, PassphraseProc,
139 (LPARAM)passphrase);
140 if (!dlgret) {
141 free(key);
142 return; /* operation cancelled */
143 }
144 } else
145 *passphrase = '\0';
146 ret = loadrsakey(filename, key, passphrase);
147 attempts++;
148 } while (ret == -1);
149 if (ret == 0) {
150 MessageBox(NULL, "Couldn't load public key.", APPNAME,
151 MB_OK | MB_ICONERROR);
152 free(key);
153 return;
154 }
155 if (add234(rsakeys, key) != key)
156 free(key); /* already present, don't waste RAM */
157}
158
159/*
160 * This is the main agent function that answers messages.
161 */
d70f60ae 162void answer_msg(void *msg) {
163 unsigned char *p = msg;
164 unsigned char *ret = msg;
5c58ad2d 165 int type;
166
5c58ad2d 167 /*
168 * Get the message type.
169 */
170 type = p[4];
171
172 p += 5;
5c58ad2d 173 switch (type) {
174 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
175 /*
176 * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
177 */
178 {
179 enum234 e;
180 struct RSAKey *key;
181 int len, nkeys;
182
183 /*
184 * Count up the number and length of keys we hold.
185 */
186 len = nkeys = 0;
187 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
188 nkeys++;
189 len += 4; /* length field */
190 len += ssh1_bignum_length(key->exponent);
191 len += ssh1_bignum_length(key->modulus);
192 len += 4 + strlen(key->comment);
193 }
194
195 /*
196 * Packet header is the obvious five bytes, plus four
197 * bytes for the key count.
198 */
199 len += 5 + 4;
d70f60ae 200 if (len > AGENT_MAX_MSGLEN)
201 goto failure; /* aaargh! too much stuff! */
202 PUT_32BIT(ret, len-4);
203 ret[4] = SSH_AGENT_RSA_IDENTITIES_ANSWER;
204 PUT_32BIT(ret+5, nkeys);
205 p = ret + 5 + 4;
206 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
207 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus));
208 p += 4;
209 p += ssh1_write_bignum(p, key->exponent);
210 p += ssh1_write_bignum(p, key->modulus);
211 PUT_32BIT(p, strlen(key->comment));
212 memcpy(p+4, key->comment, strlen(key->comment));
213 p += 4 + strlen(key->comment);
5c58ad2d 214 }
215 }
216 break;
217 case SSH_AGENTC_RSA_CHALLENGE:
218 /*
219 * Reply with either SSH_AGENT_RSA_RESPONSE or
220 * SSH_AGENT_FAILURE, depending on whether we have that key
221 * or not.
222 */
223 {
224 struct RSAKey reqkey, *key;
225 Bignum challenge, response;
226 unsigned char response_source[48], response_md5[16];
227 struct MD5Context md5c;
228 int i, len;
229
230 p += 4;
231 p += ssh1_read_bignum(p, &reqkey.exponent);
232 p += ssh1_read_bignum(p, &reqkey.modulus);
233 p += ssh1_read_bignum(p, &challenge);
234 memcpy(response_source+32, p, 16); p += 16;
235 if (GET_32BIT(p) != 1 ||
236 (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
237 freebn(reqkey.exponent);
238 freebn(reqkey.modulus);
239 freebn(challenge);
240 goto failure;
241 }
242 response = rsadecrypt(challenge, key);
243 for (i = 0; i < 32; i++)
244 response_source[i] = bignum_byte(response, 31-i);
245
246 MD5Init(&md5c);
247 MD5Update(&md5c, response_source, 48);
248 MD5Final(response_md5, &md5c);
249 memset(response_source, 0, 48); /* burn the evidence */
250 freebn(response); /* and that evidence */
251 freebn(challenge); /* yes, and that evidence */
252 freebn(reqkey.exponent); /* and free some memory ... */
253 freebn(reqkey.modulus); /* ... while we're at it. */
254
255 /*
256 * Packet is the obvious five byte header, plus sixteen
257 * bytes of MD5.
258 */
259 len = 5 + 16;
d70f60ae 260 PUT_32BIT(ret, len-4);
261 ret[4] = SSH_AGENT_RSA_RESPONSE;
262 memcpy(ret+5, response_md5, 16);
5c58ad2d 263 }
264 break;
265#if 0 /* FIXME: implement these */
266 case SSH_AGENTC_ADD_RSA_IDENTITY:
267 /*
268 * Add to the list and return SSH_AGENT_SUCCESS, or
269 * SSH_AGENT_FAILURE if the key was malformed.
270 */
271 break;
272 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
273 /*
274 * Remove from the list and return SSH_AGENT_SUCCESS, or
275 * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
276 * start with.
277 */
278 break;
279#endif
280 default:
281 failure:
282 /*
283 * Unrecognised message. Return SSH_AGENT_FAILURE.
284 */
d70f60ae 285 PUT_32BIT(ret, 1);
286 ret[4] = SSH_AGENT_FAILURE;
5c58ad2d 287 break;
288 }
5c58ad2d 289}
290
291/*
292 * Key comparison function for the 2-3-4 tree of RSA keys.
293 */
294int cmpkeys(void *av, void *bv) {
295 struct RSAKey *a = (struct RSAKey *)av;
296 struct RSAKey *b = (struct RSAKey *)bv;
297 Bignum am, bm;
298 int alen, blen;
299
300 am = a->modulus;
301 bm = b->modulus;
302 /*
303 * Compare by length of moduli.
304 */
305 alen = ssh1_bignum_bitcount(am);
306 blen = ssh1_bignum_bitcount(bm);
307 if (alen > blen) return +1; else if (alen < blen) return -1;
308 /*
309 * Now compare by moduli themselves.
310 */
311 alen = (alen + 7) / 8; /* byte count */
312 while (alen-- > 0) {
313 int abyte, bbyte;
314 abyte = bignum_byte(am, alen);
315 bbyte = bignum_byte(bm, alen);
316 if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
317 }
318 /*
319 * Give up.
320 */
321 return 0;
322}
323
324static void error(char *s) {
325 MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
326}
327
328/*
329 * Dialog-box function for the key list box.
330 */
331static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
332 WPARAM wParam, LPARAM lParam) {
333 enum234 e;
334 struct RSAKey *key;
335 OPENFILENAME of;
336 char filename[FILENAME_MAX];
337
338 switch (msg) {
339 case WM_INITDIALOG:
340 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
341 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
342 0, (LPARAM) key->comment);
343 }
344 return 0;
345 case WM_COMMAND:
346 switch (LOWORD(wParam)) {
347 case IDOK:
348 case IDCANCEL:
349 keylist = NULL;
350 DestroyWindow(hwnd);
351 return 0;
352 case 101: /* add key */
353 if (HIWORD(wParam) == BN_CLICKED ||
354 HIWORD(wParam) == BN_DOUBLECLICKED) {
355 memset(&of, 0, sizeof(of));
356#ifdef OPENFILENAME_SIZE_VERSION_400
357 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
358#else
359 of.lStructSize = sizeof(of);
360#endif
361 of.hwndOwner = hwnd;
362 of.lpstrFilter = "All Files\0*\0\0\0";
363 of.lpstrCustomFilter = NULL;
364 of.nFilterIndex = 1;
365 of.lpstrFile = filename; *filename = '\0';
366 of.nMaxFile = sizeof(filename);
367 of.lpstrFileTitle = NULL;
368 of.lpstrInitialDir = NULL;
369 of.lpstrTitle = "Select Public Key File";
370 of.Flags = 0;
371 if (GetOpenFileName(&of)) {
372 add_keyfile(filename);
373 }
374 SendDlgItemMessage(hwnd, 100, LB_RESETCONTENT, 0, 0);
375 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
376 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
377 0, (LPARAM) key->comment);
378 }
379 SendDlgItemMessage (hwnd, 100, LB_SETCURSEL, (WPARAM) -1, 0);
380 }
381 return 0;
382 case 102: /* remove key */
383 if (HIWORD(wParam) == BN_CLICKED ||
384 HIWORD(wParam) == BN_DOUBLECLICKED) {
385 int n = SendDlgItemMessage (hwnd, 100, LB_GETCURSEL, 0, 0);
386 if (n == LB_ERR || n == 0) {
387 MessageBeep(0);
388 break;
389 }
390 for (key = first234(rsakeys, &e); key; key = next234(&e))
391 if (n-- == 0)
392 break;
393 del234(rsakeys, key);
394 freersakey(key); free(key);
395 SendDlgItemMessage(hwnd, 100, LB_RESETCONTENT, 0, 0);
396 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
397 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
398 0, (LPARAM) key->comment);
399 }
400 SendDlgItemMessage (hwnd, 100, LB_SETCURSEL, (WPARAM) -1, 0);
401 }
402 return 0;
403 }
404 return 0;
405 case WM_CLOSE:
406 keylist = NULL;
407 DestroyWindow(hwnd);
408 return 0;
409 }
410 return 0;
411}
412
413static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
414 WPARAM wParam, LPARAM lParam) {
415 int ret;
416 static int menuinprogress;
417
418 switch (message) {
419 case WM_SYSTRAY:
420 if (lParam == WM_RBUTTONUP) {
421 POINT cursorpos;
422 GetCursorPos(&cursorpos);
423 PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
905beba5 424 } else if (lParam == WM_LBUTTONDBLCLK) {
425 /* Equivalent to IDM_VIEWKEYS. */
426 PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
5c58ad2d 427 }
428 break;
429 case WM_SYSTRAY2:
430 if (!menuinprogress) {
431 menuinprogress = 1;
432 SetForegroundWindow(hwnd);
433 ret = TrackPopupMenu(systray_menu,
434 TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
435 TPM_RIGHTBUTTON,
436 wParam, lParam, 0, hwnd, NULL);
437 menuinprogress = 0;
438 }
439 break;
440 case WM_COMMAND:
441 case WM_SYSCOMMAND:
442 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
443 case IDM_CLOSE:
444 SendMessage(hwnd, WM_CLOSE, 0, 0);
445 break;
446 case IDM_VIEWKEYS:
447 if (!keylist) {
448 keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
449 NULL, KeyListProc);
450 ShowWindow (keylist, SW_SHOWNORMAL);
905beba5 451 /*
452 * Sometimes the window comes up minimised / hidden
453 * for no obvious reason. Prevent this.
454 */
455 SetForegroundWindow(keylist);
456 SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
457 SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
5c58ad2d 458 }
459 break;
460 }
461 break;
462 case WM_DESTROY:
463 PostQuitMessage (0);
464 return 0;
465 case WM_COPYDATA:
466 {
467 COPYDATASTRUCT *cds;
d70f60ae 468 char *mapname;
469 void *p;
470 HANDLE filemap, proc;
471 PSID mapowner, procowner;
472 PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
473 int ret = 0;
5c58ad2d 474
475 cds = (COPYDATASTRUCT *)lParam;
d70f60ae 476 if (cds->dwData != AGENT_COPYDATA_ID)
477 return 0; /* not our message, mate */
478 mapname = (char *)cds->lpData;
479 if (mapname[cds->cbData - 1] != '\0')
480 return 0; /* failure to be ASCIZ! */
481#ifdef DEBUG_IPC
482 debug(("mapname is :%s:\r\n", mapname));
483#endif
484 filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
485#ifdef DEBUG_IPC
486 debug(("filemap is %p\r\n", filemap));
487#endif
488 if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
489 int rc;
490 if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
491 GetCurrentProcessId())) == NULL) {
492#ifdef DEBUG_IPC
493 debug(("couldn't get handle for process\r\n"));
494#endif
495 return 0;
496 }
497 if (GetSecurityInfo(proc, SE_KERNEL_OBJECT,
498 OWNER_SECURITY_INFORMATION,
499 &procowner, NULL, NULL, NULL,
500 &psd2) != ERROR_SUCCESS) {
501#ifdef DEBUG_IPC
502 debug(("couldn't get owner info for process\r\n"));
503#endif
504 CloseHandle(proc);
505 return 0; /* unable to get security info */
506 }
507 CloseHandle(proc);
508 if ((rc = GetSecurityInfo(filemap, SE_KERNEL_OBJECT,
509 OWNER_SECURITY_INFORMATION,
510 &mapowner, NULL, NULL, NULL,
511 &psd1) != ERROR_SUCCESS)) {
512#ifdef DEBUG_IPC
513 debug(("couldn't get owner info for filemap: %d\r\n", rc));
514#endif
515 return 0;
5c58ad2d 516 }
d70f60ae 517#ifdef DEBUG_IPC
518 debug(("got security stuff\r\n"));
519#endif
520 if (!EqualSid(mapowner, procowner))
521 return 0; /* security ID mismatch! */
522#ifdef DEBUG_IPC
523 debug(("security stuff matched\r\n"));
524#endif
525 LocalFree(psd1);
526 LocalFree(psd2);
527 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
528#ifdef DEBUG_IPC
529 debug(("p is %p\r\n", p));
530 {int i; for(i=0;i<5;i++)debug(("p[%d]=%02x\r\n", i, ((unsigned char *)p)[i]));}
531#endif
532 answer_msg(p);
533 ret = 1;
534 UnmapViewOfFile(p);
535 }
536 CloseHandle(filemap);
537 return ret;
5c58ad2d 538 }
5c58ad2d 539 }
540
541 return DefWindowProc (hwnd, message, wParam, lParam);
542}
543
544int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
545 WNDCLASS wndclass;
5c58ad2d 546 MSG msg;
547
2faac2e1 548 /*
549 * First bomb out totally if we are already running.
550 */
551 if (FindWindow("Pageant", "Pageant")) {
552 MessageBox(NULL, "Pageant is already running", "Pageant Error",
553 MB_ICONERROR | MB_OK);
554 return 0;
555 }
556
5c58ad2d 557 instance = inst;
558
559 if (!prev) {
560 wndclass.style = 0;
561 wndclass.lpfnWndProc = WndProc;
562 wndclass.cbClsExtra = 0;
563 wndclass.cbWndExtra = 0;
564 wndclass.hInstance = inst;
565 wndclass.hIcon = LoadIcon (inst,
566 MAKEINTRESOURCE(IDI_MAINICON));
567 wndclass.hCursor = LoadCursor (NULL, IDC_IBEAM);
568 wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
569 wndclass.lpszMenuName = NULL;
570 wndclass.lpszClassName = APPNAME;
571
572 RegisterClass (&wndclass);
573 }
574
575 hwnd = keylist = NULL;
576
577 hwnd = CreateWindow (APPNAME, APPNAME,
578 WS_OVERLAPPEDWINDOW | WS_VSCROLL,
579 CW_USEDEFAULT, CW_USEDEFAULT,
580 100, 100, NULL, NULL, inst, NULL);
581
582 /* Set up a system tray icon */
583 {
584 BOOL res;
585 NOTIFYICONDATA tnid;
586 HICON hicon;
587
588#ifdef NIM_SETVERSION
589 tnid.uVersion = 0;
590 res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
591#endif
592
593 tnid.cbSize = sizeof(NOTIFYICONDATA);
594 tnid.hWnd = hwnd;
595 tnid.uID = 1; /* unique within this systray use */
596 tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
597 tnid.uCallbackMessage = WM_SYSTRAY;
598 tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
599 strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
600
601 res = Shell_NotifyIcon(NIM_ADD, &tnid);
602
603 if (hicon)
604 DestroyIcon(hicon);
605
606 systray_menu = CreatePopupMenu();
607 AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "View Keys");
608 AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "Terminate");
609 }
610
611 ShowWindow (hwnd, SW_HIDE);
612
613 /*
dacbd0e8 614 * Initialise storage for RSA keys.
615 */
616 rsakeys = newtree234(cmpkeys);
617
618 /*
619 * Process the command line and add RSA keys as listed on it.
5c58ad2d 620 */
621 {
8c42f28c 622 char *p;
623 int inquotes = 0;
624 p = cmdline;
dacbd0e8 625 while (*p) {
626 while (*p && isspace(*p)) p++;
627 if (*p && !isspace(*p)) {
8c42f28c 628 char *q = p, *pp = p;
629 while (*p && (inquotes || !isspace(*p)))
630 {
631 if (*p == '"') {
632 inquotes = !inquotes;
633 p++;
634 continue;
635 }
636 *pp++ = *p++;
637 }
638 if (*pp) {
639 if (*p) p++;
640 *pp++ = '\0';
641 }
dacbd0e8 642 add_keyfile(q);
643 }
644 }
5c58ad2d 645 }
646
647 /*
dacbd0e8 648 * Main message loop.
5c58ad2d 649 */
5c58ad2d 650 while (GetMessage(&msg, NULL, 0, 0) == 1) {
651 TranslateMessage(&msg);
652 DispatchMessage(&msg);
653 }
654
655 /* Clean up the system tray icon */
656 {
657 NOTIFYICONDATA tnid;
658
659 tnid.cbSize = sizeof(NOTIFYICONDATA);
660 tnid.hWnd = hwnd;
661 tnid.uID = 1;
662
663 Shell_NotifyIcon(NIM_DELETE, &tnid);
664
665 DestroyMenu(systray_menu);
666 }
667
668 exit(msg.wParam);
669}