]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pageant.c
a9af585c29f8ed4739f12d34fb364a28e544f48a
[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 struct PassphraseProcStruct {
90     char *passphrase;
91     char *comment;
92 };
93
94 /*
95  * Dialog-box function for the passphrase box.
96  */
97 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
98                                    WPARAM wParam, LPARAM lParam) {
99     static char *passphrase;
100     struct PassphraseProcStruct *p;
101
102     switch (msg) {
103       case WM_INITDIALOG:
104         p = (struct PassphraseProcStruct *)lParam;
105         passphrase = p->passphrase;
106         if (p->comment)
107             SetDlgItemText(hwnd, 101, p->comment);
108         *passphrase = 0;
109         return 0;
110       case WM_COMMAND:
111         switch (LOWORD(wParam)) {
112           case IDOK:
113             if (*passphrase)
114                 EndDialog (hwnd, 1);
115             else
116                 MessageBeep (0);
117             return 0;
118           case IDCANCEL:
119             EndDialog (hwnd, 0);
120             return 0;
121           case 102:                    /* edit box */
122             if (HIWORD(wParam) == EN_CHANGE) {
123                 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
124                 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
125             }
126             return 0;
127         }
128         return 0;
129       case WM_CLOSE:
130         EndDialog (hwnd, 0);
131         return 0;
132     }
133     return 0;
134 }
135
136 /*
137  * Update the visible key list.
138  */
139 void keylist_update(void) {
140     struct RSAKey *key;
141     enum234 e;
142
143     if (keylist) {
144         SendDlgItemMessage(keylist, 100, LB_RESETCONTENT, 0, 0);
145         for (key = first234(rsakeys, &e); key; key = next234(&e)) {
146             char listentry[512], *p;
147             /*
148              * Replace two spaces in the fingerprint with tabs, for
149              * nice alignment in the box.
150              */
151             rsa_fingerprint(listentry, sizeof(listentry), key);
152             p = strchr(listentry, ' '); if (p) *p = '\t';
153             p = strchr(listentry, ' '); if (p) *p = '\t';
154             SendDlgItemMessage (keylist, 100, LB_ADDSTRING,
155                                 0, (LPARAM)listentry);
156         }
157         SendDlgItemMessage (keylist, 100, LB_SETCURSEL, (WPARAM) -1, 0);
158     }
159 }
160
161 /*
162  * This function loads a key from a file and adds it.
163  */
164 void add_keyfile(char *filename) {
165     char passphrase[PASSPHRASE_MAXLEN];
166     struct RSAKey *key;
167     int needs_pass;
168     int ret;
169     int attempts;
170     char *comment;
171     struct PassphraseProcStruct pps;
172
173     needs_pass = rsakey_encrypted(filename, &comment);
174     attempts = 0;
175     key = malloc(sizeof(*key));
176     pps.passphrase = passphrase;
177     pps.comment = comment;
178     do {
179         if (needs_pass) {
180             int dlgret;
181             dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
182                                     NULL, PassphraseProc,
183                                     (LPARAM)&pps);
184             if (!dlgret) {
185                 if (comment) free(comment);
186                 free(key);
187                 return;                /* operation cancelled */
188             }
189         } else
190             *passphrase = '\0';
191         ret = loadrsakey(filename, key, passphrase);
192         attempts++;
193     } while (ret == -1);
194     if (comment) free(comment);
195     if (ret == 0) {
196         MessageBox(NULL, "Couldn't load public key.", APPNAME,
197                    MB_OK | MB_ICONERROR);
198         free(key);
199         return;
200     }
201     if (add234(rsakeys, key) != key)
202         free(key);                     /* already present, don't waste RAM */
203 }
204
205 /*
206  * This is the main agent function that answers messages.
207  */
208 void answer_msg(void *msg) {
209     unsigned char *p = msg;
210     unsigned char *ret = msg;
211     int type;
212
213     /*
214      * Get the message type.
215      */
216     type = p[4];
217
218     p += 5;
219     switch (type) {
220       case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
221         /*
222          * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
223          */
224         {
225             enum234 e;
226             struct RSAKey *key;
227             int len, nkeys;
228
229             /*
230              * Count up the number and length of keys we hold.
231              */
232             len = nkeys = 0;
233             for (key = first234(rsakeys, &e); key; key = next234(&e)) {
234                 nkeys++;
235                 len += 4;              /* length field */
236                 len += ssh1_bignum_length(key->exponent);
237                 len += ssh1_bignum_length(key->modulus);
238                 len += 4 + strlen(key->comment);
239             }
240
241             /*
242              * Packet header is the obvious five bytes, plus four
243              * bytes for the key count.
244              */
245             len += 5 + 4;
246             if (len > AGENT_MAX_MSGLEN)
247                 goto failure;          /* aaargh! too much stuff! */
248             PUT_32BIT(ret, len-4);
249             ret[4] = SSH_AGENT_RSA_IDENTITIES_ANSWER;
250             PUT_32BIT(ret+5, nkeys);
251             p = ret + 5 + 4;
252             for (key = first234(rsakeys, &e); key; key = next234(&e)) {
253                 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus));
254                 p += 4;
255                 p += ssh1_write_bignum(p, key->exponent);
256                 p += ssh1_write_bignum(p, key->modulus);
257                 PUT_32BIT(p, strlen(key->comment));
258                 memcpy(p+4, key->comment, strlen(key->comment));
259                 p += 4 + strlen(key->comment);
260             }
261         }
262         break;
263       case SSH_AGENTC_RSA_CHALLENGE:
264         /*
265          * Reply with either SSH_AGENT_RSA_RESPONSE or
266          * SSH_AGENT_FAILURE, depending on whether we have that key
267          * or not.
268          */
269         {
270             struct RSAKey reqkey, *key;
271             Bignum challenge, response;
272             unsigned char response_source[48], response_md5[16];
273             struct MD5Context md5c;
274             int i, len;
275
276             p += 4;
277             p += ssh1_read_bignum(p, &reqkey.exponent);
278             p += ssh1_read_bignum(p, &reqkey.modulus);
279             p += ssh1_read_bignum(p, &challenge);
280             memcpy(response_source+32, p, 16); p += 16;
281             if (GET_32BIT(p) != 1 ||
282                 (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
283                 freebn(reqkey.exponent);
284                 freebn(reqkey.modulus);
285                 freebn(challenge);
286                 goto failure;
287             }
288             response = rsadecrypt(challenge, key);
289             for (i = 0; i < 32; i++)
290                 response_source[i] = bignum_byte(response, 31-i);
291
292             MD5Init(&md5c);
293             MD5Update(&md5c, response_source, 48);
294             MD5Final(response_md5, &md5c);
295             memset(response_source, 0, 48);   /* burn the evidence */
296             freebn(response);          /* and that evidence */
297             freebn(challenge);         /* yes, and that evidence */
298             freebn(reqkey.exponent);   /* and free some memory ... */
299             freebn(reqkey.modulus);    /* ... while we're at it. */
300
301             /*
302              * Packet is the obvious five byte header, plus sixteen
303              * bytes of MD5.
304              */
305             len = 5 + 16;
306             PUT_32BIT(ret, len-4);
307             ret[4] = SSH_AGENT_RSA_RESPONSE;
308             memcpy(ret+5, response_md5, 16);
309         }
310         break;
311       case SSH_AGENTC_ADD_RSA_IDENTITY:
312         /*
313          * Add to the list and return SSH_AGENT_SUCCESS, or
314          * SSH_AGENT_FAILURE if the key was malformed.
315          */
316         {
317             struct RSAKey *key;
318             char *comment;
319             key = malloc(sizeof(struct RSAKey));
320             memset(key, 0, sizeof(key));
321             p += makekey(p, key, NULL, 1);
322             p += makeprivate(p, key);
323             p += ssh1_read_bignum(p, NULL);    /* p^-1 mod q */
324             p += ssh1_read_bignum(p, NULL);    /* p */
325             p += ssh1_read_bignum(p, NULL);    /* q */
326             comment = malloc(GET_32BIT(p));
327             if (comment) {
328                 memcpy(comment, p+4, GET_32BIT(p));
329                 key->comment = comment;
330             }
331             PUT_32BIT(ret, 1);
332             ret[4] = SSH_AGENT_FAILURE;
333             if (add234(rsakeys, key) == key) {
334                 keylist_update();
335                 ret[4] = SSH_AGENT_SUCCESS;
336             } else {
337                 freersakey(key);
338                 free(key);
339             }
340         }
341         break;
342       case SSH_AGENTC_REMOVE_RSA_IDENTITY:
343         /*
344          * Remove from the list and return SSH_AGENT_SUCCESS, or
345          * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
346          * start with.
347          */
348         {
349             struct RSAKey reqkey, *key;
350
351             p += makekey(p, &reqkey, NULL, 0);
352             key = find234(rsakeys, &reqkey, NULL);
353             freebn(reqkey.exponent);
354             freebn(reqkey.modulus);
355             PUT_32BIT(ret, 1);
356             ret[4] = SSH_AGENT_FAILURE;
357             if (key) {
358                 del234(rsakeys, key);
359                 keylist_update();
360                 freersakey(key);
361                 ret[4] = SSH_AGENT_SUCCESS;
362             }
363         }
364         break;
365       default:
366         failure:
367         /*
368          * Unrecognised message. Return SSH_AGENT_FAILURE.
369          */
370         PUT_32BIT(ret, 1);
371         ret[4] = SSH_AGENT_FAILURE;
372         break;
373     }
374 }
375
376 /*
377  * Key comparison function for the 2-3-4 tree of RSA keys.
378  */
379 int cmpkeys(void *av, void *bv) {
380     struct RSAKey *a = (struct RSAKey *)av;
381     struct RSAKey *b = (struct RSAKey *)bv;
382     Bignum am, bm;
383     int alen, blen;
384
385     am = a->modulus;
386     bm = b->modulus;
387     /*
388      * Compare by length of moduli.
389      */
390     alen = ssh1_bignum_bitcount(am);
391     blen = ssh1_bignum_bitcount(bm);
392     if (alen > blen) return +1; else if (alen < blen) return -1;
393     /*
394      * Now compare by moduli themselves.
395      */
396     alen = (alen + 7) / 8;             /* byte count */
397     while (alen-- > 0) {
398         int abyte, bbyte;
399         abyte = bignum_byte(am, alen);
400         bbyte = bignum_byte(bm, alen);
401         if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
402     }
403     /*
404      * Give up.
405      */
406     return 0;
407 }
408
409 static void error(char *s) {
410     MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
411 }
412
413 /*
414  * Dialog-box function for the key list box.
415  */
416 static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
417                                 WPARAM wParam, LPARAM lParam) {
418     enum234 e;
419     struct RSAKey *key;
420     OPENFILENAME of;
421     char filename[FILENAME_MAX];
422
423     switch (msg) {
424       case WM_INITDIALOG:
425         keylist = hwnd;
426         {
427             static int tabs[2] = {25, 175};
428             SendDlgItemMessage (hwnd, 100, LB_SETTABSTOPS, 2,
429                                 (LPARAM) tabs);
430         }
431         keylist_update();
432         return 0;
433       case WM_COMMAND:
434         switch (LOWORD(wParam)) {
435           case IDOK:
436           case IDCANCEL:
437             keylist = NULL;
438             DestroyWindow(hwnd);
439             return 0;
440           case 101:                    /* add key */
441             if (HIWORD(wParam) == BN_CLICKED ||
442                 HIWORD(wParam) == BN_DOUBLECLICKED) {
443                 memset(&of, 0, sizeof(of));
444 #ifdef OPENFILENAME_SIZE_VERSION_400
445                 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
446 #else
447                 of.lStructSize = sizeof(of);
448 #endif
449                 of.hwndOwner = hwnd;
450                 of.lpstrFilter = "All Files\0*\0\0\0";
451                 of.lpstrCustomFilter = NULL;
452                 of.nFilterIndex = 1;
453                 of.lpstrFile = filename; *filename = '\0';
454                 of.nMaxFile = sizeof(filename);
455                 of.lpstrFileTitle = NULL;
456                 of.lpstrInitialDir = NULL;
457                 of.lpstrTitle = "Select Public Key File";
458                 of.Flags = 0;
459                 if (GetOpenFileName(&of)) {
460                     add_keyfile(filename);
461                     keylist_update();
462                 }
463             }
464             return 0;
465           case 102:                    /* remove key */
466             if (HIWORD(wParam) == BN_CLICKED ||
467                 HIWORD(wParam) == BN_DOUBLECLICKED) {
468                 int n = SendDlgItemMessage (hwnd, 100, LB_GETCURSEL, 0, 0);
469                 if (n == LB_ERR || n == 0) {
470                     MessageBeep(0);
471                     break;
472                 }
473                 for (key = first234(rsakeys, &e); key; key = next234(&e))
474                     if (n-- == 0)
475                         break;
476                 del234(rsakeys, key);
477                 freersakey(key); free(key);
478                 keylist_update();
479             }
480             return 0;
481         }
482         return 0;
483       case WM_CLOSE:
484         keylist = NULL;
485         DestroyWindow(hwnd);
486         return 0;
487     }
488     return 0;
489 }
490
491 static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
492                                  WPARAM wParam, LPARAM lParam) {
493     int ret;
494     static int menuinprogress;
495
496     switch (message) {
497       case WM_SYSTRAY:
498         if (lParam == WM_RBUTTONUP) {
499             POINT cursorpos;
500             GetCursorPos(&cursorpos);
501             PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
502         } else if (lParam == WM_LBUTTONDBLCLK) {
503             /* Equivalent to IDM_VIEWKEYS. */
504             PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
505         }
506         break;
507       case WM_SYSTRAY2:
508         if (!menuinprogress) {
509             menuinprogress = 1;
510             SetForegroundWindow(hwnd);
511             ret = TrackPopupMenu(systray_menu,
512                                  TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
513                                  TPM_RIGHTBUTTON,
514                                  wParam, lParam, 0, hwnd, NULL);
515             menuinprogress = 0;
516         }
517         break;
518       case WM_COMMAND:
519       case WM_SYSCOMMAND:
520         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
521           case IDM_CLOSE:
522             SendMessage(hwnd, WM_CLOSE, 0, 0);
523             break;
524           case IDM_VIEWKEYS:
525             if (!keylist) {
526                 keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
527                                         NULL, KeyListProc);
528                 ShowWindow (keylist, SW_SHOWNORMAL);
529                 /* 
530                  * Sometimes the window comes up minimised / hidden
531                  * for no obvious reason. Prevent this.
532                  */
533                 SetForegroundWindow(keylist);
534                 SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
535                               SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
536             }
537             break;
538         }
539         break;
540       case WM_DESTROY:
541         PostQuitMessage (0);
542         return 0;
543       case WM_COPYDATA:
544         {
545             COPYDATASTRUCT *cds;
546             char *mapname;
547             void *p;
548             HANDLE filemap, proc;
549             PSID mapowner, procowner;
550             PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
551             int ret = 0;
552
553             cds = (COPYDATASTRUCT *)lParam;
554             if (cds->dwData != AGENT_COPYDATA_ID)
555                 return 0;              /* not our message, mate */
556             mapname = (char *)cds->lpData;
557             if (mapname[cds->cbData - 1] != '\0')
558                 return 0;              /* failure to be ASCIZ! */
559 #ifdef DEBUG_IPC
560             debug(("mapname is :%s:\r\n", mapname));
561 #endif
562             filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
563 #ifdef DEBUG_IPC
564             debug(("filemap is %p\r\n", filemap));
565 #endif
566             if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
567                 int rc;
568                 if (has_security) {
569                     if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
570                                             GetCurrentProcessId())) == NULL) {
571 #ifdef DEBUG_IPC
572                         debug(("couldn't get handle for process\r\n"));
573 #endif
574                         return 0;
575                     }
576                     if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
577                                         OWNER_SECURITY_INFORMATION,
578                                         &procowner, NULL, NULL, NULL,
579                                         &psd2) != ERROR_SUCCESS) {
580 #ifdef DEBUG_IPC
581                         debug(("couldn't get owner info for process\r\n"));
582 #endif
583                         CloseHandle(proc);
584                         return 0;          /* unable to get security info */
585                     }
586                     CloseHandle(proc);
587                     if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
588                                               OWNER_SECURITY_INFORMATION,
589                                               &mapowner, NULL, NULL, NULL,
590                                               &psd1) != ERROR_SUCCESS)) {
591 #ifdef DEBUG_IPC
592                         debug(("couldn't get owner info for filemap: %d\r\n", rc));
593 #endif
594                         return 0;
595                     }
596 #ifdef DEBUG_IPC
597                     debug(("got security stuff\r\n"));
598 #endif
599                     if (!EqualSid(mapowner, procowner))
600                         return 0;          /* security ID mismatch! */
601 #ifdef DEBUG_IPC
602                     debug(("security stuff matched\r\n"));
603 #endif
604                     LocalFree(psd1);
605                     LocalFree(psd2);
606                 } else {
607 #ifdef DEBUG_IPC
608                     debug(("security APIs not present\r\n"));
609 #endif
610                 }
611                 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
612 #ifdef DEBUG_IPC
613                 debug(("p is %p\r\n", p));
614                 {int i; for(i=0;i<5;i++)debug(("p[%d]=%02x\r\n", i, ((unsigned char *)p)[i]));}
615 #endif
616                 answer_msg(p);
617                 ret = 1;
618                 UnmapViewOfFile(p);
619             }
620             CloseHandle(filemap);
621             return ret;
622         }
623     }
624
625     return DefWindowProc (hwnd, message, wParam, lParam);
626 }
627
628 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
629     WNDCLASS wndclass;
630     MSG msg;
631     OSVERSIONINFO osi;
632     HMODULE advapi;
633
634     /*
635      * Determine whether we're an NT system (should have security
636      * APIs) or a non-NT system (don't do security).
637      */
638     memset(&osi, 0, sizeof(OSVERSIONINFO));
639     osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
640     if (GetVersionEx(&osi) && osi.dwPlatformId==VER_PLATFORM_WIN32_NT) {
641         has_security = TRUE;
642     } else
643         has_security = FALSE;
644
645     if (has_security) {
646         /*
647          * Attempt to ge the security API we need.
648          */
649         advapi = LoadLibrary("ADVAPI32.DLL");
650         getsecurityinfo = (gsi_fn_t)GetProcAddress(advapi, "GetSecurityInfo");
651         if (!getsecurityinfo) {
652             MessageBox(NULL,
653                        "Unable to access security APIs. Pageant will\n"
654                        "not run, in case it causes a security breach.",
655                        "Pageant Fatal Error", MB_ICONERROR | MB_OK);
656             return 1;
657         }
658     } else
659         advapi = NULL;
660
661     /*
662      * First bomb out totally if we are already running.
663      */
664     if (FindWindow("Pageant", "Pageant")) {
665         MessageBox(NULL, "Pageant is already running", "Pageant Error",
666                    MB_ICONERROR | MB_OK);
667         if (advapi) FreeLibrary(advapi);
668         return 0;
669     }
670
671     instance = inst;
672
673     if (!prev) {
674         wndclass.style         = 0;
675         wndclass.lpfnWndProc   = WndProc;
676         wndclass.cbClsExtra    = 0;
677         wndclass.cbWndExtra    = 0;
678         wndclass.hInstance     = inst;
679         wndclass.hIcon         = LoadIcon (inst,
680                                            MAKEINTRESOURCE(IDI_MAINICON));
681         wndclass.hCursor       = LoadCursor (NULL, IDC_IBEAM);
682         wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
683         wndclass.lpszMenuName  = NULL;
684         wndclass.lpszClassName = APPNAME;
685
686         RegisterClass (&wndclass);
687     }
688
689     hwnd = keylist = NULL;
690
691     hwnd = CreateWindow (APPNAME, APPNAME,
692                          WS_OVERLAPPEDWINDOW | WS_VSCROLL,
693                          CW_USEDEFAULT, CW_USEDEFAULT,
694                          100, 100, NULL, NULL, inst, NULL);
695
696     /* Set up a system tray icon */
697     {
698         BOOL res;
699         NOTIFYICONDATA tnid;
700         HICON hicon;
701
702 #ifdef NIM_SETVERSION
703         tnid.uVersion = 0;
704         res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
705 #endif
706
707         tnid.cbSize = sizeof(NOTIFYICONDATA); 
708         tnid.hWnd = hwnd; 
709         tnid.uID = 1;                  /* unique within this systray use */
710         tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; 
711         tnid.uCallbackMessage = WM_SYSTRAY;
712         tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
713         strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
714
715         res = Shell_NotifyIcon(NIM_ADD, &tnid); 
716
717         if (hicon) 
718             DestroyIcon(hicon); 
719
720         systray_menu = CreatePopupMenu();
721         AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "&View Keys");
722         AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
723     }
724
725     ShowWindow (hwnd, SW_HIDE);
726
727     /*
728      * Initialise storage for RSA keys.
729      */
730     rsakeys = newtree234(cmpkeys);
731
732     /*
733      * Process the command line and add RSA keys as listed on it.
734      */
735     {
736         char *p;
737         int inquotes = 0;
738         p = cmdline;
739         while (*p) {
740             while (*p && isspace(*p)) p++;
741             if (*p && !isspace(*p)) {
742                 char *q = p, *pp = p;
743                 while (*p && (inquotes || !isspace(*p)))
744                 {
745                     if (*p == '"') {
746                         inquotes = !inquotes;
747                         p++;
748                         continue;
749                     }
750                     *pp++ = *p++;
751                 }
752                 if (*pp) {
753                     if (*p) p++;
754                     *pp++ = '\0';
755                 }
756                 add_keyfile(q);
757             }
758         }
759     }
760
761     /*
762      * Main message loop.
763      */
764     while (GetMessage(&msg, NULL, 0, 0) == 1) {
765         TranslateMessage(&msg);
766         DispatchMessage(&msg);
767     }
768
769     /* Clean up the system tray icon */
770     {
771         NOTIFYICONDATA tnid;
772
773         tnid.cbSize = sizeof(NOTIFYICONDATA); 
774         tnid.hWnd = hwnd;
775         tnid.uID = 1;
776
777         Shell_NotifyIcon(NIM_DELETE, &tnid); 
778
779         DestroyMenu(systray_menu);
780     }
781
782     if (advapi) FreeLibrary(advapi);
783     exit(msg.wParam);
784 }