Rework keylist_update() to fix both a buffer-size limitation and a
[u/mdw/putty] / windows / winpgnt.c
index 209c7c6..e220d6b 100644 (file)
@@ -8,6 +8,8 @@
 #include <assert.h>
 #include <tchar.h>
 
+#define PUTTY_DO_GLOBALS
+
 #include "putty.h"
 #include "ssh.h"
 #include "misc.h"
 
 #ifndef NO_SECURITY
 #include <aclapi.h>
+#ifdef DEBUG_IPC
+#define _WIN32_WINNT 0x0500            /* for ConvertSidToStringSid */
+#include <sddl.h>
+#endif
 #endif
 
 #define IDI_MAINICON 200
 #define IDI_TRAYICON 201
 
-#define WM_XUSER     (WM_USER + 0x2000)
-#define WM_SYSTRAY   (WM_XUSER + 6)
-#define WM_SYSTRAY2  (WM_XUSER + 7)
+#define WM_SYSTRAY   (WM_APP + 6)
+#define WM_SYSTRAY2  (WM_APP + 7)
 
 #define AGENT_COPYDATA_ID 0x804e50ba   /* random goop */
 
 
 extern char ver[];
 
-static HINSTANCE instance;
-static HWND main_hwnd;
 static HWND keylist;
 static HWND aboutbox;
 static HMENU systray_menu, session_menu;
 static int already_running;
-static int requested_help;
 
-char *help_path;
 static char *putty_path;
 
+/* CWD for "add key" file requester. */
+static filereq *keypath = NULL;
+
 #define IDM_PUTTY         0x0060
 #define IDM_SESSIONS_BASE 0x1000
 #define IDM_SESSIONS_MAX  0x2000
@@ -77,7 +81,7 @@ void modalfatalbox(char *fmt, ...)
     va_start(ap, fmt);
     buf = dupvprintf(fmt, ap);
     va_end(ap);
