]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pageant.c
Remote addition and removal of keys in Pageant
[PuTTY.git] / pageant.c
1 /*
2  * Pageant: the PuTTY Authentication Agent.
3  */
4
5 #include <windows.h>
6 #include <aclapi.h>
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)
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
25
26 #define IDM_CLOSE    0x0010
27 #define IDM_VIEWKEYS 0x0020
28
29 #define APPNAME "Pageant"
30
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
40 HINSTANCE instance;
41 HWND hwnd;
42 HWND keylist;
43 HMENU systray_menu;
44
45 tree234 *rsakeys;
46
47 int has_security;
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;
53
54 /*
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.
58  *
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.
62  */
63 int random_byte(void) {
64     MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
65     exit(0);
66 }
67
68 /*
69  * This function is needed to link with the DES code. We need not
70  * have it do anything at all.
71  */
72 void logevent(char *msg) {
73 }
74
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]))
80
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); }
86
87 #define PASSPHRASE_MAXLEN 512
88
89 /*
90  * Dialog-box function for the passphrase box.
91  */
92 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
93                                    WPARAM wParam, LPARAM lParam) {
94     static char *passphrase;
95
96     switch (msg) {
97       case WM_INITDIALOG:
98         passphrase = (char *)lParam;
99         *passphrase = 0;
100         return 0;
101       case WM_COMMAND:
102         switch (LOWORD(wParam)) {
103           case IDOK:
104             if (*passphrase)
105                 EndDialog (hwnd, 1);
106             else
107                 MessageBeep (0);
108             return 0;
109           case IDCANCEL:
110             EndDialog (hwnd, 0);
111             return 0;
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';
116             }
117             return 0;
118         }
119         return 0;
120       case WM_CLOSE:
121         EndDialog (hwnd, 0);
122         return 0;
123     }
124     return 0;
125 }
126
127 /*
128  * Update the visible key list.
129  */
130 void keylist_update(void) {
131     struct RSAKey *key;
132     enum234 e;
133
134     if (keylist) {
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);
139         }
140         SendDlgItemMessage (keylist, 100, LB_SETCURSEL, (WPARAM) -1, 0);
141     }
142 }
143
144 /*
145  * This function loads a key from a file and adds it.
146  */
147 void add_keyfile(char *filename) {
148     char passphrase[PASSPHRASE_MAXLEN];
149     struct RSAKey *key;
150     int needs_pass;
151     int ret;
152     int attempts;
153
154     /* FIXME: we can acquire comment here and use it in dialog */
155     needs_pass = rsakey_encrypted(filename, NULL);
156     attempts = 0;
157     key = malloc(sizeof(*key));
158     do {
159         if (needs_pass) {
160             int dlgret;
161             dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
162                                     NULL, PassphraseProc,
163                                     (LPARAM)passphrase);
164             if (!dlgret) {
165                 free(key);
166                 return;                /* operation cancelled */
167             }
168         } else
169             *passphrase = '\0';
170         ret = loadrsakey(filename, key, passphrase);
171         attempts++;
172     } while (ret == -1);
173     if (ret == 0) {
174         MessageBox(NULL, "Couldn't load public key.", APPNAME,
175                    MB_OK | MB_ICONERROR);
176         free(key);
177         return;
178     }
179     if (add234(rsakeys, key) != key)
180         free(key);                     /* already present, don't waste RAM */
181 }
182
183 /*
184  * This is the main agent function that answers messages.
185  */
186 void answer_msg(void *msg) {
187     unsigned char *p = msg;
188     unsigned char *ret = msg;
189     int type;
190
191     /*
192      * Get the message type.
193      */
194     type = p[4];
195
196     p += 5;
197     switch (type) {
198       case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
199         /*
200          * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
201          */
202         {
203             enum234 e;
204             struct RSAKey *key;
205             int len, nkeys;
206
207             /*
208              * Count up the number and length of keys we hold.
209              */
210             len = nkeys = 0;
211             for (key = first234(rsakeys, &e); key; key = next234(&e)) {
212                 nkeys++;
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);
217             }
218
219             /*
220              * Packet header is the obvious five bytes, plus four
221              * bytes for the key count.
222              */
223             len += 5 + 4;
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);
229             p = ret + 5 + 4;
230             for (key = first234(rsakeys, &e); key; key = next234(&e)) {
231                 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus));
232                 p += 4;
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);
238             }
239         }
240         break;
241       case SSH_AGENTC_RSA_CHALLENGE:
242         /*
243          * Reply with either SSH_AGENT_RSA_RESPONSE or
244          * SSH_AGENT_FAILURE, depending on whether we have that key
245          * or not.
246          */
247         {
248             struct RSAKey reqkey, *key;
249             Bignum challenge, response;
250             unsigned char response_source[48], response_md5[16];
251             struct MD5Context md5c;
252             int i, len;
253
254             p += 4;
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);
263                 freebn(challenge);
264                 goto failure;
265             }
266             response = rsadecrypt(challenge, key);
267             for (i = 0; i < 32; i++)
268                 response_source[i] = bignum_byte(response, 31-i);
269
270             MD5Init(&md5c);
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. */
278
279             /*
280              * Packet is the obvious five byte header, plus sixteen
281              * bytes of MD5.
282              */
283             len = 5 + 16;
284             PUT_32BIT(ret, len-4);
285             ret[4] = SSH_AGENT_RSA_RESPONSE;
286             memcpy(ret+5, response_md5, 16);
287         }
288         break;
289       case SSH_AGENTC_ADD_RSA_IDENTITY:
290         /*
291          * Add to the list and return SSH_AGENT_SUCCESS, or
292          * SSH_AGENT_FAILURE if the key was malformed.
293          */
294         {
295             struct RSAKey *key;
296             char *comment;
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));
305             if (comment) {
306                 memcpy(comment, p+4, GET_32BIT(p));
307                 key->comment = comment;
308             }
309             PUT_32BIT(ret, 1);
310             ret[4] = SSH_AGENT_FAILURE;
311             if (add234(rsakeys, key) == key) {
312                 keylist_update();
313                 ret[4] = SSH_AGENT_SUCCESS;
314             } else {
315                 freersakey(key);
316             }
317         }
318         break;
319       case SSH_AGENTC_REMOVE_RSA_IDENTITY:
320         /*
321          * Remove from the list and return SSH_AGENT_SUCCESS, or
322          * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
323          * start with.
324          */
325         {
326             struct RSAKey reqkey, *key;
327
328             p += makekey(p, &reqkey, NULL, 0);
329             key = find234(rsakeys, &reqkey, NULL);
330             freebn(reqkey.exponent);
331             freebn(reqkey.modulus);
332             PUT_32BIT(ret, 1);
333             ret[4] = SSH_AGENT_FAILURE;
334             if (key) {
335                 del234(rsakeys, key);
336                 keylist_update();
337                 ret[4] = SSH_AGENT_SUCCESS;
338             }
339         }
340         break;
341       default:
342         failure:
343         /*
344          * Unrecognised message. Return SSH_AGENT_FAILURE.
345          */
346         PUT_32BIT(ret, 1);
347         ret[4] = SSH_AGENT_FAILURE;
348         break;
349     }
350 }
351
352 /*
353  * Key comparison function for the 2-3-4 tree of RSA keys.
354  */
355 int cmpkeys(void *av, void *bv) {
356     struct RSAKey *a = (struct RSAKey *)av;
357     struct RSAKey *b = (struct RSAKey *)bv;
358     Bignum am, bm;
359     int alen, blen;
360
361     am = a->modulus;
362     bm = b->modulus;
363     /*
364      * Compare by length of moduli.
365      */
366     alen = ssh1_bignum_bitcount(am);
367     blen = ssh1_bignum_bitcount(bm);
368     if (alen > blen) return +1; else if (alen < blen) return -1;
369     /*
370      * Now compare by moduli themselves.
371      */
372     alen = (alen + 7) / 8;             /* byte count */
373     while (alen-- > 0) {
374         int abyte, bbyte;
375         abyte = bignum_byte(am, alen);
376         bbyte = bignum_byte(bm, alen);
377         if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
378     }
379     /*
380      * Give up.
381      */
382     return 0;
383 }
384
385 static void error(char *s) {
386     MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
387 }
388
389 /*
390  * Dialog-box function for the key list box.
391  */
392 static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
393                                 WPARAM wParam, LPARAM lParam) {
394     enum234 e;
395     struct RSAKey *key;
396     OPENFILENAME of;
397     char filename[FILENAME_MAX];
398
399     switch (msg) {
400       case WM_INITDIALOG:
401         for (key = first234(rsakeys, &e); key; key = next234(&e)) {
402             SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
403                                 0, (LPARAM) key->comment);
404         }
405         return 0;
406       case WM_COMMAND:
407         switch (LOWORD(wParam)) {
408           case IDOK:
409           case IDCANCEL:
410             keylist = NULL;
411             DestroyWindow(hwnd);
412             return 0;
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;
419 #else
420                 of.lStructSize = sizeof(of);
421 #endif
422                 of.hwndOwner = hwnd;
423                 of.lpstrFilter = "All Files\0*\0\0\0";
424                 of.lpstrCustomFilter = NULL;
425                 of.nFilterIndex = 1;
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";
431                 of.Flags = 0;
432                 if (GetOpenFileName(&of)) {
433                     add_keyfile(filename);
434                     keylist_update();
435                 }
436             }
437             return 0;
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) {
443                     MessageBeep(0);
444                     break;
445                 }
446                 for (key = first234(rsakeys, &e); key; key = next234(&e))
447                     if (n-- == 0)
448                         break;
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);
455                 }
456                 SendDlgItemMessage (hwnd, 100, LB_SETCURSEL, (WPARAM) -1, 0);
457             }
458             return 0;
459         }
460         return 0;
461       case WM_CLOSE:
462         keylist = NULL;
463         DestroyWindow(hwnd);
464         return 0;
465     }
466     return 0;
467 }
468
469 static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
470                                  WPARAM wParam, LPARAM lParam) {
471     int ret;
472     static int menuinprogress;
473
474     switch (message) {
475       case WM_SYSTRAY:
476         if (lParam == WM_RBUTTONUP) {
477             POINT cursorpos;
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);
483         }
484         break;
485       case WM_SYSTRAY2:
486         if (!menuinprogress) {
487             menuinprogress = 1;
488             SetForegroundWindow(hwnd);
489             ret = TrackPopupMenu(systray_menu,
490                                  TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
491                                  TPM_RIGHTBUTTON,
492                                  wParam, lParam, 0, hwnd, NULL);
493             menuinprogress = 0;
494         }
495         break;
496       case WM_COMMAND:
497       case WM_SYSCOMMAND:
498         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
499           case IDM_CLOSE:
500             SendMessage(hwnd, WM_CLOSE, 0, 0);
501             break;
502           case IDM_VIEWKEYS:
503             if (!keylist) {
504                 keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
505                                         NULL, KeyListProc);
506                 ShowWindow (keylist, SW_SHOWNORMAL);
507                 /* 
508                  * Sometimes the window comes up minimised / hidden
509                  * for no obvious reason. Prevent this.
510                  */
511                 SetForegroundWindow(keylist);
512                 SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
513                               SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
514             }
515             break;
516         }
517         break;
518       case WM_DESTROY:
519         PostQuitMessage (0);
520         return 0;
521       case WM_COPYDATA:
522         {
523             COPYDATASTRUCT *cds;
524             char *mapname;
525             void *p;
526             HANDLE filemap, proc;
527             PSID mapowner, procowner;
528             PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
529             int ret = 0;
530
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! */
537 #ifdef DEBUG_IPC
538             debug(("mapname is :%s:\r\n", mapname));
539 #endif
540             filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
541 #ifdef DEBUG_IPC
542             debug(("filemap is %p\r\n", filemap));
543 #endif
544             if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
545                 int rc;
546                 if (has_security) {
547                     if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
548                                             GetCurrentProcessId())) == NULL) {
549 #ifdef DEBUG_IPC
550                         debug(("couldn't get handle for process\r\n"));
551 #endif
552                         return 0;
553                     }
554                     if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
555                                         OWNER_SECURITY_INFORMATION,
556                                         &procowner, NULL, NULL, NULL,
557                                         &psd2) != ERROR_SUCCESS) {
558 #ifdef DEBUG_IPC
559                         debug(("couldn't get owner info for process\r\n"));
560 #endif
561                         CloseHandle(proc);
562                         return 0;          /* unable to get security info */
563                     }
564                     CloseHandle(proc);
565                     if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
566                                               OWNER_SECURITY_INFORMATION,
567                                               &mapowner, NULL, NULL, NULL,
568                                               &psd1) != ERROR_SUCCESS)) {
569 #ifdef DEBUG_IPC
570                         debug(("couldn't get owner info for filemap: %d\r\n", rc));
571 #endif
572                         return 0;
573                     }
574 #ifdef DEBUG_IPC
575                     debug(("got security stuff\r\n"));
576 #endif
577                     if (!EqualSid(mapowner, procowner))
578                         return 0;          /* security ID mismatch! */
579 #ifdef DEBUG_IPC
580                     debug(("security stuff matched\r\n"));
581 #endif
582                     LocalFree(psd1);
583                     LocalFree(psd2);
584                 } else {
585 #ifdef DEBUG_IPC
586                     debug(("security APIs not present\r\n"));
587 #endif
588                 }
589                 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
590 #ifdef DEBUG_IPC
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]));}
593 #endif
594                 answer_msg(p);
595                 ret = 1;
596                 UnmapViewOfFile(p);
597             }
598             CloseHandle(filemap);
599             return ret;
600         }
601     }
602
603     return DefWindowProc (hwnd, message, wParam, lParam);
604 }
605
606 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
607     WNDCLASS wndclass;
608     MSG msg;
609     OSVERSIONINFO osi;
610     HMODULE advapi;
611
612     /*
613      * Determine whether we're an NT system (should have security
614      * APIs) or a non-NT system (don't do security).
615      */
616     memset(&osi, 0, sizeof(OSVERSIONINFO));
617     osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
618     if (GetVersionEx(&osi) && osi.dwPlatformId==VER_PLATFORM_WIN32_NT) {
619         has_security = TRUE;
620     } else
621         has_security = FALSE;
622
623     if (has_security) {
624         /*
625          * Attempt to ge the security API we need.
626          */
627         advapi = LoadLibrary("ADVAPI32.DLL");
628         getsecurityinfo = (gsi_fn_t)GetProcAddress(advapi, "GetSecurityInfo");
629         if (!getsecurityinfo) {
630             MessageBox(NULL,
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);
634             return 1;
635         }
636     } else
637         advapi = NULL;
638
639     /*
640      * First bomb out totally if we are already running.
641      */
642     if (FindWindow("Pageant", "Pageant")) {
643         MessageBox(NULL, "Pageant is already running", "Pageant Error",
644                    MB_ICONERROR | MB_OK);
645         if (advapi) FreeLibrary(advapi);
646         return 0;
647     }
648
649     instance = inst;
650
651     if (!prev) {
652         wndclass.style         = 0;
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;
663
664         RegisterClass (&wndclass);
665     }
666
667     hwnd = keylist = NULL;
668
669     hwnd = CreateWindow (APPNAME, APPNAME,
670                          WS_OVERLAPPEDWINDOW | WS_VSCROLL,
671                          CW_USEDEFAULT, CW_USEDEFAULT,
672                          100, 100, NULL, NULL, inst, NULL);
673
674     /* Set up a system tray icon */
675     {
676         BOOL res;
677         NOTIFYICONDATA tnid;
678         HICON hicon;
679
680 #ifdef NIM_SETVERSION
681         tnid.uVersion = 0;
682         res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
683 #endif
684
685         tnid.cbSize = sizeof(NOTIFYICONDATA); 
686         tnid.hWnd = hwnd; 
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)");
692
693         res = Shell_NotifyIcon(NIM_ADD, &tnid); 
694
695         if (hicon) 
696             DestroyIcon(hicon); 
697
698         systray_menu = CreatePopupMenu();
699         AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "&View Keys");
700         AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
701     }
702
703     ShowWindow (hwnd, SW_HIDE);
704
705     /*
706      * Initialise storage for RSA keys.
707      */
708     rsakeys = newtree234(cmpkeys);
709
710     /*
711      * Process the command line and add RSA keys as listed on it.
712      */
713     {
714         char *p;
715         int inquotes = 0;
716         p = cmdline;
717         while (*p) {
718             while (*p && isspace(*p)) p++;
719             if (*p && !isspace(*p)) {
720                 char *q = p, *pp = p;
721                 while (*p && (inquotes || !isspace(*p)))
722                 {
723                     if (*p == '"') {
724                         inquotes = !inquotes;
725                         p++;
726                         continue;
727                     }
728                     *pp++ = *p++;
729                 }
730                 if (*pp) {
731                     if (*p) p++;
732                     *pp++ = '\0';
733                 }
734                 add_keyfile(q);
735             }
736         }
737     }
738
739     /*
740      * Main message loop.
741      */
742     while (GetMessage(&msg, NULL, 0, 0) == 1) {
743         TranslateMessage(&msg);
744         DispatchMessage(&msg);
745     }
746
747     /* Clean up the system tray icon */
748     {
749         NOTIFYICONDATA tnid;
750
751         tnid.cbSize = sizeof(NOTIFYICONDATA); 
752         tnid.hWnd = hwnd;
753         tnid.uID = 1;
754
755         Shell_NotifyIcon(NIM_DELETE, &tnid); 
756
757         DestroyMenu(systray_menu);
758     }
759
760     if (advapi) FreeLibrary(advapi);
761     exit(msg.wParam);
762 }