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