2 * Pageant: the PuTTY Authentication Agent.
7 #include <stdio.h> /* FIXME */
8 #include "putty.h" /* FIXME */
12 #define IDI_MAINICON 200
13 #define IDI_TRAYICON 201
15 #define WM_XUSER (WM_USER + 0x2000)
16 #define WM_SYSTRAY (WM_XUSER + 6)
17 #define WM_SYSTRAY2 (WM_XUSER + 7)
19 #define AGENT_COPYDATA_ID 0x804e50ba /* random goop */
22 * FIXME: maybe some day we can sort this out ...
24 #define AGENT_MAX_MSGLEN 8192
26 #define IDM_CLOSE 0x0010
27 #define IDM_VIEWKEYS 0x0020
29 #define APPNAME "Pageant"
31 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES 1
32 #define SSH_AGENT_RSA_IDENTITIES_ANSWER 2
33 #define SSH_AGENTC_RSA_CHALLENGE 3
34 #define SSH_AGENT_RSA_RESPONSE 4
35 #define SSH_AGENT_FAILURE 5
36 #define SSH_AGENT_SUCCESS 6
37 #define SSH_AGENTC_ADD_RSA_IDENTITY 7
38 #define SSH_AGENTC_REMOVE_RSA_IDENTITY 8
48 typedef DWORD (WINAPI *gsi_fn_t)
49 (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
50 PSID *, PSID *, PACL *, PACL *,
51 PSECURITY_DESCRIPTOR *);
52 gsi_fn_t getsecurityinfo;
55 * We need this to link with the RSA code, because rsaencrypt()
56 * pads its data with random bytes. Since we only use rsadecrypt(),
57 * which is deterministic, this should never be called.
59 * If it _is_ called, there is a _serious_ problem, because it
60 * won't generate true random numbers. So we must scream, panic,
61 * and exit immediately if that should happen.
63 int random_byte(void) {
64 MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
69 * This function is needed to link with the DES code. We need not
70 * have it do anything at all.
72 void logevent(char *msg) {
75 #define GET_32BIT(cp) \
76 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
77 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
78 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
79 ((unsigned long)(unsigned char)(cp)[3]))
81 #define PUT_32BIT(cp, value) { \
82 (cp)[0] = (unsigned char)((value) >> 24); \
83 (cp)[1] = (unsigned char)((value) >> 16); \
84 (cp)[2] = (unsigned char)((value) >> 8); \
85 (cp)[3] = (unsigned char)(value); }
87 #define PASSPHRASE_MAXLEN 512
90 * Dialog-box function for the passphrase box.
92 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
93 WPARAM wParam, LPARAM lParam) {
94 static char *passphrase;
98 passphrase = (char *)lParam;
102 switch (LOWORD(wParam)) {
112 case 102: /* edit box */
113 if (HIWORD(wParam) == EN_CHANGE) {
114 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
115 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
128 * This function loads a key from a file and adds it.
130 void add_keyfile(char *filename) {
131 char passphrase[PASSPHRASE_MAXLEN];
137 /* FIXME: we can acquire comment here and use it in dialog */
138 needs_pass = rsakey_encrypted(filename, NULL);
140 key = malloc(sizeof(*key));
144 dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
145 NULL, PassphraseProc,
149 return; /* operation cancelled */
153 ret = loadrsakey(filename, key, passphrase);
157 MessageBox(NULL, "Couldn't load public key.", APPNAME,
158 MB_OK | MB_ICONERROR);
162 if (add234(rsakeys, key) != key)
163 free(key); /* already present, don't waste RAM */
167 * This is the main agent function that answers messages.
169 void answer_msg(void *msg) {
170 unsigned char *p = msg;
171 unsigned char *ret = msg;
175 * Get the message type.
181 case SSH_AGENTC_REQUEST_RSA_IDENTITIES:
183 * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
191 * Count up the number and length of keys we hold.
194 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
196 len += 4; /* length field */
197 len += ssh1_bignum_length(key->exponent);
198 len += ssh1_bignum_length(key->modulus);
199 len += 4 + strlen(key->comment);
203 * Packet header is the obvious five bytes, plus four
204 * bytes for the key count.
207 if (len > AGENT_MAX_MSGLEN)
208 goto failure; /* aaargh! too much stuff! */
209 PUT_32BIT(ret, len-4);
210 ret[4] = SSH_AGENT_RSA_IDENTITIES_ANSWER;
211 PUT_32BIT(ret+5, nkeys);
213 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
214 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus));
216 p += ssh1_write_bignum(p, key->exponent);
217 p += ssh1_write_bignum(p, key->modulus);
218 PUT_32BIT(p, strlen(key->comment));
219 memcpy(p+4, key->comment, strlen(key->comment));
220 p += 4 + strlen(key->comment);
224 case SSH_AGENTC_RSA_CHALLENGE:
226 * Reply with either SSH_AGENT_RSA_RESPONSE or
227 * SSH_AGENT_FAILURE, depending on whether we have that key
231 struct RSAKey reqkey, *key;
232 Bignum challenge, response;
233 unsigned char response_source[48], response_md5[16];
234 struct MD5Context md5c;
238 p += ssh1_read_bignum(p, &reqkey.exponent);
239 p += ssh1_read_bignum(p, &reqkey.modulus);
240 p += ssh1_read_bignum(p, &challenge);
241 memcpy(response_source+32, p, 16); p += 16;
242 if (GET_32BIT(p) != 1 ||
243 (key = find234(rsakeys, &reqkey, NULL)) == NULL) {
244 freebn(reqkey.exponent);
245 freebn(reqkey.modulus);
249 response = rsadecrypt(challenge, key);
250 for (i = 0; i < 32; i++)
251 response_source[i] = bignum_byte(response, 31-i);
254 MD5Update(&md5c, response_source, 48);
255 MD5Final(response_md5, &md5c);
256 memset(response_source, 0, 48); /* burn the evidence */
257 freebn(response); /* and that evidence */
258 freebn(challenge); /* yes, and that evidence */
259 freebn(reqkey.exponent); /* and free some memory ... */
260 freebn(reqkey.modulus); /* ... while we're at it. */
263 * Packet is the obvious five byte header, plus sixteen
267 PUT_32BIT(ret, len-4);
268 ret[4] = SSH_AGENT_RSA_RESPONSE;
269 memcpy(ret+5, response_md5, 16);
272 #if 0 /* FIXME: implement these */
273 case SSH_AGENTC_ADD_RSA_IDENTITY:
275 * Add to the list and return SSH_AGENT_SUCCESS, or
276 * SSH_AGENT_FAILURE if the key was malformed.
279 case SSH_AGENTC_REMOVE_RSA_IDENTITY:
281 * Remove from the list and return SSH_AGENT_SUCCESS, or
282 * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
290 * Unrecognised message. Return SSH_AGENT_FAILURE.
293 ret[4] = SSH_AGENT_FAILURE;
299 * Key comparison function for the 2-3-4 tree of RSA keys.
301 int cmpkeys(void *av, void *bv) {
302 struct RSAKey *a = (struct RSAKey *)av;
303 struct RSAKey *b = (struct RSAKey *)bv;
310 * Compare by length of moduli.
312 alen = ssh1_bignum_bitcount(am);
313 blen = ssh1_bignum_bitcount(bm);
314 if (alen > blen) return +1; else if (alen < blen) return -1;
316 * Now compare by moduli themselves.
318 alen = (alen + 7) / 8; /* byte count */
321 abyte = bignum_byte(am, alen);
322 bbyte = bignum_byte(bm, alen);
323 if (abyte > bbyte) return +1; else if (abyte < bbyte) return -1;
331 static void error(char *s) {
332 MessageBox(hwnd, s, APPNAME, MB_OK | MB_ICONERROR);
336 * Dialog-box function for the key list box.
338 static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
339 WPARAM wParam, LPARAM lParam) {
343 char filename[FILENAME_MAX];
347 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
348 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
349 0, (LPARAM) key->comment);
353 switch (LOWORD(wParam)) {
359 case 101: /* add key */
360 if (HIWORD(wParam) == BN_CLICKED ||
361 HIWORD(wParam) == BN_DOUBLECLICKED) {
362 memset(&of, 0, sizeof(of));
363 #ifdef OPENFILENAME_SIZE_VERSION_400
364 of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
366 of.lStructSize = sizeof(of);
369 of.lpstrFilter = "All Files\0*\0\0\0";
370 of.lpstrCustomFilter = NULL;
372 of.lpstrFile = filename; *filename = '\0';
373 of.nMaxFile = sizeof(filename);
374 of.lpstrFileTitle = NULL;
375 of.lpstrInitialDir = NULL;
376 of.lpstrTitle = "Select Public Key File";
378 if (GetOpenFileName(&of)) {
379 add_keyfile(filename);
381 SendDlgItemMessage(hwnd, 100, LB_RESETCONTENT, 0, 0);
382 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
383 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
384 0, (LPARAM) key->comment);
386 SendDlgItemMessage (hwnd, 100, LB_SETCURSEL, (WPARAM) -1, 0);
389 case 102: /* remove key */
390 if (HIWORD(wParam) == BN_CLICKED ||
391 HIWORD(wParam) == BN_DOUBLECLICKED) {
392 int n = SendDlgItemMessage (hwnd, 100, LB_GETCURSEL, 0, 0);
393 if (n == LB_ERR || n == 0) {
397 for (key = first234(rsakeys, &e); key; key = next234(&e))
400 del234(rsakeys, key);
401 freersakey(key); free(key);
402 SendDlgItemMessage(hwnd, 100, LB_RESETCONTENT, 0, 0);
403 for (key = first234(rsakeys, &e); key; key = next234(&e)) {
404 SendDlgItemMessage (hwnd, 100, LB_ADDSTRING,
405 0, (LPARAM) key->comment);
407 SendDlgItemMessage (hwnd, 100, LB_SETCURSEL, (WPARAM) -1, 0);
420 static LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
421 WPARAM wParam, LPARAM lParam) {
423 static int menuinprogress;
427 if (lParam == WM_RBUTTONUP) {
429 GetCursorPos(&cursorpos);
430 PostMessage(hwnd, WM_SYSTRAY2, cursorpos.x, cursorpos.y);
431 } else if (lParam == WM_LBUTTONDBLCLK) {
432 /* Equivalent to IDM_VIEWKEYS. */
433 PostMessage(hwnd, WM_COMMAND, IDM_VIEWKEYS, 0);
437 if (!menuinprogress) {
439 SetForegroundWindow(hwnd);
440 ret = TrackPopupMenu(systray_menu,
441 TPM_RIGHTALIGN | TPM_BOTTOMALIGN |
443 wParam, lParam, 0, hwnd, NULL);
449 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
451 SendMessage(hwnd, WM_CLOSE, 0, 0);
455 keylist = CreateDialog (instance, MAKEINTRESOURCE(211),
457 ShowWindow (keylist, SW_SHOWNORMAL);
459 * Sometimes the window comes up minimised / hidden
460 * for no obvious reason. Prevent this.
462 SetForegroundWindow(keylist);
463 SetWindowPos (keylist, HWND_TOP, 0, 0, 0, 0,
464 SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
477 HANDLE filemap, proc;
478 PSID mapowner, procowner;
479 PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
482 cds = (COPYDATASTRUCT *)lParam;
483 if (cds->dwData != AGENT_COPYDATA_ID)
484 return 0; /* not our message, mate */
485 mapname = (char *)cds->lpData;
486 if (mapname[cds->cbData - 1] != '\0')
487 return 0; /* failure to be ASCIZ! */
489 debug(("mapname is :%s:\r\n", mapname));
491 filemap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, mapname);
493 debug(("filemap is %p\r\n", filemap));
495 if (filemap != NULL && filemap != INVALID_HANDLE_VALUE) {
498 if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
499 GetCurrentProcessId())) == NULL) {
501 debug(("couldn't get handle for process\r\n"));
505 if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
506 OWNER_SECURITY_INFORMATION,
507 &procowner, NULL, NULL, NULL,
508 &psd2) != ERROR_SUCCESS) {
510 debug(("couldn't get owner info for process\r\n"));
513 return 0; /* unable to get security info */
516 if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
517 OWNER_SECURITY_INFORMATION,
518 &mapowner, NULL, NULL, NULL,
519 &psd1) != ERROR_SUCCESS)) {
521 debug(("couldn't get owner info for filemap: %d\r\n", rc));
526 debug(("got security stuff\r\n"));
528 if (!EqualSid(mapowner, procowner))
529 return 0; /* security ID mismatch! */
531 debug(("security stuff matched\r\n"));
537 debug(("security APIs not present\r\n"));
540 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, 0);
542 debug(("p is %p\r\n", p));
543 {int i; for(i=0;i<5;i++)debug(("p[%d]=%02x\r\n", i, ((unsigned char *)p)[i]));}
549 CloseHandle(filemap);
554 return DefWindowProc (hwnd, message, wParam, lParam);
557 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
564 * Determine whether we're an NT system (should have security
565 * APIs) or a non-NT system (don't do security).
567 memset(&osi, 0, sizeof(OSVERSIONINFO));
568 osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
569 if (GetVersionEx(&osi) && osi.dwPlatformId==VER_PLATFORM_WIN32_NT) {
572 has_security = FALSE;
576 * Attempt to ge the security API we need.
578 advapi = LoadLibrary("ADVAPI32.DLL");
579 getsecurityinfo = (gsi_fn_t)GetProcAddress(advapi, "GetSecurityInfo");
580 if (!getsecurityinfo) {
582 "Unable to access security APIs. Pageant will\n"
583 "not run, in case it causes a security breach.",
584 "Pageant Fatal Error", MB_ICONERROR | MB_OK);
591 * First bomb out totally if we are already running.
593 if (FindWindow("Pageant", "Pageant")) {
594 MessageBox(NULL, "Pageant is already running", "Pageant Error",
595 MB_ICONERROR | MB_OK);
596 if (advapi) FreeLibrary(advapi);
604 wndclass.lpfnWndProc = WndProc;
605 wndclass.cbClsExtra = 0;
606 wndclass.cbWndExtra = 0;
607 wndclass.hInstance = inst;
608 wndclass.hIcon = LoadIcon (inst,
609 MAKEINTRESOURCE(IDI_MAINICON));
610 wndclass.hCursor = LoadCursor (NULL, IDC_IBEAM);
611 wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
612 wndclass.lpszMenuName = NULL;
613 wndclass.lpszClassName = APPNAME;
615 RegisterClass (&wndclass);
618 hwnd = keylist = NULL;
620 hwnd = CreateWindow (APPNAME, APPNAME,
621 WS_OVERLAPPEDWINDOW | WS_VSCROLL,
622 CW_USEDEFAULT, CW_USEDEFAULT,
623 100, 100, NULL, NULL, inst, NULL);
625 /* Set up a system tray icon */
631 #ifdef NIM_SETVERSION
633 res = Shell_NotifyIcon(NIM_SETVERSION, &tnid);
636 tnid.cbSize = sizeof(NOTIFYICONDATA);
638 tnid.uID = 1; /* unique within this systray use */
639 tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
640 tnid.uCallbackMessage = WM_SYSTRAY;
641 tnid.hIcon = hicon = LoadIcon (instance, MAKEINTRESOURCE(201));
642 strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
644 res = Shell_NotifyIcon(NIM_ADD, &tnid);
649 systray_menu = CreatePopupMenu();
650 AppendMenu (systray_menu, MF_ENABLED, IDM_VIEWKEYS, "View Keys");
651 AppendMenu (systray_menu, MF_ENABLED, IDM_CLOSE, "Terminate");
654 ShowWindow (hwnd, SW_HIDE);
657 * Initialise storage for RSA keys.
659 rsakeys = newtree234(cmpkeys);
662 * Process the command line and add RSA keys as listed on it.
669 while (*p && isspace(*p)) p++;
670 if (*p && !isspace(*p)) {
671 char *q = p, *pp = p;
672 while (*p && (inquotes || !isspace(*p)))
675 inquotes = !inquotes;
693 while (GetMessage(&msg, NULL, 0, 0) == 1) {
694 TranslateMessage(&msg);
695 DispatchMessage(&msg);
698 /* Clean up the system tray icon */
702 tnid.cbSize = sizeof(NOTIFYICONDATA);
706 Shell_NotifyIcon(NIM_DELETE, &tnid);
708 DestroyMenu(systray_menu);
711 if (advapi) FreeLibrary(advapi);