]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - pageant.c
Double-clicking on the Pageant systray icon now brings up the key list
[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 /*
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  */
56 int 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  */
65 void 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  */
85 static 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  */
123 void add_keyfile(char *filename) {
124     char passphrase[PASSPHRASE_MAXLEN];
125     struct RSAKey *key;
126     int needs_pass;
127     int ret;
128     int attempts;
129
130     /* FIXME: we can acquire comment here and use it in dialog */
131     needs_pass = rsakey_encrypted(filename, NULL);
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  */
162 void answer_msg(void *msg) {
163     unsigned char *p = msg;
164     unsigned char *ret = msg;
165     int type;
166
167     /*
168      * Get the message type.
169      */
170     type = p[4];
171
172     p += 5;
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;
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);
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;
260             PUT_32BIT(ret, len-4);
261             ret[4] = SSH_AGENT_RSA_RESPONSE;
262             memcpy(ret+5, response_md5, 16);
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          */
285         PUT_32BIT(ret, 1);
286         ret[4] = SSH_AGENT_FAILURE;
287         break;
288     }
289 }
290
291 /*
292  * Key comparison function for the 2-3-4 tree of RSA keys.
293  */
294 int 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
324 static 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  */
331 static 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
413 static 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);
424         } else if (lParam == WM_LBUTTONDBLCLK) {
425             /* Equivalent to IDM_VIEWKEYS. */
426             PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
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);
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);
458             }
459             break;
460         }
461         break;
462       case WM_DESTROY:
463         PostQuitMessage (0);
464         return 0;
465       case WM_COPYDATA:
466         {
467             COPYDATASTRUCT *cds;
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;
474
475             cds = (COPYDATASTRUCT *)lParam;
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;
516                 }
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;
538         }
539     }
540
541     return DefWindowProc (hwnd, message, wParam, lParam);
542 }
543
544 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
545     WNDCLASS wndclass;
546     MSG msg;
547
548     instance = inst;
549
550     if (!prev) {
551         wndclass.style         = 0;
552         wndclass.lpfnWndProc   = WndProc;
553         wndclass.cbClsExtra    = 0;
554         wndclass.cbWndExtra    = 0;
555         wndclass.hInstance     = inst;
556         wndclass.hIcon         = LoadIcon (inst,
557                                            MAKEINTRESOURCE(IDI_MAINICON));
558         wndclass.hCursor       = LoadCursor (NULL, IDC_IBEAM);
559         wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
560         wndclass.lpszMenuName  = NULL;
561         wndclass.lpszClassName = APPNAME;
562
563         RegisterClass (&wndclass);
564     }
565
566     hwnd = keylist = NULL;
567
568     hwnd = CreateWindow (APPNAME, APPNAME,
569                          WS_OVERLAPPEDWINDOW | WS_VSCROLL,
570                          CW_USEDEFAULT, CW_USEDEFAULT,
571                          100, 100, NULL, NULL, inst, NULL);
572
573     /* Set up a system tray icon */
574     {
575         BOOL res;
576         NOTIFYICONDATA tnid;
577         HICON hicon;
578
579 #ifdef NIM_SETVERSION
580         tnid.uVersion = 0;
581         res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
582 #endif
583
584         tnid.cbSize = sizeof(NOTIFYICONDATA); 
585         tnid.hWnd = hwnd; 
586         tnid.uID = 1;                  /* unique within this systray use */
587         tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; 
588         tnid.uCallbackMessage = WM_SYSTRAY;
589         tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
590         strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
591
592         res = Shell_NotifyIcon(NIM_ADD, &tnid); 
593
594         if (hicon) 
595             DestroyIcon(hicon); 
596
597         systray_menu = CreatePopupMenu();
598         AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "View Keys");
599         AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "Terminate");
600     }
601
602     ShowWindow (hwnd, SW_HIDE);
603
604     /*
605      * Initialise storage for RSA keys.
606      */
607     rsakeys = newtree234(cmpkeys);
608
609     /*
610      * Process the command line and add RSA keys as listed on it.
611      * FIXME: we don't support spaces in filenames here. We should.
612      */
613     {
614         char *p = cmdline;
615         while (*p) {
616             while (*p && isspace(*p)) p++;
617             if (*p && !isspace(*p)) {
618                 char *q = p;
619                 while (*p && !isspace(*p)) p++;
620                 if (*p) *p++ = '\0';
621                 add_keyfile(q);
622             }
623         }
624     }
625
626     /*
627      * Main message loop.
628      */
629     while (GetMessage(&msg, NULL, 0, 0) == 1) {
630         TranslateMessage(&msg);
631         DispatchMessage(&msg);
632     }
633
634     /* Clean up the system tray icon */
635     {
636         NOTIFYICONDATA tnid;
637
638         tnid.cbSize = sizeof(NOTIFYICONDATA); 
639         tnid.hWnd = hwnd;
640         tnid.uID = 1;
641
642         Shell_NotifyIcon(NIM_DELETE, &tnid); 
643
644         DestroyMenu(systray_menu);
645     }
646
647     exit(msg.wParam);
648 }