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
89 struct PassphraseProcStruct
{
95 * Dialog-box function for the passphrase box.
97 static int CALLBACK
PassphraseProc(HWND hwnd
, UINT msg
,
98 WPARAM wParam
, LPARAM lParam
) {
99 static char *passphrase
;
100 struct PassphraseProcStruct
*p
;
104 p
= (struct PassphraseProcStruct
*)lParam
;
105 passphrase
= p
->passphrase
;
107 SetDlgItemText(hwnd
, 101, p
->comment
);
111 switch (LOWORD(wParam
)) {
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';
137 * Update the visible key list.
139 void keylist_update(void) {
144 SendDlgItemMessage(keylist
, 100, LB_RESETCONTENT
, 0, 0);
145 for (key
= first234(rsakeys
, &e
); key
; key
= next234(&e
)) {
146 char listentry
[512], *p
;
148 * Replace two spaces in the fingerprint with tabs, for
149 * nice alignment in the box.
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
);
157 SendDlgItemMessage (keylist
, 100, LB_SETCURSEL
, (WPARAM
) -1, 0);
162 * This function loads a key from a file and adds it.
164 void add_keyfile(char *filename
) {
165 char passphrase
[PASSPHRASE_MAXLEN
];
171 struct PassphraseProcStruct pps
;
173 needs_pass
= rsakey_encrypted(filename
, &comment
);
175 key
= malloc(sizeof(*key
));
176 pps
.passphrase
= passphrase
;
177 pps
.comment
= comment
;
181 dlgret
= DialogBoxParam(instance
, MAKEINTRESOURCE(210),
182 NULL
, PassphraseProc
,
185 if (comment
) free(comment
);
187 return; /* operation cancelled */
191 ret
= loadrsakey(filename
, key
, passphrase
);
194 if (comment
) free(comment
);
196 MessageBox(NULL
, "Couldn't load public key.", APPNAME
,
197 MB_OK
| MB_ICONERROR
);
201 if (add234(rsakeys
, key
) != key
)
202 free(key
); /* already present, don't waste RAM */
206 * This is the main agent function that answers messages.
208 void answer_msg(void *msg
) {
209 unsigned char *p
= msg
;
210 unsigned char *ret
= msg
;
214 * Get the message type.
220 case SSH_AGENTC_REQUEST_RSA_IDENTITIES
:
222 * Reply with SSH_AGENT_RSA_IDENTITIES_ANSWER.
230 * Count up the number and length of keys we hold.
233 for (key
= first234(rsakeys
, &e
); key
; key
= next234(&e
)) {
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
);
242 * Packet header is the obvious five bytes, plus four
243 * bytes for the key count.
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
);
252 for (key
= first234(rsakeys
, &e
); key
; key
= next234(&e
)) {
253 PUT_32BIT(p
, ssh1_bignum_bitcount(key
->modulus
));
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
);
263 case SSH_AGENTC_RSA_CHALLENGE
:
265 * Reply with either SSH_AGENT_RSA_RESPONSE or
266 * SSH_AGENT_FAILURE, depending on whether we have that key
270 struct RSAKey reqkey
, *key
;
271 Bignum challenge
, response
;
272 unsigned char response_source
[48], response_md5
[16];
273 struct MD5Context md5c
;
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
);
288 response
= rsadecrypt(challenge
, key
);
289 for (i
= 0; i
< 32; i
++)
290 response_source
[i
] = bignum_byte(response
, 31-i
);
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. */
302 * Packet is the obvious five byte header, plus sixteen
306 PUT_32BIT(ret
, len
-4);
307 ret
[4] = SSH_AGENT_RSA_RESPONSE
;
308 memcpy(ret
+5, response_md5
, 16);
311 case SSH_AGENTC_ADD_RSA_IDENTITY
:
313 * Add to the list and return SSH_AGENT_SUCCESS, or
314 * SSH_AGENT_FAILURE if the key was malformed.
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
));
328 memcpy(comment
, p
+4, GET_32BIT(p
));
329 key
->comment
= comment
;
332 ret
[4] = SSH_AGENT_FAILURE
;
333 if (add234(rsakeys
, key
) == key
) {
335 ret
[4] = SSH_AGENT_SUCCESS
;
342 case SSH_AGENTC_REMOVE_RSA_IDENTITY
:
344 * Remove from the list and return SSH_AGENT_SUCCESS, or
345 * perhaps SSH_AGENT_FAILURE if it wasn't in the list to
349 struct RSAKey reqkey
, *key
;
351 p
+= makekey(p
, &reqkey
, NULL
, 0);
352 key
= find234(rsakeys
, &reqkey
, NULL
);
353 freebn(reqkey
.exponent
);
354 freebn(reqkey
.modulus
);
356 ret
[4] = SSH_AGENT_FAILURE
;
358 del234(rsakeys
, key
);
361 ret
[4] = SSH_AGENT_SUCCESS
;
368 * Unrecognised message. Return SSH_AGENT_FAILURE.
371 ret
[4] = SSH_AGENT_FAILURE
;
377 * Key comparison function for the 2-3-4 tree of RSA keys.
379 int cmpkeys(void *av
, void *bv
) {
380 struct RSAKey
*a
= (struct RSAKey
*)av
;
381 struct RSAKey
*b
= (struct RSAKey
*)bv
;
388 * Compare by length of moduli.
390 alen
= ssh1_bignum_bitcount(am
);
391 blen
= ssh1_bignum_bitcount(bm
);
392 if (alen
> blen
) return +1; else if (alen
< blen
) return -1;
394 * Now compare by moduli themselves.
396 alen
= (alen
+ 7) / 8; /* byte count */
399 abyte
= bignum_byte(am
, alen
);
400 bbyte
= bignum_byte(bm
, alen
);
401 if (abyte
> bbyte
) return +1; else if (abyte
< bbyte
) return -1;
409 static void error(char *s
) {
410 MessageBox(hwnd
, s
, APPNAME
, MB_OK
| MB_ICONERROR
);
414 * Dialog-box function for the key list box.
416 static int CALLBACK
KeyListProc(HWND hwnd
, UINT msg
,
417 WPARAM wParam
, LPARAM lParam
) {
421 char filename
[FILENAME_MAX
];
427 static int tabs
[2] = {25, 175};
428 SendDlgItemMessage (hwnd
, 100, LB_SETTABSTOPS
, 2,
434 switch (LOWORD(wParam
)) {
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
;
447 of
.lStructSize
= sizeof(of
);
450 of
.lpstrFilter
= "All Files\0*\0\0\0";
451 of
.lpstrCustomFilter
= NULL
;
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";
459 if (GetOpenFileName(&of
)) {
460 add_keyfile(filename
);
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) {
473 for (key
= first234(rsakeys
, &e
); key
; key
= next234(&e
))
476 del234(rsakeys
, key
);
477 freersakey(key
); free(key
);
491 static LRESULT CALLBACK
WndProc (HWND hwnd
, UINT message
,
492 WPARAM wParam
, LPARAM lParam
) {
494 static int menuinprogress
;
498 if (lParam
== WM_RBUTTONUP
) {
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);
508 if (!menuinprogress
) {
510 SetForegroundWindow(hwnd
);
511 ret
= TrackPopupMenu(systray_menu
,
512 TPM_RIGHTALIGN
| TPM_BOTTOMALIGN
|
514 wParam
, lParam
, 0, hwnd
, NULL
);
520 switch (wParam
& ~0xF) { /* low 4 bits reserved to Windows */
522 SendMessage(hwnd
, WM_CLOSE
, 0, 0);
526 keylist
= CreateDialog (instance
, MAKEINTRESOURCE(211),
528 ShowWindow (keylist
, SW_SHOWNORMAL
);
530 * Sometimes the window comes up minimised / hidden
531 * for no obvious reason. Prevent this.
533 SetForegroundWindow(keylist
);
534 SetWindowPos (keylist
, HWND_TOP
, 0, 0, 0, 0,
535 SWP_NOMOVE
| SWP_NOSIZE
| SWP_SHOWWINDOW
);
548 HANDLE filemap
, proc
;
549 PSID mapowner
, procowner
;
550 PSECURITY_DESCRIPTOR psd1
= NULL
, psd2
= NULL
;
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! */
560 debug(("mapname is :%s:\r\n", mapname
));
562 filemap
= OpenFileMapping(FILE_MAP_ALL_ACCESS
, FALSE
, mapname
);
564 debug(("filemap is %p\r\n", filemap
));
566 if (filemap
!= NULL
&& filemap
!= INVALID_HANDLE_VALUE
) {
569 if ((proc
= OpenProcess(MAXIMUM_ALLOWED
, FALSE
,
570 GetCurrentProcessId())) == NULL
) {
572 debug(("couldn't get handle for process\r\n"));
576 if (getsecurityinfo(proc
, SE_KERNEL_OBJECT
,
577 OWNER_SECURITY_INFORMATION
,
578 &procowner
, NULL
, NULL
, NULL
,
579 &psd2
) != ERROR_SUCCESS
) {
581 debug(("couldn't get owner info for process\r\n"));
584 return 0; /* unable to get security info */
587 if ((rc
= getsecurityinfo(filemap
, SE_KERNEL_OBJECT
,
588 OWNER_SECURITY_INFORMATION
,
589 &mapowner
, NULL
, NULL
, NULL
,
590 &psd1
) != ERROR_SUCCESS
)) {
592 debug(("couldn't get owner info for filemap: %d\r\n", rc
));
597 debug(("got security stuff\r\n"));
599 if (!EqualSid(mapowner
, procowner
))
600 return 0; /* security ID mismatch! */
602 debug(("security stuff matched\r\n"));
608 debug(("security APIs not present\r\n"));
611 p
= MapViewOfFile(filemap
, FILE_MAP_WRITE
, 0, 0, 0);
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
]));}
620 CloseHandle(filemap
);
625 return DefWindowProc (hwnd
, message
, wParam
, lParam
);
628 int WINAPI
WinMain(HINSTANCE inst
, HINSTANCE prev
, LPSTR cmdline
, int show
) {
635 * Determine whether we're an NT system (should have security
636 * APIs) or a non-NT system (don't do security).
638 memset(&osi
, 0, sizeof(OSVERSIONINFO
));
639 osi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
640 if (GetVersionEx(&osi
) && osi
.dwPlatformId
==VER_PLATFORM_WIN32_NT
) {
643 has_security
= FALSE
;
647 * Attempt to ge the security API we need.
649 advapi
= LoadLibrary("ADVAPI32.DLL");
650 getsecurityinfo
= (gsi_fn_t
)GetProcAddress(advapi
, "GetSecurityInfo");
651 if (!getsecurityinfo
) {
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
);
662 * First bomb out totally if we are already running.
664 if (FindWindow("Pageant", "Pageant")) {
665 MessageBox(NULL
, "Pageant is already running", "Pageant Error",
666 MB_ICONERROR
| MB_OK
);
667 if (advapi
) FreeLibrary(advapi
);
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
;
686 RegisterClass (&wndclass
);
689 hwnd
= keylist
= NULL
;
691 hwnd
= CreateWindow (APPNAME
, APPNAME
,
692 WS_OVERLAPPEDWINDOW
| WS_VSCROLL
,
693 CW_USEDEFAULT
, CW_USEDEFAULT
,
694 100, 100, NULL
, NULL
, inst
, NULL
);
696 /* Set up a system tray icon */
702 #ifdef NIM_SETVERSION
704 res
= Shell_NotifyIcon(NIM_SETVERSION
, &tnid
);
707 tnid
.cbSize
= sizeof(NOTIFYICONDATA
);
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)");
715 res
= Shell_NotifyIcon(NIM_ADD
, &tnid
);
720 systray_menu
= CreatePopupMenu();
721 AppendMenu (systray_menu
, MF_ENABLED
, IDM_VIEWKEYS
, "&View Keys");
722 AppendMenu (systray_menu
, MF_ENABLED
, IDM_CLOSE
, "E&xit");
725 ShowWindow (hwnd
, SW_HIDE
);
728 * Initialise storage for RSA keys.
730 rsakeys
= newtree234(cmpkeys
);
733 * Process the command line and add RSA keys as listed on it.
740 while (*p
&& isspace(*p
)) p
++;
741 if (*p
&& !isspace(*p
)) {
742 char *q
= p
, *pp
= p
;
743 while (*p
&& (inquotes
|| !isspace(*p
)))
746 inquotes
= !inquotes
;
764 while (GetMessage(&msg
, NULL
, 0, 0) == 1) {
765 TranslateMessage(&msg
);
766 DispatchMessage(&msg
);
769 /* Clean up the system tray icon */
773 tnid
.cbSize
= sizeof(NOTIFYICONDATA
);
777 Shell_NotifyIcon(NIM_DELETE
, &tnid
);
779 DestroyMenu(systray_menu
);
782 if (advapi
) FreeLibrary(advapi
);