]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - puttygen.c
Preliminary support for RSA user authentication in SSH2! Most of the
[PuTTY.git] / puttygen.c
1 /*
2  * PuTTY key generation front end.
3  */
4
5 #include <windows.h>
6 #include <commctrl.h>
7 #include <time.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 #define PUTTY_DO_GLOBALS
12
13 #include "putty.h"
14 #include "ssh.h"
15 #include "winstuff.h"
16
17 #define WM_DONEKEY (WM_XUSER + 1)
18
19 #define DEFAULT_KEYSIZE 1024
20
21 /* ----------------------------------------------------------------------
22  * Progress report code. This is really horrible :-)
23  */
24 #define PHASE1TOTAL 0x10000
25 #define PHASE2TOTAL 0x10000
26 #define PHASE3TOTAL 0x04000
27 #define PHASE1START 0
28 #define PHASE2START (PHASE1TOTAL)
29 #define PHASE3START (PHASE1TOTAL + PHASE2TOTAL)
30 #define TOTALTOTAL  (PHASE1TOTAL + PHASE2TOTAL + PHASE3TOTAL)
31 #define PROGRESSBIGRANGE 65535
32 #define DIVISOR     ((TOTALTOTAL + PROGRESSBIGRANGE - 1) / PROGRESSBIGRANGE)
33 #define PROGRESSRANGE (TOTALTOTAL / DIVISOR)
34 struct progress {
35     unsigned phase1param, phase1current, phase1n;
36     unsigned phase2param, phase2current, phase2n;
37     unsigned phase3mult;
38     HWND progbar;
39 };
40
41 static void progress_update(void *param, int phase, int iprogress) {
42     struct progress *p = (struct progress *)param;
43     unsigned progress = iprogress;
44     int position;
45
46     switch (phase) {
47       case -1:
48         p->phase1param = 0x10000 + progress;
49         p->phase1current = 0x10000; p->phase1n = 0;
50         return;
51       case -2:
52         p->phase2param = 0x10000 + progress;
53         p->phase2current = 0x10000; p->phase2n = 0;
54         return;
55       case -3:
56         p->phase3mult = PHASE3TOTAL / progress;
57         return;
58       case 1:
59         while (p->phase1n < progress) {
60             p->phase1n++;
61             p->phase1current *= p->phase1param;
62             p->phase1current /= 0x10000;
63         }
64         position = PHASE1START + 0x10000 - p->phase1current;
65         break;
66       case 2:
67         while (p->phase2n < progress) {
68             p->phase2n++;
69             p->phase2current *= p->phase2param;
70             p->phase2current /= 0x10000;
71         }
72         position = PHASE2START + 0x10000 - p->phase2current;
73         break;
74       case 3:
75         position = PHASE3START + progress * p->phase3mult;
76         break;
77     }
78
79     SendMessage(p->progbar, PBM_SETPOS, position / DIVISOR, 0);
80 }
81
82 extern char ver[];
83
84 #define PASSPHRASE_MAXLEN 512
85
86 struct PassphraseProcStruct {
87     char *passphrase;
88     char *comment;
89 };
90
91 /*
92  * Dialog-box function for the passphrase box.
93  */
94 static int CALLBACK PassphraseProc(HWND hwnd, UINT msg,
95                                    WPARAM wParam, LPARAM lParam) {
96     static char *passphrase;
97     struct PassphraseProcStruct *p;
98
99     switch (msg) {
100       case WM_INITDIALOG:
101         SetForegroundWindow(hwnd);
102         SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
103                       SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);
104
105         /*
106          * Centre the window.
107          */
108         {                              /* centre the window */
109             RECT rs, rd;
110             HWND hw;
111
112             hw = GetDesktopWindow();
113             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
114                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
115                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
116                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
117         }
118
119         p = (struct PassphraseProcStruct *)lParam;
120         passphrase = p->passphrase;
121         if (p->comment)
122             SetDlgItemText(hwnd, 101, p->comment);
123         *passphrase = 0;
124         return 0;
125       case WM_COMMAND:
126         switch (LOWORD(wParam)) {
127           case IDOK:
128             if (*passphrase)
129                 EndDialog (hwnd, 1);
130             else
131                 MessageBeep (0);
132             return 0;
133           case IDCANCEL:
134             EndDialog (hwnd, 0);
135             return 0;
136           case 102:                    /* edit box */
137             if (HIWORD(wParam) == EN_CHANGE) {
138                 GetDlgItemText (hwnd, 102, passphrase, PASSPHRASE_MAXLEN-1);
139                 passphrase[PASSPHRASE_MAXLEN-1] = '\0';
140             }
141             return 0;
142         }
143         return 0;
144       case WM_CLOSE:
145         EndDialog (hwnd, 0);
146         return 0;
147     }
148     return 0;
149 }
150
151 /*
152  * Prompt for a key file. Assumes the filename buffer is of size
153  * FILENAME_MAX.
154  */
155 static int prompt_keyfile(HWND hwnd, char *dlgtitle,
156                           char *filename, int save) {
157     OPENFILENAME of;
158     memset(&of, 0, sizeof(of));
159 #ifdef OPENFILENAME_SIZE_VERSION_400
160     of.lStructSize = OPENFILENAME_SIZE_VERSION_400;
161 #else
162     of.lStructSize = sizeof(of);
163 #endif
164     of.hwndOwner = hwnd;
165     of.lpstrFilter = "All Files\0*\0\0\0";
166     of.lpstrCustomFilter = NULL;
167     of.nFilterIndex = 1;
168     of.lpstrFile = filename; *filename = '\0';
169     of.nMaxFile = FILENAME_MAX;
170     of.lpstrFileTitle = NULL;
171     of.lpstrInitialDir = NULL;
172     of.lpstrTitle = dlgtitle;
173     of.Flags = 0;
174     if (save)
175         return GetSaveFileName(&of);
176     else
177         return GetOpenFileName(&of);
178 }
179
180 /*
181  * This function is needed to link with the DES code. We need not
182  * have it do anything at all.
183  */
184 void logevent(char *msg) {
185 }
186
187 /*
188  * Dialog-box function for the Licence box.
189  */
190 static int CALLBACK LicenceProc (HWND hwnd, UINT msg,
191                                  WPARAM wParam, LPARAM lParam) {
192     switch (msg) {
193       case WM_INITDIALOG:
194         /*
195          * Centre the window.
196          */
197         {                              /* centre the window */
198             RECT rs, rd;
199             HWND hw;
200
201             hw = GetDesktopWindow();
202             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
203                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
204                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
205                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
206         }
207
208         return 1;
209       case WM_COMMAND:
210         switch (LOWORD(wParam)) {
211           case IDOK:
212             EndDialog(hwnd, 1);
213             return 0;
214         }
215         return 0;
216       case WM_CLOSE:
217         EndDialog(hwnd, 1);
218         return 0;
219     }
220     return 0;
221 }
222
223 /*
224  * Dialog-box function for the About box.
225  */
226 static int CALLBACK AboutProc (HWND hwnd, UINT msg,
227                                WPARAM wParam, LPARAM lParam) {
228     switch (msg) {
229       case WM_INITDIALOG:
230         /*
231          * Centre the window.
232          */
233         {                              /* centre the window */
234             RECT rs, rd;
235             HWND hw;
236
237             hw = GetDesktopWindow();
238             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
239                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
240                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
241                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
242         }
243
244         SetDlgItemText (hwnd, 100, ver);
245         return 1;
246       case WM_COMMAND:
247         switch (LOWORD(wParam)) {
248           case IDOK:
249             EndDialog(hwnd, 1);
250             return 0;
251           case 101:
252             EnableWindow(hwnd, 0);
253             DialogBox (hinst, MAKEINTRESOURCE(214), NULL, LicenceProc);
254             EnableWindow(hwnd, 1);
255             SetActiveWindow(hwnd);
256             return 0;
257         }
258         return 0;
259       case WM_CLOSE:
260         EndDialog(hwnd, 1);
261         return 0;
262     }
263     return 0;
264 }
265
266 /*
267  * Thread to generate a key.
268  */
269 struct rsa_key_thread_params {
270     HWND progressbar;                  /* notify this with progress */
271     HWND dialog;                       /* notify this on completion */
272     int keysize;                       /* bits in key */
273     struct RSAKey *key;
274 };
275 static DWORD WINAPI generate_rsa_key_thread(void *param) {
276     struct rsa_key_thread_params *params =
277         (struct rsa_key_thread_params *)param;
278     struct progress prog;
279     prog.progbar = params->progressbar;
280
281     rsa_generate(params->key, params->keysize, progress_update, &prog);
282
283     PostMessage(params->dialog, WM_DONEKEY, 0, 0);
284
285     sfree(params);
286     return 0;
287 }
288
289 struct MainDlgState {
290     int collecting_entropy;
291     int generation_thread_exists;
292     int key_exists;
293     int entropy_got, entropy_required, entropy_size;
294     int keysize;
295     int ssh2;
296     char **commentptr;                 /* points to key.comment or ssh2key.comment */
297     struct ssh2_userkey ssh2key;
298     unsigned *entropy;
299     struct RSAKey key;
300 };
301
302 static void hidemany(HWND hwnd, const int *ids, int hideit) {
303     while (*ids) {
304         ShowWindow(GetDlgItem(hwnd, *ids++), (hideit ? SW_HIDE : SW_SHOW));
305     }
306 }
307
308 static void setupbigedit1(HWND hwnd, int id, struct RSAKey *key) {
309     char *buffer;
310     char *dec1, *dec2;
311
312     dec1 = bignum_decimal(key->exponent);
313     dec2 = bignum_decimal(key->modulus);
314     buffer = smalloc(strlen(dec1)+strlen(dec2)+
315                      strlen(key->comment)+30);
316     sprintf(buffer, "%d %s %s %s",
317             ssh1_bignum_bitcount(key->modulus),
318             dec1, dec2, key->comment);
319     SetDlgItemText(hwnd, id, buffer);
320     sfree(dec1);
321     sfree(dec2);
322     sfree(buffer);
323 }
324
325 static void setupbigedit2(HWND hwnd, int id, struct ssh2_userkey *key) {
326     unsigned char *pub_blob;
327     char *buffer, *p;
328     int pub_len, buflen;
329     int i;
330
331     pub_blob = key->alg->public_blob(key->data, &pub_len);
332     buffer = smalloc(strlen(key->alg->name) + 4*((pub_len+2)/3) +
333                      strlen(key->comment) + 3);
334     strcpy(buffer, key->alg->name);
335     p = buffer + strlen(buffer);
336     *p++ = ' ';
337     i = 0;
338     while (i < pub_len) {
339         int n = (pub_len-i < 3 ? pub_len-i : 3);
340         base64_encode_atom(pub_blob+i, n, p);
341         i += n;
342         p += 4;
343     }
344     *p++ = ' ';
345     strcpy(p, key->comment);
346     SetDlgItemText(hwnd, id, buffer);
347     sfree(pub_blob);
348     sfree(buffer);    
349 }
350
351 /*
352  * Dialog-box function for the main PuTTYgen dialog box.
353  */
354 static int CALLBACK MainDlgProc (HWND hwnd, UINT msg,
355                                  WPARAM wParam, LPARAM lParam) {
356     enum {
357         controlidstart = 100,
358         IDC_TITLE,
359         IDC_BOX_KEY,
360         IDC_NOKEY,
361         IDC_GENERATING,
362         IDC_PROGRESS,
363         IDC_PKSTATIC, IDC_KEYDISPLAY,
364         IDC_FPSTATIC, IDC_FINGERPRINT,
365         IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
366         IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
367         IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT,
368         IDC_BOX_ACTIONS,
369         IDC_GENSTATIC, IDC_GENERATE,
370         IDC_LOADSTATIC, IDC_LOAD,
371         IDC_SAVESTATIC, IDC_SAVE,
372         IDC_BOX_PARAMS,
373         IDC_TYPESTATIC, IDC_KEYSSH1, IDC_KEYSSH2RSA,
374         IDC_BITSSTATIC, IDC_BITS,
375         IDC_ABOUT,
376     };
377     static const int nokey_ids[] = { IDC_NOKEY, 0 };
378     static const int generating_ids[] = { IDC_GENERATING, IDC_PROGRESS, 0 };
379     static const int gotkey_ids[] = {
380         IDC_PKSTATIC, IDC_KEYDISPLAY,
381         IDC_FPSTATIC, IDC_FINGERPRINT,
382         IDC_COMMENTSTATIC, IDC_COMMENTEDIT,
383         IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT,
384         IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 0 };
385     static const char generating_msg[] =
386         "Please wait while a key is generated...";
387     static const char entropy_msg[] =
388         "Please generate some randomness by moving the mouse over the blank area.";
389     struct MainDlgState *state;
390
391     switch (msg) {
392       case WM_INITDIALOG:
393         /*
394          * Centre the window.
395          */
396         {                              /* centre the window */
397             RECT rs, rd;
398             HWND hw;
399
400             hw = GetDesktopWindow();
401             if (GetWindowRect (hw, &rs) && GetWindowRect (hwnd, &rd))
402                 MoveWindow (hwnd, (rs.right + rs.left + rd.left - rd.right)/2,
403                             (rs.bottom + rs.top + rd.top - rd.bottom)/2,
404                             rd.right-rd.left, rd.bottom-rd.top, TRUE);
405         }
406
407         state = smalloc(sizeof(*state));
408         state->generation_thread_exists = FALSE;
409         state->collecting_entropy = FALSE;
410         state->entropy = NULL;
411         state->key_exists = FALSE;
412         SetWindowLong(hwnd, GWL_USERDATA, (LONG)state);
413         {
414             struct ctlpos cp, cp2;
415
416             /* Accelerators used: acglops */
417
418             ctlposinit(&cp, hwnd, 10, 10, 10);
419             bartitle(&cp, "Public and private key generation for PuTTY",
420                     IDC_TITLE);
421             beginbox(&cp, "Key",
422                      IDC_BOX_KEY);
423             cp2 = cp;
424             statictext(&cp2, "No key.", IDC_NOKEY);
425             cp2 = cp;
426             statictext(&cp2, "",
427                        IDC_GENERATING);
428             progressbar(&cp2, IDC_PROGRESS);
429             bigeditctrl(&cp,
430                         "&Public key for pasting into authorized_keys file:",
431                         IDC_PKSTATIC, IDC_KEYDISPLAY, 7);
432             SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0);
433             staticedit(&cp, "Key fingerprint:", IDC_FPSTATIC,
434                        IDC_FINGERPRINT, 75);
435             SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1, 0);
436             staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC,
437                        IDC_COMMENTEDIT, 75);
438             staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC,
439                            IDC_PASSPHRASE1EDIT, 75);
440             staticpassedit(&cp, "C&onfirm passphrase:", IDC_PASSPHRASE2STATIC,
441                            IDC_PASSPHRASE2EDIT, 75);
442             endbox(&cp);
443             beginbox(&cp, "Actions",
444                      IDC_BOX_ACTIONS);
445             staticbtn(&cp, "Generate a public/private key pair",
446                       IDC_GENSTATIC, "&Generate", IDC_GENERATE);
447             staticbtn(&cp, "Load an existing private key file",
448                       IDC_LOADSTATIC, "&Load", IDC_LOAD);
449             staticbtn(&cp, "Save the generated key to a new file",
450                       IDC_SAVESTATIC, "&Save", IDC_SAVE);
451             endbox(&cp);
452             beginbox(&cp, "Parameters",
453                      IDC_BOX_PARAMS);
454             radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 2,
455                           "SSH&1 (RSA)", IDC_KEYSSH1,
456                           "SSH2 &RSA", IDC_KEYSSH2RSA, NULL);
457             staticedit(&cp, "Number of &bits in a generated key:",
458                        IDC_BITSSTATIC, IDC_BITS, 20);
459             endbox(&cp);
460         }
461         CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2RSA, IDC_KEYSSH1);
462         SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE);
463
464         /*
465          * Initially, hide the progress bar and the key display,
466          * and show the no-key display. Also disable the Save
467          * button, because with no key we obviously can't save
468          * anything.
469          */
470         hidemany(hwnd, nokey_ids, FALSE);
471         hidemany(hwnd, generating_ids, TRUE);
472         hidemany(hwnd, gotkey_ids, TRUE);
473         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
474
475         return 1;
476       case WM_MOUSEMOVE:
477         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
478         if (state->collecting_entropy &&
479             state->entropy &&
480             state->entropy_got < state->entropy_required) {
481             state->entropy[state->entropy_got++] = lParam;
482             state->entropy[state->entropy_got++] = GetMessageTime();
483             SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS,
484                                state->entropy_got, 0);
485             if (state->entropy_got >= state->entropy_required) {
486                 struct rsa_key_thread_params *params;
487                 DWORD threadid;
488
489                 /*
490                  * Seed the entropy pool
491                  */
492                 random_add_heavynoise(state->entropy, state->entropy_size);
493                 memset(state->entropy, 0, state->entropy_size);
494                 sfree(state->entropy);
495                 state->collecting_entropy = FALSE;
496
497                 SetDlgItemText(hwnd, IDC_GENERATING, generating_msg);
498                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
499                                    MAKELPARAM(0, PROGRESSRANGE));
500                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
501
502                 params = smalloc(sizeof(*params));
503                 params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS);
504                 params->dialog = hwnd;
505                 params->keysize = state->keysize;
506                 params->key = &state->key;
507
508                 if (!CreateThread(NULL, 0, generate_rsa_key_thread,
509                                   params, 0, &threadid)) {
510                     MessageBox(hwnd, "Out of thread resources",
511                                "Key generation error",
512                                MB_OK | MB_ICONERROR);
513                     sfree(params);
514                 } else {
515                     state->generation_thread_exists = TRUE;
516                 }
517             }
518         }
519         break;
520       case WM_COMMAND:
521         switch (LOWORD(wParam)) {
522           case IDC_COMMENTEDIT:
523             if (HIWORD(wParam) == EN_CHANGE) {
524                 state = (struct MainDlgState *)
525                     GetWindowLong(hwnd, GWL_USERDATA);
526                 if (state->key_exists) {
527                     HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT);
528                     int len = GetWindowTextLength(editctl);
529                     if (*state->commentptr)
530                         sfree(*state->commentptr);
531                     *state->commentptr = smalloc(len+1);
532                     GetWindowText(editctl, *state->commentptr, len+1);
533                 }                
534             }
535             break;
536           case IDC_ABOUT:
537             EnableWindow(hwnd, 0);
538             DialogBox (hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
539             EnableWindow(hwnd, 1);
540             SetActiveWindow(hwnd);
541             return 0;
542           case IDC_GENERATE:
543             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
544             if (!state->generation_thread_exists) {
545                 BOOL ok;
546                 state->keysize = GetDlgItemInt(hwnd, IDC_BITS,
547                                                &ok, FALSE);
548                 if (!ok) state->keysize = DEFAULT_KEYSIZE;
549                 /* If we ever introduce a new key type, check it here! */
550                 state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1);
551                 if (state->keysize < 256) {
552                     int ret = MessageBox(hwnd,
553                                          "PuTTYgen will not generate a key"
554                                          " smaller than 256 bits.\n"
555                                          "Key length reset to 256. Continue?",
556                                          "PuTTYgen Warning",
557                                          MB_ICONWARNING | MB_OKCANCEL);
558                     if (ret != IDOK)
559                         break;
560                     state->keysize = 256;
561                     SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
562                 }
563                 hidemany(hwnd, nokey_ids, TRUE);
564                 hidemany(hwnd, generating_ids, FALSE);
565                 hidemany(hwnd, gotkey_ids, TRUE);
566                 EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 0);
567                 EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 0);
568                 EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
569                 state->key_exists = FALSE;
570                 SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
571                 state->collecting_entropy = TRUE;
572
573                 /*
574                  * My brief statistical tests on mouse movements
575                  * suggest that there are about 2.5 bits of
576                  * randomness in the x position, 2.5 in the y
577                  * position, and 1.7 in the message time, making
578                  * 5.7 bits of unpredictability per mouse movement.
579                  * However, other people have told me it's far less
580                  * than that, so I'm going to be stupidly cautious
581                  * and knock that down to a nice round 2. With this
582                  * method, we require two words per mouse movement,
583                  * so with 2 bits per mouse movement we expect 2
584                  * bits every 2 words.
585                  */
586                 state->entropy_required = (state->keysize/2) * 2;
587                 state->entropy_got = 0;
588                 state->entropy_size = (state->entropy_required *
589                                        sizeof(*state->entropy));
590                 state->entropy = smalloc(state->entropy_size);
591
592                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
593                                    MAKELPARAM(0, state->entropy_required));
594                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
595             }
596             break;
597           case IDC_SAVE:
598             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
599             if (state->key_exists) {
600                 char filename[FILENAME_MAX];
601                 char passphrase[PASSPHRASE_MAXLEN];
602                 char passphrase2[PASSPHRASE_MAXLEN];
603                 GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
604                                passphrase, sizeof(passphrase));
605                 GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
606                                passphrase2, sizeof(passphrase2));
607                 if (strcmp(passphrase, passphrase2)) {
608                     MessageBox(hwnd,
609                                "The two passphrases given do not match.",
610                                "PuTTYgen Error",
611                                MB_OK | MB_ICONERROR);
612                     break;
613                 }
614                 if (!*passphrase) {
615                     int ret;
616                     ret = MessageBox(hwnd,
617                                      "Are you sure you want to save this key\n"
618                                      "without a passphrase to protect it?",
619                                      "PuTTYgen Warning",
620                                      MB_YESNO | MB_ICONWARNING);
621                     if (ret != IDYES)
622                         break;
623                 }
624                 if (prompt_keyfile(hwnd, "Save private key as:",
625                                    filename, 1)) {
626                     int ret;
627                     FILE *fp = fopen(filename, "r");
628                     if (fp) {
629                         char buffer[FILENAME_MAX+80];
630                         fclose(fp);
631                         sprintf(buffer, "Overwrite existing file\n%.*s?",
632                                 FILENAME_MAX, filename);
633                         ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
634                                          MB_YESNO | MB_ICONWARNING);
635                         if (ret != IDYES)
636                             break;
637                     }
638                     if (state->ssh2) {
639                         ret = ssh2_save_userkey(filename, &state->ssh2key,
640                                                 *passphrase ? passphrase : NULL);
641                     } else {
642                         ret = saversakey(filename, &state->key,
643                                          *passphrase ? passphrase : NULL);
644                     }
645                     if (ret <= 0) {
646                         MessageBox(hwnd, "Unable to save key file",
647                                    "PuTTYgen Error",
648                                    MB_OK | MB_ICONERROR);
649                     }
650                 }
651             }
652             break;
653           case IDC_LOAD:
654             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
655             if (!state->generation_thread_exists) {
656                 char filename[FILENAME_MAX];
657                 if (prompt_keyfile(hwnd, "Load private key:",
658                                    filename, 0)) {
659                     char passphrase[PASSPHRASE_MAXLEN];
660                     int needs_pass;
661                     int ver;
662                     int ret;
663                     char *comment;
664                     struct PassphraseProcStruct pps;
665                     struct RSAKey newkey1;
666                     struct ssh2_userkey *newkey2;
667
668                     ver = keyfile_version(filename);
669                     if (ver == 0) {
670                         MessageBox(NULL, "Couldn't load private key.",
671                                    "PuTTYgen Error", MB_OK | MB_ICONERROR);
672                         break;
673                     }
674
675                     comment = NULL;
676                     if (ver == 1)
677                         needs_pass = rsakey_encrypted(filename, &comment);
678                     else
679                         needs_pass = ssh2_userkey_encrypted(filename, &comment);
680                     pps.passphrase = passphrase;
681                     pps.comment = comment;
682                     do {
683                         if (needs_pass) {
684                             int dlgret;
685                             dlgret = DialogBoxParam(hinst,
686                                                     MAKEINTRESOURCE(210),
687                                                     NULL, PassphraseProc,
688                                                     (LPARAM)&pps);
689                             if (!dlgret) {
690                                 ret = -2;
691                                 break;
692                             }
693                         } else
694                             *passphrase = '\0';
695                         if (ver == 1)
696                             ret = loadrsakey(filename, &newkey1, passphrase);
697                         else {
698                             newkey2 = ssh2_load_userkey(filename, passphrase);
699                             if (newkey2 == SSH2_WRONG_PASSPHRASE)
700                                 ret = -1;
701                             else if (!newkey2)
702                                 ret = 0;
703                             else
704                                 ret = 1;
705                         }
706                     } while (ret == -1);
707                     if (comment) sfree(comment);
708                     if (ret == 0) {
709                         MessageBox(NULL, "Couldn't load private key.",
710                                    "PuTTYgen Error", MB_OK | MB_ICONERROR);
711                     } else if (ret == 1) {
712                         EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
713                         EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
714                         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
715                         /*
716                          * Now update the key controls with all the
717                          * key data.
718                          */
719                         {
720                             SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
721                                            passphrase);
722                             SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
723                                            passphrase);
724                             if (ver == 1) {
725                                 char buf[128];
726                                 char *savecomment;
727
728                                 state->ssh2 = FALSE;
729                                 state->commentptr = &state->key.comment;
730                                 state->key = newkey1;
731
732                                 /*
733                                  * Set the key fingerprint.
734                                  */
735                                 savecomment = state->key.comment;
736                                 state->key.comment = NULL;
737                                 rsa_fingerprint(buf, sizeof(buf), &state->key);
738                                 state->key.comment = savecomment;
739
740                                 SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
741                                 /*
742                                  * Construct a decimal representation
743                                  * of the key, for pasting into
744                                  * .ssh/authorized_keys on a Unix box.
745                                  */
746                                 setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
747                             } else {
748                                 char *fp;
749                                 char *savecomment;
750
751                                 state->ssh2 = TRUE;
752                                 state->commentptr = &state->ssh2key.comment;
753                                 state->ssh2key = *newkey2;   /* structure copy */
754                                 sfree(newkey2);
755
756                                 savecomment = state->ssh2key.comment;
757                                 state->ssh2key.comment = NULL;
758                                 fp = state->
759                                     ssh2key.alg->fingerprint(state->ssh2key.data);
760                                 state->ssh2key.comment = savecomment;
761
762                                 SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
763                                 sfree(fp);
764
765                                 setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
766                             }
767                             SetDlgItemText(hwnd, IDC_COMMENTEDIT,
768                                            *state->commentptr);
769                         }
770                         /*
771                          * Finally, hide the progress bar and show
772                          * the key data.
773                          */
774                         hidemany(hwnd, nokey_ids, TRUE);
775                         hidemany(hwnd, generating_ids, TRUE);
776                         hidemany(hwnd, gotkey_ids, FALSE);
777                         state->key_exists = TRUE;
778                     }
779                 }
780             }
781             break;
782         }
783         return 0;
784       case WM_DONEKEY:
785         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
786         state->generation_thread_exists = FALSE;
787         state->key_exists = TRUE;
788         SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0);
789         EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
790         EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
791         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
792         if (state->ssh2)
793             state->commentptr = &state->ssh2key.comment;
794         else
795             state->commentptr = &state->key.comment;
796         /*
797          * Invent a comment for the key. We'll do this by including
798          * the date in it. This will be so horrifyingly ugly that
799          * the user will immediately want to change it, which is
800          * what we want :-)
801          */
802         *state->commentptr = smalloc(30);
803         {
804             time_t t;
805             struct tm *tm;
806             time(&t);
807             tm = localtime(&t);
808             strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
809         }
810             
811         /*
812          * Now update the key controls with all the key data.
813          */
814         {
815             char *savecomment;
816             /*
817              * Blank passphrase, initially. This isn't dangerous,
818              * because we will warn (Are You Sure?) before allowing
819              * the user to save an unprotected private key.
820              */
821             SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
822             SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
823             /*
824              * Set the comment.
825              */
826             SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
827             /*
828              * Set the key fingerprint.
829              */
830             savecomment = *state->commentptr;
831             *state->commentptr = NULL;
832             if (state->ssh2) {
833                 char *fp;
834                 fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
835                 SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
836                 sfree(fp);
837             } else {
838                 char buf[128];
839                 rsa_fingerprint(buf, sizeof(buf), &state->key);
840                 SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
841             }
842             *state->commentptr = savecomment;
843             /*
844              * Construct a decimal representation of the key, for
845              * pasting into .ssh/authorized_keys on a Unix box.
846              */
847             if (state->ssh2) {
848                 setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
849             } else {
850                 setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
851             }
852         }
853         /*
854          * Finally, hide the progress bar and show the key data.
855          */
856         hidemany(hwnd, nokey_ids, TRUE);
857         hidemany(hwnd, generating_ids, TRUE);
858         hidemany(hwnd, gotkey_ids, FALSE);
859         break;
860       case WM_CLOSE:
861         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
862         sfree(state);
863         EndDialog(hwnd, 1);
864         return 0;
865     }
866     return 0;
867 }
868
869 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
870     InitCommonControls();
871     hinst = inst;
872     random_init();
873     return DialogBox(hinst, MAKEINTRESOURCE(201), NULL, MainDlgProc) != IDOK;
874 }