-    MessageBox(main_hwnd, buf, "Pageant Fatal Error",
+    MessageBox(hwnd, buf, "Pageant Fatal Error",
               MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
     sfree(buf);
     exit(1);
@@ -113,10 +117,10 @@ static tree234 *rsakeys, *ssh2keys;
 
 static int has_security;
 #ifndef NO_SECURITY
-typedef DWORD(WINAPI * gsi_fn_t)
- (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
-  PSID *, PSID *, PACL *, PACL *, PSECURITY_DESCRIPTOR *);
-static gsi_fn_t getsecurityinfo;
+DECL_WINDOWS_FUNCTION(extern, DWORD, GetSecurityInfo,
                    (HANDLE, SE_OBJECT_TYPE, SECURITY_INFORMATION,
+                      PSID *, PSID *, PACL *, PACL *,
+                      PSECURITY_DESCRIPTOR *));
 #endif
 
 /*
@@ -139,14 +143,14 @@ static void *get_keylist2(int *length);
  */
 int random_byte(void)
 {
-    MessageBox(main_hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
+    MessageBox(hwnd, "Internal Error", APPNAME, MB_OK | MB_ICONERROR);
     exit(0);
     /* this line can't be reached but it placates MSVC's warnings :-) */
     return 0;
 }
 
 /*
- * Blob structure for passing to the asymmetric SSH2 key compare
+ * Blob structure for passing to the asymmetric SSH-2 key compare
  * function, prototyped here.
  */
 struct blob {
@@ -155,22 +159,8 @@ struct blob {
 };
 static int cmpkeys_ssh2_asymm(void *av, void *bv);
 
-#define GET_32BIT(cp) \
-    (((unsigned long)(unsigned char)(cp)[0] << 24) | \
-    ((unsigned long)(unsigned char)(cp)[1] << 16) | \
-    ((unsigned long)(unsigned char)(cp)[2] << 8) | \
-    ((unsigned long)(unsigned char)(cp)[3]))
-
-#define PUT_32BIT(cp, value) { \
-    (cp)[0] = (unsigned char)((value) >> 24); \
-    (cp)[1] = (unsigned char)((value) >> 16); \
-    (cp)[2] = (unsigned char)((value) >> 8); \
-    (cp)[3] = (unsigned char)(value); }
-
-#define PASSPHRASE_MAXLEN 512
-
 struct PassphraseProcStruct {
-    char *passphrase;
+    char **passphrase;
     char *comment;
 };
 
@@ -184,7 +174,7 @@ static void forget_passphrases(void)
 {
     while (count234(passphrases) > 0) {
        char *pp = index234(passphrases, 0);
-       memset(pp, 0, strlen(pp));
+       smemclr(pp, strlen(pp));
        delpos234(passphrases, 0);
        free(pp);
     }
@@ -233,7 +223,7 @@ static int CALLBACK AboutProc(HWND hwnd, UINT msg,
            return 0;
          case 101:
            EnableWindow(hwnd, 0);
-           DialogBox(instance, MAKEINTRESOURCE(214), hwnd, LicenceProc);
+           DialogBox(hinst, MAKEINTRESOURCE(214), hwnd, LicenceProc);
            EnableWindow(hwnd, 1);
            SetActiveWindow(hwnd);
            return 0;
@@ -255,7 +245,7 @@ static HWND passphrase_box;
 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
                                   WPARAM wParam, LPARAM lParam)
 {
-    static char *passphrase = NULL;
+    static char **passphrase = NULL;
     struct PassphraseProcStruct *p;
 
     switch (msg) {
@@ -283,8 +273,9 @@ static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
        passphrase = p->passphrase;
        if (p->comment)
            SetDlgItemText(hwnd, 101, p->comment);
-       *passphrase = 0;
-       SetDlgItemText(hwnd, 102, passphrase);
+        burnstr(*passphrase);
+        *passphrase = dupstr("");
+       SetDlgItemText(hwnd, 102, *passphrase);
        return 0;
       case WM_COMMAND:
        switch (LOWORD(wParam)) {
@@ -299,9 +290,8 @@ static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
            return 0;
          case 102:                    /* edit box */
            if ((HIWORD(wParam) == EN_CHANGE) && passphrase) {
-               GetDlgItemText(hwnd, 102, passphrase,
-                              PASSPHRASE_MAXLEN - 1);
-               passphrase[PASSPHRASE_MAXLEN - 1] = '\0';
+                burnstr(*passphrase);
+                *passphrase = GetDlgItemText_alloc(hwnd, 102);
            }
            return 0;
        }
@@ -320,7 +310,7 @@ void old_keyfile_warning(void)
 {
     static const char mbtitle[] = "PuTTY Key File Warning";
     static const char message[] =
-       "You are loading an SSH 2 private key which has an\n"
+       "You are loading an SSH-2 private key which has an\n"
        "old version of the file format. This means your key\n"
        "file is not fully tamperproof. Future versions of\n"
        "PuTTY may stop supporting this private key format,\n"
@@ -363,28 +353,27 @@ static void keylist_update(void)
                               0, (LPARAM) listentry);
        }
        for (i = 0; NULL != (skey = index234(ssh2keys, i)); i++) {
-           char listentry[512], *p;
-           int len;
+           char *listentry, *p;
+           int fp_len;
            /*
             * Replace two spaces in the fingerprint with tabs, for
             * nice alignment in the box.
             */
            p = skey->alg->fingerprint(skey->data);
-           strncpy(listentry, p, sizeof(listentry));
+            listentry = dupprintf("%s\t%s", p, skey->comment);
+            fp_len = strlen(listentry);
+            sfree(p);
+
            p = strchr(listentry, ' ');
-           if (p)
+           if (p && p < listentry + fp_len)
                *p = '\t';
            p = strchr(listentry, ' ');
-           if (p)
+           if (p && p < listentry + fp_len)
                *p = '\t';
-           len = strlen(listentry);
-           if (len < sizeof(listentry) - 2) {
-               listentry[len] = '\t';
-               strncpy(listentry + len + 1, skey->comment,
-                       sizeof(listentry) - len - 1);
-           }
+
            SendDlgItemMessage(keylist, 100, LB_ADDSTRING, 0,
                               (LPARAM) listentry);
+            sfree(listentry);
        }
        SendDlgItemMessage(keylist, 100, LB_SETCURSEL, (WPARAM) - 1, 0);
     }
@@ -393,24 +382,26 @@ static void keylist_update(void)
 /*
  * This function loads a key from a file and adds it.
  */
-static void add_keyfile(Filename filename)
+static void add_keyfile(Filename *filename)
 {
-    char passphrase[PASSPHRASE_MAXLEN];
+    char *passphrase;
     struct RSAKey *rkey = NULL;
     struct ssh2_userkey *skey = NULL;
     int needs_pass;
     int ret;
     int attempts;
     char *comment;
-    struct PassphraseProcStruct pps;
+    const char *error = NULL;
     int type;
     int original_pass;
        
-    type = key_type(&filename);
+    type = key_type(filename);
     if (type != SSH_KEYTYPE_SSH1 && type != SSH_KEYTYPE_SSH2) {
-       char msg[256];
-       sprintf(msg, "Couldn't load this key (%s)", key_type_to_str(type));
-       MessageBox(NULL, msg, APPNAME, MB_OK | MB_ICONERROR);
+       char *msg = dupprintf("Couldn't load this key (%s)",
+                             key_type_to_str(type));
+       message_box(msg, APPNAME, MB_OK | MB_ICONERROR,
+                   HELPCTXID(errors_cantloadkey));
+       sfree(msg);
        return;
     }
 
@@ -424,18 +415,23 @@ static void add_keyfile(Filename filename)
        int i, nkeys, bloblen, keylistlen;
 
        if (type == SSH_KEYTYPE_SSH1) {
-           if (!rsakey_pubblob(&filename, &blob, &bloblen, NULL)) {
-               MessageBox(NULL, "Couldn't load private key.", APPNAME,
-                          MB_OK | MB_ICONERROR);
+           if (!rsakey_pubblob(filename, &blob, &bloblen, NULL, &error)) {
+               char *msg = dupprintf("Couldn't load private key (%s)", error);
+               message_box(msg, APPNAME, MB_OK | MB_ICONERROR,
+                           HELPCTXID(errors_cantloadkey));
+               sfree(msg);
                return;
            }
            keylist = get_keylist1(&keylistlen);
        } else {
            unsigned char *blob2;
-           blob = ssh2_userkey_loadpub(&filename, NULL, &bloblen, NULL);
+           blob = ssh2_userkey_loadpub(filename, NULL, &bloblen,
+                                       NULL, &error);
            if (!blob) {
-               MessageBox(NULL, "Couldn't load private key.", APPNAME,
-                          MB_OK | MB_ICONERROR);
+               char *msg = dupprintf("Couldn't load private key (%s)", error);
+               message_box(msg, APPNAME, MB_OK | MB_ICONERROR,
+                           HELPCTXID(errors_cantloadkey));
+               sfree(msg);
                return;
            }
            /* For our purposes we want the blob prefixed with its length */
@@ -453,7 +449,12 @@ static void add_keyfile(Filename filename)
                           MB_OK | MB_ICONERROR);
                return;
            }
-           nkeys = GET_32BIT(keylist);
+           nkeys = toint(GET_32BIT(keylist));
+           if (nkeys < 0) {
+               MessageBox(NULL, "Received broken key list?!", APPNAME,
+                          MB_OK | MB_ICONERROR);
+               return;
+           }
            p = keylist + 4;
            keylistlen -= 4;
 
@@ -481,8 +482,8 @@ static void add_keyfile(Filename filename)
                                   MB_OK | MB_ICONERROR);
                        return;
                    }
-                   n = 4 + GET_32BIT(p);
-                   if (keylistlen < n) {
+                   n = toint(4 + GET_32BIT(p));
+                   if (n < 0 || keylistlen < n) {
                        MessageBox(NULL, "Received broken key list?!", APPNAME,
                                   MB_OK | MB_ICONERROR);
                        return;
@@ -498,8 +499,8 @@ static void add_keyfile(Filename filename)
                                   MB_OK | MB_ICONERROR);
                        return;
                    }
-                   n = 4 + GET_32BIT(p);
-                   if (keylistlen < n) {
+                   n = toint(4 + GET_32BIT(p));
+                   if (n < 0 || keylistlen < n) {
                        MessageBox(NULL, "Received broken key list?!", APPNAME,
                                   MB_OK | MB_ICONERROR);
                        return;
@@ -515,27 +516,35 @@ static void add_keyfile(Filename filename)
        sfree(blob);
     }
 
+    error = NULL;
     if (type == SSH_KEYTYPE_SSH1)
-       needs_pass = rsakey_encrypted(&filename, &comment);
+       needs_pass = rsakey_encrypted(filename, &comment);
     else
-       needs_pass = ssh2_userkey_encrypted(&filename, &comment);
+       needs_pass = ssh2_userkey_encrypted(filename, &comment);
     attempts = 0;
     if (type == SSH_KEYTYPE_SSH1)
        rkey = snew(struct RSAKey);
-    pps.passphrase = passphrase;
-    pps.comment = comment;
+    passphrase = NULL;
     original_pass = 0;
     do {
+        burnstr(passphrase);
+        passphrase = NULL;
+
        if (needs_pass) {
            /* try all the remembered passphrases first */
            char *pp = index234(passphrases, attempts);
            if(pp) {
-               strcpy(passphrase, pp);
+               passphrase = dupstr(pp);
            } else {
                int dlgret;
+                struct PassphraseProcStruct pps;
+
+                pps.passphrase = &passphrase;
+                pps.comment = comment;
+
                original_pass = 1;
-               dlgret = DialogBoxParam(instance, MAKEINTRESOURCE(210),
-                                       NULL, PassphraseProc, (LPARAM) & pps);
+               dlgret = DialogBoxParam(hinst, MAKEINTRESOURCE(210),
+                                       NULL, PassphraseProc, (LPARAM) &pps);
                passphrase_box = NULL;
                if (!dlgret) {
                    if (comment)
@@ -544,13 +553,16 @@ static void add_keyfile(Filename filename)
                        sfree(rkey);
                    return;                    /* operation cancelled */
                }
+
+                assert(passphrase != NULL);
            }
        } else
-           *passphrase = '\0';
+           passphrase = dupstr("");
+
        if (type == SSH_KEYTYPE_SSH1)
-           ret = loadrsakey(&filename, rkey, passphrase, NULL);
+           ret = loadrsakey(filename, rkey, passphrase, &error);
        else {
-           skey = ssh2_load_userkey(&filename, passphrase, NULL);
+           skey = ssh2_load_userkey(filename, passphrase, &error);
            if (skey == SSH2_WRONG_PASSPHRASE)
                ret = -1;
            else if (!skey)
@@ -561,17 +573,22 @@ static void add_keyfile(Filename filename)
        attempts++;
     } while (ret == -1);
 
-    /* if they typed in an ok passphrase, remember it */
     if(original_pass && ret) {
-       char *pp = dupstr(passphrase);
-       addpos234(passphrases, pp, 0);
+        /* If they typed in an ok passphrase, remember it */
+       addpos234(passphrases, passphrase, 0);
+    } else {
+        /* Otherwise, destroy it */
+        burnstr(passphrase);
     }
+    passphrase = NULL;
 
     if (comment)
        sfree(comment);
     if (ret == 0) {
-       MessageBox(NULL, "Couldn't load private key.", APPNAME,
-                  MB_OK | MB_ICONERROR);
+       char *msg = dupprintf("Couldn't load private key (%s)", error);
+       message_box(msg, APPNAME, MB_OK | MB_ICONERROR,
+                   HELPCTXID(errors_cantloadkey));
+       sfree(msg);
        if (type == SSH_KEYTYPE_SSH1)
            sfree(rkey);
        return;
@@ -681,7 +698,7 @@ static void add_keyfile(Filename filename)
 }
 
 /*
- * Create an SSH1 key list in a malloc'ed buffer; return its
+ * Create an SSH-1 key list in a malloc'ed buffer; return its
  * length.
  */
 static void *make_keylist1(int *length)
@@ -725,7 +742,7 @@ static void *make_keylist1(int *length)
 }
 
 /*
- * Create an SSH2 key list in a malloc'ed buffer; return its
+ * Create an SSH-2 key list in a malloc'ed buffer; return its
  * length.
  */
 static void *make_keylist2(int *length)
@@ -955,7 +972,7 @@ static void answer_msg(void *msg)
            MD5Init(&md5c);
            MD5Update(&md5c, response_source, 48);
            MD5Final(response_md5, &md5c);
-           memset(response_source, 0, 48);     /* burn the evidence */
+           smemclr(response_source, 48);       /* burn the evidence */
            freebn(response);          /* and that evidence */
            freebn(challenge);         /* yes, and that evidence */
            freebn(reqkey.exponent);   /* and free some memory ... */
@@ -985,17 +1002,17 @@ static void answer_msg(void *msg)
 
            if (msgend < p+4)
                goto failure;
-           b.len = GET_32BIT(p);
+           b.len = toint(GET_32BIT(p));
+            if (b.len < 0 || b.len > msgend - (p+4))
+                goto failure;
            p += 4;
-           if (msgend < p+b.len)
-               goto failure;
            b.blob = p;
            p += b.len;
            if (msgend < p+4)
                goto failure;
-           datalen = GET_32BIT(p);
+           datalen = toint(GET_32BIT(p));
            p += 4;
-           if (msgend < p+datalen)
+           if (datalen < 0 || datalen > msgend - p)
                goto failure;
            data = p;
            key = find234(ssh2keys, &b, cmpkeys_ssh2_asymm);
@@ -1068,9 +1085,9 @@ static void answer_msg(void *msg)
                sfree(key);
                goto failure;
            }
-            commentlen = GET_32BIT(p);
+            commentlen = toint(GET_32BIT(p));
 
-           if (msgend < p+commentlen) {
+           if (commentlen < 0 || commentlen > msgend - p) {
                freersakey(key);
                sfree(key);
                goto failure;
@@ -1107,9 +1124,9 @@ static void answer_msg(void *msg)
 
            if (msgend < p+4)
                goto failure;
-           alglen = GET_32BIT(p);
+           alglen = toint(GET_32BIT(p));
            p += 4;
-           if (msgend < p+alglen)
+           if (alglen < 0 || alglen > msgend - p)
                goto failure;
            alg = p;
            p += alglen;
@@ -1143,10 +1160,10 @@ static void answer_msg(void *msg)
                sfree(key);
                goto failure;
            }
-           commlen = GET_32BIT(p);
+           commlen = toint(GET_32BIT(p));
            p += 4;
 
-           if (msgend < p+commlen) {
+           if (commlen < 0 || commlen > msgend - p) {
                key->alg->freekey(key->data);
                sfree(key);
                goto failure;
@@ -1210,10 +1227,10 @@ static void answer_msg(void *msg)
 
            if (msgend < p+4)
                goto failure;
-           b.len = GET_32BIT(p);
+           b.len = toint(GET_32BIT(p));
            p += 4;
 
-           if (msgend < p+b.len)
+           if (b.len < 0 || b.len > msgend - p)
                goto failure;
            b.blob = p;
            p += b.len;
@@ -1235,7 +1252,7 @@ static void answer_msg(void *msg)
        break;
       case SSH1_AGENTC_REMOVE_ALL_RSA_IDENTITIES:
        /*
-        * Remove all SSH1 keys. Always returns success.
+        * Remove all SSH-1 keys. Always returns success.
         */
        {
            struct RSAKey *rkey;
@@ -1253,7 +1270,7 @@ static void answer_msg(void *msg)
        break;
       case SSH2_AGENTC_REMOVE_ALL_IDENTITIES:
        /*
-        * Remove all SSH2 keys. Always returns success.
+        * Remove all SSH-2 keys. Always returns success.
         */
        {
            struct ssh2_userkey *skey;
@@ -1321,7 +1338,7 @@ static int cmpkeys_rsa(void *av, void *bv)
 }
 
 /*
- * Key comparison function for the 2-3-4 tree of SSH2 keys.
+ * Key comparison function for the 2-3-4 tree of SSH-2 keys.
  */
 static int cmpkeys_ssh2(void *av, void *bv)
 {
@@ -1361,7 +1378,7 @@ static int cmpkeys_ssh2(void *av, void *bv)
 
 /*
  * Key comparison function for looking up a blob in the 2-3-4 tree
- * of SSH2 keys.
+ * of SSH-2 keys.
  */
 static int cmpkeys_ssh2_asymm(void *av, void *bv)
 {
@@ -1405,30 +1422,21 @@ static int cmpkeys_ssh2_asymm(void *av, void *bv)
 static void prompt_add_keyfile(void)
 {
     OPENFILENAME of;
-    char filename[FILENAME_MAX];
     char *filelist = snewn(8192, char);
-    char *filewalker;
-    int n, dirlen;
        
+    if (!keypath) keypath = filereq_new();
     memset(&of, 0, sizeof(of));
-#ifdef OPENFILENAME_SIZE_VERSION_400
-    of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
-#else
-    of.lStructSize = sizeof(of);
-#endif
-    of.hwndOwner = main_hwnd;
-    of.lpstrFilter = "PuTTY Private Key Files (*.ppk)\0*.ppk\0"
-       "All Files (*.*)\0*\0\0\0";
+    of.hwndOwner = hwnd;
+    of.lpstrFilter = FILTER_KEY_FILES;
     of.lpstrCustomFilter = NULL;
     of.nFilterIndex = 1;
     of.lpstrFile = filelist;
     *filelist = '\0';
-    of.nMaxFile = FILENAME_MAX;
+    of.nMaxFile = 8192;
     of.lpstrFileTitle = NULL;
-    of.lpstrInitialDir = NULL;
     of.lpstrTitle = "Select Private Key File";
     of.Flags = OFN_ALLOWMULTISELECT | OFN_EXPLORER;
-    if (GetOpenFileName(&of)) {
+    if (request_file(keypath, &of, TRUE, FALSE)) {
        if(strlen(filelist) > of.nFileOffset)
            /* Only one filename returned? */
            add_keyfile(filename_from_str(filelist));
@@ -1438,28 +1446,13 @@ static void prompt_add_keyfile(void)
             * rest the filenames. terminated with an
             * empty string.
             */
-           filewalker = filelist;
-           dirlen = strlen(filewalker);
-           if(dirlen > FILENAME_MAX - 8) return;
-           memcpy(filename, filewalker, dirlen);
-
-           filewalker += dirlen + 1;
-           filename[dirlen++] = '\\';
-
-           /* then go over names one by one */
-           for(;;) {
-               n = strlen(filewalker) + 1;
-               /* end of the list */
-               if(n == 1)
-                   break;
-               /* too big, shouldn't happen */
-               if(n + dirlen > FILENAME_MAX)
-                   break;
-
-               memcpy(filename + dirlen, filewalker, n);
-               filewalker += n;
-
+           char *dir = filelist;
+           char *filewalker = filelist + strlen(dir) + 1;
+           while (*filewalker != '\0') {
+               char *filename = dupcat(dir, "\\", filewalker, NULL);
                add_keyfile(filename_from_str(filename));
+               sfree(filename);
+               filewalker += strlen(filewalker) + 1;
            }
        }
 
@@ -1495,15 +1488,15 @@ static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
                           rd.right - rd.left, rd.bottom - rd.top, TRUE);
        }
 
-        if (help_path)
-            SetWindowLong(hwnd, GWL_EXSTYLE,
-                          GetWindowLong(hwnd, GWL_EXSTYLE) | WS_EX_CONTEXTHELP);
+        if (has_help())
+            SetWindowLongPtr(hwnd, GWL_EXSTYLE,
+                            GetWindowLongPtr(hwnd, GWL_EXSTYLE) |
+                            WS_EX_CONTEXTHELP);
         else {
             HWND item = GetDlgItem(hwnd, 103);   /* the Help button */
             if (item)
                 DestroyWindow(item);
         }
-        requested_help = FALSE;
 
        keylist = hwnd;
        {
@@ -1596,27 +1589,22 @@ static int CALLBACK KeyListProc(HWND hwnd, UINT msg,
          case 103:                    /* help */
             if (HIWORD(wParam) == BN_CLICKED ||
                 HIWORD(wParam) == BN_DOUBLECLICKED) {
-                if (help_path) {
-                    WinHelp(main_hwnd, help_path, HELP_COMMAND,
-                            (DWORD)"JI(`',`pageant.general')");
-                    requested_help = TRUE;
-                }
+               launch_help(hwnd, WINHELP_CTX_pageant_general);
             }
            return 0;
        }
        return 0;
       case WM_HELP:
-        if (help_path) {
+        {
             int id = ((LPHELPINFO)lParam)->iCtrlId;
-            char *cmd = NULL;
+            char *topic = NULL;
             switch (id) {
-              case 100: cmd = "JI(`',`pageant.keylist')"; break;
-              case 101: cmd = "JI(`',`pageant.addkey')"; break;
-              case 102: cmd = "JI(`',`pageant.remkey')"; break;
+              case 100: topic = WINHELP_CTX_pageant_keylist; break;
+              case 101: topic = WINHELP_CTX_pageant_addkey; break;
+              case 102: topic = WINHELP_CTX_pageant_remkey; break;
             }
-            if (cmd) {
-                WinHelp(main_hwnd, help_path, HELP_COMMAND, (DWORD)cmd);
-                requested_help = TRUE;
+            if (topic) {
+               launch_help(hwnd, topic);
             } else {
                 MessageBeep(0);
             }
@@ -1647,7 +1635,7 @@ static BOOL AddTrayIcon(HWND hwnd)
     tnid.uID = 1;             /* unique within this systray use */
     tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
     tnid.uCallbackMessage = WM_SYSTRAY;
-    tnid.hIcon = hicon = LoadIcon(instance, MAKEINTRESOURCE(201));
+    tnid.hIcon = hicon = LoadIcon(hinst, MAKEINTRESOURCE(201));
     strcpy(tnid.szTip, "Pageant (PuTTY authentication agent)");
 
     res = Shell_NotifyIcon(NIM_ADD, &tnid);
@@ -1710,6 +1698,53 @@ static void update_sessions(void)
     }
 }
 
+#ifndef NO_SECURITY
+/*
+ * Versions of Pageant prior to 0.61 expected this SID on incoming
+ * communications. For backwards compatibility, and more particularly
+ * for compatibility with derived works of PuTTY still using the old
+ * Pageant client code, we accept it as an alternative to the one
+ * returned from get_user_sid() in winpgntc.c.
+ */
+PSID get_default_sid(void)
+{
+    HANDLE proc = NULL;
+    DWORD sidlen;
+    PSECURITY_DESCRIPTOR psd = NULL;
+    PSID sid = NULL, copy = NULL, ret = NULL;
+
+    if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
+                            GetCurrentProcessId())) == NULL)
+        goto cleanup;
+
+    if (p_GetSecurityInfo(proc, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION,
+                          &sid, NULL, NULL, NULL, &psd) != ERROR_SUCCESS)
+        goto cleanup;
+
+    sidlen = GetLengthSid(sid);
+
+    copy = (PSID)smalloc(sidlen);
+
+    if (!CopySid(sidlen, copy, sid))
+        goto cleanup;
+
+    /* Success. Move sid into the return value slot, and null it out
+     * to stop the cleanup code freeing it. */
+    ret = copy;
+    copy = NULL;
+
+  cleanup:
+    if (proc != NULL)
+        CloseHandle(proc);
+    if (psd != NULL)
+        LocalFree(psd);
+    if (copy != NULL)
+        sfree(copy);
+
+    return ret;
+}
+#endif
+
 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
                                WPARAM wParam, LPARAM lParam)
 {
@@ -1772,7 +1807,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
            break;
          case IDM_VIEWKEYS:
            if (!keylist) {
-               keylist = CreateDialog(instance, MAKEINTRESOURCE(211),
+               keylist = CreateDialog(hinst, MAKEINTRESOURCE(211),
                                       NULL, KeyListProc);
                ShowWindow(keylist, SW_SHOWNORMAL);
            }
@@ -1797,7 +1832,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
            break;
          case IDM_ABOUT:
            if (!aboutbox) {
-               aboutbox = CreateDialog(instance, MAKEINTRESOURCE(213),
+               aboutbox = CreateDialog(hinst, MAKEINTRESOURCE(213),
                                        NULL, AboutProc);
                ShowWindow(aboutbox, SW_SHOWNORMAL);
                /* 
@@ -1810,11 +1845,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
            }
            break;
          case IDM_HELP:
-            if (help_path) {
-                WinHelp(main_hwnd, help_path, HELP_COMMAND,
-                        (DWORD)"JI(`',`pageant.general')");
-                requested_help = TRUE;
-            }
+           launch_help(hwnd, WINHELP_CTX_pageant_general);
            break;
          default:
            {
@@ -1841,10 +1872,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
        }
        break;
       case WM_DESTROY:
-        if (requested_help) {
-            WinHelp(main_hwnd, help_path, HELP_QUIT, 0);
-            requested_help = FALSE;
-        }
+       quit_help(hwnd);
        PostQuitMessage(0);
        return 0;
       case WM_COPYDATA:
@@ -1854,10 +1882,9 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
            void *p;
            HANDLE filemap;
 #ifndef NO_SECURITY
-           HANDLE proc;
-           PSID mapowner, procowner;
-           PSECURITY_DESCRIPTOR psd1 = NULL, psd2 = NULL;
+           PSID mapowner, ourself, ourself2;
 #endif
+            PSECURITY_DESCRIPTOR psd = NULL;
            int ret = 0;
 
            cds = (COPYDATASTRUCT *) lParam;
@@ -1877,46 +1904,54 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
 #ifndef NO_SECURITY
                int rc;
                if (has_security) {
-                   if ((proc = OpenProcess(MAXIMUM_ALLOWED, FALSE,
-                                           GetCurrentProcessId())) ==
-                       NULL) {
+                    if ((ourself = get_user_sid()) == NULL) {
 #ifdef DEBUG_IPC
-                       debug(("couldn't get handle for process\n"));
+                       debug(("couldn't get user SID\n"));
 #endif
                        return 0;
-                   }
-                   if (getsecurityinfo(proc, SE_KERNEL_OBJECT,
-                                       OWNER_SECURITY_INFORMATION,
-                                       &procowner, NULL, NULL, NULL,
-                                       &psd2) != ERROR_SUCCESS) {
+                    }
+
+                    if ((ourself2 = get_default_sid()) == NULL) {
 #ifdef DEBUG_IPC
-                       debug(("couldn't get owner info for process\n"));
+                       debug(("couldn't get default SID\n"));
 #endif
-                       CloseHandle(proc);
-                       return 0;      /* unable to get security info */
-                   }
-                   CloseHandle(proc);
-                   if ((rc = getsecurityinfo(filemap, SE_KERNEL_OBJECT,
-                                             OWNER_SECURITY_INFORMATION,
-                                             &mapowner, NULL, NULL, NULL,
-                                             &psd1) != ERROR_SUCCESS)) {
+                       return 0;
+                    }
+
+                   if ((rc = p_GetSecurityInfo(filemap, SE_KERNEL_OBJECT,
+                                               OWNER_SECURITY_INFORMATION,
+                                               &mapowner, NULL, NULL, NULL,
+                                               &psd) != ERROR_SUCCESS)) {
 #ifdef DEBUG_IPC
-                       debug(
-                             ("couldn't get owner info for filemap: %d\n",
-                              rc));
+                       debug(("couldn't get owner info for filemap: %d\n",
+                               rc));
 #endif
                        return 0;
                    }
 #ifdef DEBUG_IPC
-                   debug(("got security stuff\n"));
+                    {
+                        LPTSTR ours, ours2, theirs;
+                        ConvertSidToStringSid(mapowner, &theirs);
+                        ConvertSidToStringSid(ourself, &ours);
+                        ConvertSidToStringSid(ourself2, &ours2);
+                        debug(("got sids:\n  oursnew=%s\n  oursold=%s\n"
+                               "  theirs=%s\n", ours, ours2, theirs));
+                        LocalFree(ours);
+                        LocalFree(ours2);
+                        LocalFree(theirs);
+                    }
 #endif
-                   if (!EqualSid(mapowner, procowner))
+                   if (!EqualSid(mapowner, ourself) &&
+                        !EqualSid(mapowner, ourself2)) {
+                        CloseHandle(filemap);
                        return 0;      /* security ID mismatch! */
+                    }
 #ifdef DEBUG_IPC
                    debug(("security stuff matched\n"));
 #endif
-                   LocalFree(psd1);
-                   LocalFree(psd2);
+                    LocalFree(psd);
+                    sfree(ourself);
+                    sfree(ourself2);
                } else {
 #ifdef DEBUG_IPC
                    debug(("security APIs not present\n"));
@@ -1929,9 +1964,9 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
                {
                    int i;
                    for (i = 0; i < 5; i++)
-                       debug(
-                             ("p[%d]=%02x\n", i,
-                              ((unsigned char *) p)[i]));}
+                       debug(("p[%d]=%02x\n", i,
+                              ((unsigned char *) p)[i]));
+                }
 #endif
                answer_msg(p);
                ret = 1;
@@ -1970,7 +2005,11 @@ void agent_schedule_callback(void (*callback)(void *, void *, int),
     assert(!"We shouldn't get here");
 }
 
-void cleanup_exit(int code) { exit(code); }
+void cleanup_exit(int code)
+{
+    shutdown_help();
+    exit(code);
+}
 
 int flags = FLAG_SYNCAGENT;
 
@@ -1984,6 +2023,9 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
     int argc, i;
     char **argv, **argstart;
 
+    hinst = inst;
+    hwnd = NULL;
+
     /*
      * Determine whether we're an NT system (should have security
      * APIs) or a non-NT system (don't do security).
@@ -2002,10 +2044,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
        /*
         * Attempt to get the security API we need.
         */
-       advapi = LoadLibrary("ADVAPI32.DLL");
-       getsecurityinfo =
-           (gsi_fn_t) GetProcAddress(advapi, "GetSecurityInfo");
-       if (!getsecurityinfo) {
+        if (!init_advapi()) {
            MessageBox(NULL,
                       "Unable to access security APIs. Pageant will\n"
                       "not run, in case it causes a security breach.",
@@ -2022,27 +2061,10 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
     } else
        advapi = NULL;
 
-    instance = inst;
-
     /*
      * See if we can find our Help file.
      */
-    {
-        char b[2048], *p, *q, *r;
-        FILE *fp;
-        GetModuleFileName(NULL, b, sizeof(b) - 1);
-        r = b;
-        p = strrchr(b, '\\');
-        if (p && p >= r) r = p+1;
-        q = strrchr(b, ':');
-        if (q && q >= r) r = q+1;
-        strcpy(r, "putty.hlp");
-        if ( (fp = fopen(b, "r")) != NULL) {
-            help_path = dupstr(b);
-            fclose(fp);
-        } else
-            help_path = NULL;
-    }
+    init_help();
 
     /*
      * Look for the PuTTY binary (we will enable the saved session
@@ -2051,7 +2073,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
     {
         char b[2048], *p, *q, *r;
         FILE *fp;
-        GetModuleFileName(NULL, b, sizeof(b) - 1);
+        GetModuleFileName(NULL, b, sizeof(b) - 16);
         r = b;
         p = strrchr(b, '\\');
         if (p && p >= r) r = p+1;
@@ -2068,67 +2090,14 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
     /*
      * Find out if Pageant is already running.
      */
-    already_running = FALSE;
-    if (agent_exists())
-       already_running = TRUE;
-    else {
-
-       if (!prev) {
-           wndclass.style = 0;
-           wndclass.lpfnWndProc = WndProc;
-           wndclass.cbClsExtra = 0;
-           wndclass.cbWndExtra = 0;
-           wndclass.hInstance = inst;
-           wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
-           wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
-           wndclass.hbrBackground = GetStockObject(BLACK_BRUSH);
-           wndclass.lpszMenuName = NULL;
-           wndclass.lpszClassName = APPNAME;
-
-           RegisterClass(&wndclass);
-       }
-
-       main_hwnd = keylist = NULL;
-
-       main_hwnd = CreateWindow(APPNAME, APPNAME,
-                                 WS_OVERLAPPEDWINDOW | WS_VSCROLL,
-                                 CW_USEDEFAULT, CW_USEDEFAULT,
-                                 100, 100, NULL, NULL, inst, NULL);
-
-       /* Set up a system tray icon */
-       AddTrayIcon(main_hwnd);
+    already_running = agent_exists();
 
-        /* Accelerators used: nsvkxa */
-        systray_menu = CreatePopupMenu();
-       if (putty_path) {
-           session_menu = CreateMenu();
-           AppendMenu(systray_menu, MF_ENABLED, IDM_PUTTY, "&New Session");
-           AppendMenu(systray_menu, MF_POPUP | MF_ENABLED,
-                      (UINT) session_menu, "&Saved Sessions");
-           AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
-       }
-        AppendMenu(systray_menu, MF_ENABLED, IDM_VIEWKEYS,
-               "&View Keys");
-        AppendMenu(systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key");
-       AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
-        if (help_path)
-            AppendMenu(systray_menu, MF_ENABLED, IDM_HELP, "&Help");
-        AppendMenu(systray_menu, MF_ENABLED, IDM_ABOUT, "&About");
-       AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
-        AppendMenu(systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
-       initial_menuitems_count = GetMenuItemCount(session_menu);
-
-       /* Set the default menu item. */
-       SetMenuDefaultItem(systray_menu, IDM_VIEWKEYS, FALSE);
-
-       ShowWindow(main_hwnd, SW_HIDE);
-
-       /*
-        * Initialise storage for RSA keys.
-        */
+    /*
+     * Initialise storage for RSA keys.
+     */
+    if (!already_running) {
        rsakeys = newtree234(cmpkeys_rsa);
        ssh2keys = newtree234(cmpkeys_ssh2);
-
     }
 
     /*
@@ -2141,7 +2110,12 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
      */
     split_into_argv(cmdline, &argc, &argv, &argstart);
     for (i = 0; i < argc; i++) {
-       if (!strcmp(argv[i], "-c")) {
+       if (!strcmp(argv[i], "-pgpfp")) {
+           pgp_fingerprints();
+           if (advapi)
+               FreeLibrary(advapi);
+           return 1;
+       } else if (!strcmp(argv[i], "-c")) {
            /*
             * If we see `-c', then the rest of the
             * command line should be treated as a
@@ -2192,6 +2166,56 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
        return 0;
     }
 
+    if (!prev) {
+       wndclass.style = 0;
+       wndclass.lpfnWndProc = WndProc;
+       wndclass.cbClsExtra = 0;
+       wndclass.cbWndExtra = 0;
+       wndclass.hInstance = inst;
+       wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
+       wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
+       wndclass.hbrBackground = GetStockObject(BLACK_BRUSH);
+       wndclass.lpszMenuName = NULL;
+       wndclass.lpszClassName = APPNAME;
+
+       RegisterClass(&wndclass);
+    }
+
+    keylist = NULL;
+
+    hwnd = CreateWindow(APPNAME, APPNAME,
+                       WS_OVERLAPPEDWINDOW | WS_VSCROLL,
+                       CW_USEDEFAULT, CW_USEDEFAULT,
+                       100, 100, NULL, NULL, inst, NULL);
+
+    /* Set up a system tray icon */
+    AddTrayIcon(hwnd);
+
+    /* Accelerators used: nsvkxa */
+    systray_menu = CreatePopupMenu();
+    if (putty_path) {
+       session_menu = CreateMenu();
+       AppendMenu(systray_menu, MF_ENABLED, IDM_PUTTY, "&New Session");
+       AppendMenu(systray_menu, MF_POPUP | MF_ENABLED,
+                  (UINT) session_menu, "&Saved Sessions");
+       AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
+    }
+    AppendMenu(systray_menu, MF_ENABLED, IDM_VIEWKEYS,
+          "&View Keys");
+    AppendMenu(systray_menu, MF_ENABLED, IDM_ADDKEY, "Add &Key");
+    AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
+    if (has_help())
+       AppendMenu(systray_menu, MF_ENABLED, IDM_HELP, "&Help");
+    AppendMenu(systray_menu, MF_ENABLED, IDM_ABOUT, "&About");
+    AppendMenu(systray_menu, MF_SEPARATOR, 0, 0);
+    AppendMenu(systray_menu, MF_ENABLED, IDM_CLOSE, "E&xit");
+    initial_menuitems_count = GetMenuItemCount(session_menu);
+
+    /* Set the default menu item. */
+    SetMenuDefaultItem(systray_menu, IDM_VIEWKEYS, FALSE);
+
+    ShowWindow(hwnd, SW_HIDE);
+
     /*
      * Main message loop.
      */
@@ -2208,7 +2232,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
        NOTIFYICONDATA tnid;
 
        tnid.cbSize = sizeof(NOTIFYICONDATA);
-       tnid.hWnd = main_hwnd;
+       tnid.hWnd = hwnd;
        tnid.uID = 1;
 
        Shell_NotifyIcon(NIM_DELETE, &tnid);
@@ -2216,7 +2240,11 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
        DestroyMenu(systray_menu);
     }
 
+    if (keypath) filereq_free(keypath);
+
     if (advapi)
        FreeLibrary(advapi);
-    return msg.wParam;
+
+    cleanup_exit(msg.wParam);
+    return msg.wParam;                /* just in case optimiser complains */
 }