]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - puttygen.c
ac5079e0822a06b61b8627b9118497590e975900
[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             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;
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                     if (state->ssh2) {
534                         setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
535                     } else {
536                         setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
537                     }
538                 }
539             }
540             break;
541           case IDC_ABOUT:
542             EnableWindow(hwnd, 0);
543             DialogBox (hinst, MAKEINTRESOURCE(213), NULL, AboutProc);
544             EnableWindow(hwnd, 1);
545             SetActiveWindow(hwnd);
546             return 0;
547           case IDC_GENERATE:
548             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
549             if (!state->generation_thread_exists) {
550                 BOOL ok;
551                 state->keysize = GetDlgItemInt(hwnd, IDC_BITS,
552                                                &ok, FALSE);
553                 if (!ok) state->keysize = DEFAULT_KEYSIZE;
554                 /* If we ever introduce a new key type, check it here! */
555                 state->ssh2 = !IsDlgButtonChecked(hwnd, IDC_KEYSSH1);
556                 if (state->keysize < 256) {
557                     int ret = MessageBox(hwnd,
558                                          "PuTTYgen will not generate a key"
559                                          " smaller than 256 bits.\n"
560                                          "Key length reset to 256. Continue?",
561                                          "PuTTYgen Warning",
562                                          MB_ICONWARNING | MB_OKCANCEL);
563                     if (ret != IDOK)
564                         break;
565                     state->keysize = 256;
566                     SetDlgItemInt(hwnd, IDC_BITS, 256, FALSE);
567                 }
568                 hidemany(hwnd, nokey_ids, TRUE);
569                 hidemany(hwnd, generating_ids, FALSE);
570                 hidemany(hwnd, gotkey_ids, TRUE);
571                 EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 0);
572                 EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 0);
573                 EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 0);
574                 state->key_exists = FALSE;
575                 SetDlgItemText(hwnd, IDC_GENERATING, entropy_msg);
576                 state->collecting_entropy = TRUE;
577
578                 /*
579                  * My brief statistical tests on mouse movements
580                  * suggest that there are about 2.5 bits of
581                  * randomness in the x position, 2.5 in the y
582                  * position, and 1.7 in the message time, making
583                  * 5.7 bits of unpredictability per mouse movement.
584                  * However, other people have told me it's far less
585                  * than that, so I'm going to be stupidly cautious
586                  * and knock that down to a nice round 2. With this
587                  * method, we require two words per mouse movement,
588                  * so with 2 bits per mouse movement we expect 2
589                  * bits every 2 words.
590                  */
591                 state->entropy_required = (state->keysize/2) * 2;
592                 state->entropy_got = 0;
593                 state->entropy_size = (state->entropy_required *
594                                        sizeof(*state->entropy));
595                 state->entropy = smalloc(state->entropy_size);
596
597                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0,
598                                    MAKELPARAM(0, state->entropy_required));
599                 SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0);
600             }
601             break;
602           case IDC_SAVE:
603             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
604             if (state->key_exists) {
605                 char filename[FILENAME_MAX];
606                 char passphrase[PASSPHRASE_MAXLEN];
607                 char passphrase2[PASSPHRASE_MAXLEN];
608                 GetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
609                                passphrase, sizeof(passphrase));
610                 GetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
611                                passphrase2, sizeof(passphrase2));
612                 if (strcmp(passphrase, passphrase2)) {
613                     MessageBox(hwnd,
614                                "The two passphrases given do not match.",
615                                "PuTTYgen Error",
616                                MB_OK | MB_ICONERROR);
617                     break;
618                 }
619                 if (!*passphrase) {
620                     int ret;
621                     ret = MessageBox(hwnd,
622                                      "Are you sure you want to save this key\n"
623                                      "without a passphrase to protect it?",
624                                      "PuTTYgen Warning",
625                                      MB_YESNO | MB_ICONWARNING);
626                     if (ret != IDYES)
627                         break;
628                 }
629                 if (prompt_keyfile(hwnd, "Save private key as:",
630                                    filename, 1)) {
631                     int ret;
632                     FILE *fp = fopen(filename, "r");
633                     if (fp) {
634                         char buffer[FILENAME_MAX+80];
635                         fclose(fp);
636                         sprintf(buffer, "Overwrite existing file\n%.*s?",
637                                 FILENAME_MAX, filename);
638                         ret = MessageBox(hwnd, buffer, "PuTTYgen Warning",
639                                          MB_YESNO | MB_ICONWARNING);
640                         if (ret != IDYES)
641                             break;
642                     }
643                     if (state->ssh2) {
644                         ret = ssh2_save_userkey(filename, &state->ssh2key,
645                                                 *passphrase ? passphrase : NULL);
646                     } else {
647                         ret = saversakey(filename, &state->key,
648                                          *passphrase ? passphrase : NULL);
649                     }
650                     if (ret <= 0) {
651                         MessageBox(hwnd, "Unable to save key file",
652                                    "PuTTYgen Error",
653                                    MB_OK | MB_ICONERROR);
654                     }
655                 }
656             }
657             break;
658           case IDC_LOAD:
659             state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
660             if (!state->generation_thread_exists) {
661                 char filename[FILENAME_MAX];
662                 if (prompt_keyfile(hwnd, "Load private key:",
663                                    filename, 0)) {
664                     char passphrase[PASSPHRASE_MAXLEN];
665                     int needs_pass;
666                     int ver;
667                     int ret;
668                     char *comment;
669                     struct PassphraseProcStruct pps;
670                     struct RSAKey newkey1;
671                     struct ssh2_userkey *newkey2;
672
673                     ver = keyfile_version(filename);
674                     if (ver == 0) {
675                         MessageBox(NULL, "Couldn't load private key.",
676                                    "PuTTYgen Error", MB_OK | MB_ICONERROR);
677                         break;
678                     }
679
680                     comment = NULL;
681                     if (ver == 1)
682                         needs_pass = rsakey_encrypted(filename, &comment);
683                     else
684                         needs_pass = ssh2_userkey_encrypted(filename, &comment);
685                     pps.passphrase = passphrase;
686                     pps.comment = comment;
687                     do {
688                         if (needs_pass) {
689                             int dlgret;
690                             dlgret = DialogBoxParam(hinst,
691                                                     MAKEINTRESOURCE(210),
692                                                     NULL, PassphraseProc,
693                                                     (LPARAM)&pps);
694                             if (!dlgret) {
695                                 ret = -2;
696                                 break;
697                             }
698                         } else
699                             *passphrase = '\0';
700                         if (ver == 1)
701                             ret = loadrsakey(filename, &newkey1, passphrase);
702                         else {
703                             newkey2 = ssh2_load_userkey(filename, passphrase);
704                             if (newkey2 == SSH2_WRONG_PASSPHRASE)
705                                 ret = -1;
706                             else if (!newkey2)
707                                 ret = 0;
708                             else
709                                 ret = 1;
710                         }
711                     } while (ret == -1);
712                     if (comment) sfree(comment);
713                     if (ret == 0) {
714                         MessageBox(NULL, "Couldn't load private key.",
715                                    "PuTTYgen Error", MB_OK | MB_ICONERROR);
716                     } else if (ret == 1) {
717                         EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
718                         EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
719                         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
720                         /*
721                          * Now update the key controls with all the
722                          * key data.
723                          */
724                         {
725                             SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT,
726                                            passphrase);
727                             SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT,
728                                            passphrase);
729                             if (ver == 1) {
730                                 char buf[128];
731                                 char *savecomment;
732
733                                 state->ssh2 = FALSE;
734                                 state->commentptr = &state->key.comment;
735                                 state->key = newkey1;
736
737                                 /*
738                                  * Set the key fingerprint.
739                                  */
740                                 savecomment = state->key.comment;
741                                 state->key.comment = NULL;
742                                 rsa_fingerprint(buf, sizeof(buf), &state->key);
743                                 state->key.comment = savecomment;
744
745                                 SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
746                                 /*
747                                  * Construct a decimal representation
748                                  * of the key, for pasting into
749                                  * .ssh/authorized_keys on a Unix box.
750                                  */
751                                 setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
752                             } else {
753                                 char *fp;
754                                 char *savecomment;
755
756                                 state->ssh2 = TRUE;
757                                 state->commentptr = &state->ssh2key.comment;
758                                 state->ssh2key = *newkey2;   /* structure copy */
759                                 sfree(newkey2);
760
761                                 savecomment = state->ssh2key.comment;
762                                 state->ssh2key.comment = NULL;
763                                 fp = state->
764                                     ssh2key.alg->fingerprint(state->ssh2key.data);
765                                 state->ssh2key.comment = savecomment;
766
767                                 SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
768                                 sfree(fp);
769
770                                 setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
771                             }
772                             SetDlgItemText(hwnd, IDC_COMMENTEDIT,
773                                            *state->commentptr);
774                         }
775                         /*
776                          * Finally, hide the progress bar and show
777                          * the key data.
778                          */
779                         hidemany(hwnd, nokey_ids, TRUE);
780                         hidemany(hwnd, generating_ids, TRUE);
781                         hidemany(hwnd, gotkey_ids, FALSE);
782                         state->key_exists = TRUE;
783                     }
784                 }
785             }
786             break;
787         }
788         return 0;
789       case WM_DONEKEY:
790         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
791         state->generation_thread_exists = FALSE;
792         state->key_exists = TRUE;
793         SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, PROGRESSRANGE, 0);
794         EnableWindow(GetDlgItem(hwnd, IDC_GENERATE), 1);
795         EnableWindow(GetDlgItem(hwnd, IDC_LOAD), 1);
796         EnableWindow(GetDlgItem(hwnd, IDC_SAVE), 1);
797         if (state->ssh2) {
798             state->ssh2key.data = &state->key;
799             state->ssh2key.alg = &ssh_rsa;
800             state->commentptr = &state->ssh2key.comment;
801         } else {
802             state->commentptr = &state->key.comment;
803         }
804         /*
805          * Invent a comment for the key. We'll do this by including
806          * the date in it. This will be so horrifyingly ugly that
807          * the user will immediately want to change it, which is
808          * what we want :-)
809          */
810         *state->commentptr = smalloc(30);
811         {
812             time_t t;
813             struct tm *tm;
814             time(&t);
815             tm = localtime(&t);
816             strftime(*state->commentptr, 30, "rsa-key-%Y%m%d", tm);
817         }
818             
819         /*
820          * Now update the key controls with all the key data.
821          */
822         {
823             char *savecomment;
824             /*
825              * Blank passphrase, initially. This isn't dangerous,
826              * because we will warn (Are You Sure?) before allowing
827              * the user to save an unprotected private key.
828              */
829             SetDlgItemText(hwnd, IDC_PASSPHRASE1EDIT, "");
830             SetDlgItemText(hwnd, IDC_PASSPHRASE2EDIT, "");
831             /*
832              * Set the comment.
833              */
834             SetDlgItemText(hwnd, IDC_COMMENTEDIT, *state->commentptr);
835             /*
836              * Set the key fingerprint.
837              */
838             savecomment = *state->commentptr;
839             *state->commentptr = NULL;
840             if (state->ssh2) {
841                 char *fp;
842                 fp = state->ssh2key.alg->fingerprint(state->ssh2key.data);
843                 SetDlgItemText(hwnd, IDC_FINGERPRINT, fp);
844                 sfree(fp);
845             } else {
846                 char buf[128];
847                 rsa_fingerprint(buf, sizeof(buf), &state->key);
848                 SetDlgItemText(hwnd, IDC_FINGERPRINT, buf);
849             }
850             *state->commentptr = savecomment;
851             /*
852              * Construct a decimal representation of the key, for
853              * pasting into .ssh/authorized_keys on a Unix box.
854              */
855             if (state->ssh2) {
856                 setupbigedit2(hwnd, IDC_KEYDISPLAY, &state->ssh2key);
857             } else {
858                 setupbigedit1(hwnd, IDC_KEYDISPLAY, &state->key);
859             }
860         }
861         /*
862          * Finally, hide the progress bar and show the key data.
863          */
864         hidemany(hwnd, nokey_ids, TRUE);
865         hidemany(hwnd, generating_ids, TRUE);
866         hidemany(hwnd, gotkey_ids, FALSE);
867         break;
868       case WM_CLOSE:
869         state = (struct MainDlgState *)GetWindowLong(hwnd, GWL_USERDATA);
870         sfree(state);
871         EndDialog(hwnd, 1);
872         return 0;
873     }
874     return 0;
875 }
876
877 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
878     InitCommonControls();
879     hinst = inst;
880     random_init();
881     return DialogBox(hinst, MAKEINTRESOURCE(201), NULL, MainDlgProc) != IDOK;
882 }