Preliminary support for RSA user authentication in SSH2! Most of the
[u/mdw/putty] / sshpubk.c
1 /*
2 * Generic SSH public-key handling operations. In particular,
3 * reading of SSH public-key files, and also the generic `sign'
4 * operation for ssh2 (which checks the type of the key and
5 * dispatches to the appropriate key-type specific function).
6 */
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <assert.h>
11
12 #include "ssh.h"
13
14 #define PUT_32BIT(cp, value) do { \
15 (cp)[3] = (value); \
16 (cp)[2] = (value) >> 8; \
17 (cp)[1] = (value) >> 16; \
18 (cp)[0] = (value) >> 24; } while (0)
19
20 #define GET_32BIT(cp) \
21 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
22 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
23 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
24 ((unsigned long)(unsigned char)(cp)[3]))
25
26 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
27
28 #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
29 (x)-'a'<26 ? (x)-'a'+26 :\
30 (x)-'0'<10 ? (x)-'0'+52 :\
31 (x)=='+' ? 62 : \
32 (x)=='/' ? 63 : 0 )
33
34 static int loadrsakey_main(FILE *fp, struct RSAKey *key,
35 char **commentptr, char *passphrase) {
36 unsigned char buf[16384];
37 unsigned char keybuf[16];
38 int len;
39 int i, j, ciphertype;
40 int ret = 0;
41 struct MD5Context md5c;
42 char *comment;
43
44 /* Slurp the whole file (minus the header) into a buffer. */
45 len = fread(buf, 1, sizeof(buf), fp);
46 fclose(fp);
47 if (len < 0 || len == sizeof(buf))
48 goto end; /* file too big or not read */
49
50 i = 0;
51
52 /*
53 * A zero byte. (The signature includes a terminating NUL.)
54 */
55 if (len-i < 1 || buf[i] != 0)
56 goto end;
57 i++;
58
59 /* One byte giving encryption type, and one reserved uint32. */
60 if (len-i < 1)
61 goto end;
62 ciphertype = buf[i];
63 if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
64 goto end;
65 i++;
66 if (len-i < 4)
67 goto end; /* reserved field not present */
68 if (buf[i] != 0 || buf[i+1] != 0 || buf[i+2] != 0 || buf[i+3] != 0)
69 goto end; /* reserved field nonzero, panic! */
70 i += 4;
71
72 /* Now the serious stuff. An ordinary SSH 1 public key. */
73 i += makekey(buf+i, key, NULL, 1);
74 if (len-i < 0)
75 goto end; /* overran */
76
77 /* Next, the comment field. */
78 j = GET_32BIT(buf+i);
79 i += 4;
80 if (len-i < j) goto end;
81 comment = smalloc(j+1);
82 if (comment) {
83 memcpy(comment, buf+i, j);
84 comment[j] = '\0';
85 }
86 i += j;
87 if (commentptr)
88 *commentptr = comment;
89 if (key)
90 key->comment = comment;
91 if (!key) {
92 return ciphertype != 0;
93 }
94
95 /*
96 * Decrypt remainder of buffer.
97 */
98 if (ciphertype) {
99 MD5Init(&md5c);
100 MD5Update(&md5c, passphrase, strlen(passphrase));
101 MD5Final(keybuf, &md5c);
102 des3_decrypt_pubkey(keybuf, buf+i, (len-i+7)&~7);
103 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
104 }
105
106 /*
107 * We are now in the secret part of the key. The first four
108 * bytes should be of the form a, b, a, b.
109 */
110 if (len-i < 4) goto end;
111 if (buf[i] != buf[i+2] || buf[i+1] != buf[i+3]) { ret = -1; goto end; }
112 i += 4;
113
114 /*
115 * After that, we have one further bignum which is our
116 * decryption exponent, and then the three auxiliary values
117 * (iqmp, q, p).
118 */
119 i += makeprivate(buf+i, key);
120 if (len-i < 0) goto end;
121 i += ssh1_read_bignum(buf+i, &key->iqmp);
122 if (len-i < 0) goto end;
123 i += ssh1_read_bignum(buf+i, &key->q);
124 if (len-i < 0) goto end;
125 i += ssh1_read_bignum(buf+i, &key->p);
126 if (len-i < 0) goto end;
127
128 ret = 1;
129 end:
130 memset(buf, 0, sizeof(buf)); /* burn the evidence */
131 return ret;
132 }
133
134 int loadrsakey(char *filename, struct RSAKey *key, char *passphrase) {
135 FILE *fp;
136 unsigned char buf[64];
137
138 fp = fopen(filename, "rb");
139 if (!fp)
140 return 0; /* doesn't even exist */
141
142 /*
143 * Read the first line of the file and see if it's a v1 private
144 * key file.
145 */
146 if (fgets(buf, sizeof(buf), fp) &&
147 !strcmp(buf, rsa_signature)) {
148 return loadrsakey_main(fp, key, NULL, passphrase);
149 }
150
151 /*
152 * Otherwise, we have nothing. Return empty-handed.
153 */
154 fclose(fp);
155 return 0;
156 }
157
158 /*
159 * See whether an RSA key is encrypted. Return its comment field as
160 * well.
161 */
162 int rsakey_encrypted(char *filename, char **comment) {
163 FILE *fp;
164 unsigned char buf[64];
165
166 fp = fopen(filename, "rb");
167 if (!fp)
168 return 0; /* doesn't even exist */
169
170 /*
171 * Read the first line of the file and see if it's a v1 private
172 * key file.
173 */
174 if (fgets(buf, sizeof(buf), fp) &&
175 !strcmp(buf, rsa_signature)) {
176 return loadrsakey_main(fp, NULL, comment, NULL);
177 }
178 fclose(fp);
179 return 0; /* wasn't the right kind of file */
180 }
181
182 /*
183 * Save an RSA key file. Return nonzero on success.
184 */
185 int saversakey(char *filename, struct RSAKey *key, char *passphrase) {
186 unsigned char buf[16384];
187 unsigned char keybuf[16];
188 struct MD5Context md5c;
189 unsigned char *p, *estart;
190 FILE *fp;
191
192 /*
193 * Write the initial signature.
194 */
195 p = buf;
196 memcpy(p, rsa_signature, sizeof(rsa_signature));
197 p += sizeof(rsa_signature);
198
199 /*
200 * One byte giving encryption type, and one reserved (zero)
201 * uint32.
202 */
203 *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
204 PUT_32BIT(p, 0); p += 4;
205
206 /*
207 * An ordinary SSH 1 public key consists of: a uint32
208 * containing the bit count, then two bignums containing the
209 * modulus and exponent respectively.
210 */
211 PUT_32BIT(p, ssh1_bignum_bitcount(key->modulus)); p += 4;
212 p += ssh1_write_bignum(p, key->modulus);
213 p += ssh1_write_bignum(p, key->exponent);
214
215 /*
216 * A string containing the comment field.
217 */
218 if (key->comment) {
219 PUT_32BIT(p, strlen(key->comment)); p += 4;
220 memcpy(p, key->comment, strlen(key->comment));
221 p += strlen(key->comment);
222 } else {
223 PUT_32BIT(p, 0); p += 4;
224 }
225
226 /*
227 * The encrypted portion starts here.
228 */
229 estart = p;
230
231 /*
232 * Two bytes, then the same two bytes repeated.
233 */
234 *p++ = random_byte();
235 *p++ = random_byte();
236 p[0] = p[-2]; p[1] = p[-1]; p += 2;
237
238 /*
239 * Four more bignums: the decryption exponent, then iqmp, then
240 * q, then p.
241 */
242 p += ssh1_write_bignum(p, key->private_exponent);
243 p += ssh1_write_bignum(p, key->iqmp);
244 p += ssh1_write_bignum(p, key->q);
245 p += ssh1_write_bignum(p, key->p);
246
247 /*
248 * Now write zeros until the encrypted portion is a multiple of
249 * 8 bytes.
250 */
251 while ((p-estart) % 8)
252 *p++ = '\0';
253
254 /*
255 * Now encrypt the encrypted portion.
256 */
257 if (passphrase) {
258 MD5Init(&md5c);
259 MD5Update(&md5c, passphrase, strlen(passphrase));
260 MD5Final(keybuf, &md5c);
261 des3_encrypt_pubkey(keybuf, estart, p-estart);
262 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
263 }
264
265 /*
266 * Done. Write the result to the file.
267 */
268 fp = fopen(filename, "wb");
269 if (fp) {
270 int ret = (fwrite(buf, 1, p-buf, fp) == (size_t)(p-buf));
271 ret = ret && (fclose(fp) == 0);
272 return ret;
273 } else
274 return 0;
275 }
276
277 /* ----------------------------------------------------------------------
278 * SSH2 private key load/store functions.
279 */
280
281 /*
282 * PuTTY's own format for SSH2 keys is as follows:
283 *
284 * The file is text. Lines are terminated by CRLF, although CR-only
285 * and LF-only are tolerated on input.
286 *
287 * The first line says "PuTTY-User-Key-File-1: " plus the name of the
288 * algorithm ("ssh-dss", "ssh-rsa" etc. Although, of course, this
289 * being PuTTY, "ssh-dss" is not supported.)
290 *
291 * The next line says "Encryption: " plus an encryption type.
292 * Currently the only supported encryption types are "aes256-cbc"
293 * and "none".
294 *
295 * The next line says "Comment: " plus the comment string.
296 *
297 * Next there is a line saying "Public-Lines: " plus a number N.
298 * The following N lines contain a base64 encoding of the public
299 * part of the key. This is encoded as the standard SSH2 public key
300 * blob (with no initial length): so for RSA, for example, it will
301 * read
302 *
303 * string "ssh-rsa"
304 * mpint exponent
305 * mpint modulus
306 *
307 * Next, there is a line saying "Private-Lines: " plus a number N,
308 * and then N lines containing the (potentially encrypted) private
309 * part of the key. For the key type "ssh-rsa", this will be
310 * composed of
311 *
312 * mpint private_exponent
313 * mpint p (the larger of the two primes)
314 * mpint q (the smaller prime)
315 * mpint iqmp (the inverse of q modulo p)
316 * data padding (to reach a multiple of the cipher block size)
317 *
318 * Finally, there is a line saying "Private-Hash: " plus a hex
319 * representation of a SHA-1 hash of the plaintext version of the
320 * private part, including the final padding.
321 *
322 * If the key is encrypted, the encryption key is derived from the
323 * passphrase by means of a succession of SHA-1 hashes. Each hash
324 * is the hash of:
325 *
326 * uint32 sequence-number
327 * string passphrase
328 *
329 * where the sequence-number increases from zero. As many of these
330 * hashes are used as necessary.
331 */
332
333 static int read_header(FILE *fp, char *header) {
334 int len = 39;
335 int c;
336
337 while (len > 0) {
338 c = fgetc(fp);
339 if (c == '\n' || c == '\r' || c == EOF)
340 return 0; /* failure */
341 if (c == ':') {
342 c = fgetc(fp);
343 if (c != ' ')
344 return 0;
345 *header = '\0';
346 return 1; /* success! */
347 }
348 if (len == 0)
349 return 0; /* failure */
350 *header++ = c;
351 len--;
352 }
353 return 0; /* failure */
354 }
355
356 static char *read_body(FILE *fp) {
357 char *text;
358 int len;
359 int size;
360 int c;
361
362 size = 128;
363 text = smalloc(size);
364 len = 0;
365 text[len] = '\0';
366
367 while (1) {
368 c = fgetc(fp);
369 if (c == '\r' || c == '\n') {
370 c = fgetc(fp);
371 if (c != '\r' && c != '\n' && c != EOF)
372 ungetc(c, fp);
373 return text;
374 }
375 if (c == EOF) {
376 sfree(text);
377 return NULL;
378 }
379 if (len + 1 > size) {
380 size += 128;
381 text = srealloc(text, size);
382 }
383 text[len++] = c;
384 text[len] = '\0';
385 }
386 }
387
388 int base64_decode_atom(char *atom, unsigned char *out) {
389 int vals[4];
390 int i, v, len;
391 unsigned word;
392 char c;
393
394 for (i = 0; i < 4; i++) {
395 c = atom[i];
396 if (c >= 'A' && c <= 'Z')
397 v = c - 'A';
398 else if (c >= 'a' && c <= 'z')
399 v = c - 'a' + 26;
400 else if (c >= '0' && c <= '9')
401 v = c - '0' + 52;
402 else if (c == '+')
403 v = 62;
404 else if (c == '/')
405 v = 63;
406 else if (c == '=')
407 v = -1;
408 else
409 return 0; /* invalid atom */
410 vals[i] = v;
411 }
412
413 if (vals[0] == -1 || vals[1] == -1)
414 return 0;
415 if (vals[2] == -1 && vals[3] != -1)
416 return 0;
417
418 if (vals[3] != -1)
419 len = 3;
420 else if (vals[2] != -1)
421 len = 2;
422 else
423 len = 1;
424
425 word = ((vals[0] << 18) |
426 (vals[1] << 12) |
427 ((vals[2] & 0x3F) << 6) |
428 (vals[3] & 0x3F));
429 out[0] = (word >> 16) & 0xFF;
430 if (len > 1)
431 out[1] = (word >> 8) & 0xFF;
432 if (len > 2)
433 out[2] = word & 0xFF;
434 return len;
435 }
436
437 static char *read_blob(FILE *fp, int nlines, int *bloblen) {
438 unsigned char *blob;
439 char *line;
440 int linelen, len;
441 int i, j, k;
442
443 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
444 blob = smalloc(48 * nlines);
445 len = 0;
446 for (i = 0; i < nlines; i++) {
447 line = read_body(fp);
448 if (!line) {
449 sfree(blob);
450 return NULL;
451 }
452 linelen = strlen(line);
453 if (linelen % 4 != 0 || linelen > 64) {
454 sfree(blob);
455 sfree(line);
456 return NULL;
457 }
458 for (j = 0; j < linelen; j += 4) {
459 k = base64_decode_atom(line+j, blob+len);
460 if (!k) {
461 sfree(line);
462 sfree(blob);
463 return NULL;
464 }
465 len += k;
466 }
467 sfree(line);
468 }
469 *bloblen = len;
470 return blob;
471 }
472
473 /*
474 * Magic error return value for when the passphrase is wrong.
475 */
476 struct ssh2_userkey ssh2_wrong_passphrase = {
477 NULL, NULL, NULL
478 };
479
480 struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase) {
481 FILE *fp;
482 char header[40], *b, *comment, *hash;
483 const struct ssh_signkey *alg;
484 struct ssh2_userkey *ret;
485 int cipher, cipherblk;
486 unsigned char *public_blob, *private_blob;
487 int public_blob_len, private_blob_len;
488 int i;
489
490 ret = NULL; /* return NULL for most errors */
491 comment = hash = NULL;
492 public_blob = private_blob = NULL;
493
494 fp = fopen(filename, "rb");
495 if (!fp)
496 goto error;
497
498 /* Read the first header line which contains the key type. */
499 if (!read_header(fp, header) || 0!=strcmp(header, "PuTTY-User-Key-File-1"))
500 goto error;
501 if ((b = read_body(fp)) == NULL)
502 goto error;
503 /* Select key algorithm structure. Currently only ssh-rsa. */
504 if (!strcmp(b, "ssh-rsa"))
505 alg = &ssh_rsa;
506 else {
507 sfree(b);
508 goto error;
509 }
510 sfree(b);
511
512 /* Read the Encryption header line. */
513 if (!read_header(fp, header) || 0!=strcmp(header, "Encryption"))
514 goto error;
515 if ((b = read_body(fp)) == NULL)
516 goto error;
517 if (!strcmp(b, "aes256-cbc")) {
518 cipher = 1; cipherblk = 16;
519 } else if (!strcmp(b, "none")) {
520 cipher = 0; cipherblk = 1;
521 } else {
522 sfree(b);
523 goto error;
524 }
525 sfree(b);
526
527 /* Read the Comment header line. */
528 if (!read_header(fp, header) || 0!=strcmp(header, "Comment"))
529 goto error;
530 if ((comment = read_body(fp)) == NULL)
531 goto error;
532
533 /* Read the Public-Lines header line and the public blob. */
534 if (!read_header(fp, header) || 0!=strcmp(header, "Public-Lines"))
535 goto error;
536 if ((b = read_body(fp)) == NULL)
537 goto error;
538 i = atoi(b);
539 sfree(b);
540 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
541 goto error;
542
543 /* Read the Private-Lines header line and the Private blob. */
544 if (!read_header(fp, header) || 0!=strcmp(header, "Private-Lines"))
545 goto error;
546 if ((b = read_body(fp)) == NULL)
547 goto error;
548 i = atoi(b);
549 sfree(b);
550 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
551 goto error;
552
553 /* Read the Private-Hash header line. */
554 if (!read_header(fp, header) || 0!=strcmp(header, "Private-Hash"))
555 goto error;
556 if ((hash = read_body(fp)) == NULL)
557 goto error;
558
559 fclose(fp);
560 fp = NULL;
561
562 /*
563 * Decrypt the private blob.
564 */
565 if (cipher) {
566 unsigned char key[40];
567 SHA_State s;
568 int passlen;
569
570 if (!passphrase)
571 goto error;
572 if (private_blob_len % cipherblk)
573 goto error;
574
575 passlen = strlen(passphrase);
576
577 SHA_Init(&s);
578 SHA_Bytes(&s, "\0\0\0\0", 4);
579 SHA_Bytes(&s, passphrase, passlen);
580 SHA_Final(&s, key+0);
581 SHA_Init(&s);
582 SHA_Bytes(&s, "\0\0\0\1", 4);
583 SHA_Bytes(&s, passphrase, passlen);
584 SHA_Final(&s, key+20);
585 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
586 }
587
588 /*
589 * Verify the private hash.
590 */
591 {
592 char realhash[41];
593 unsigned char binary[20];
594 SHA_State s;
595
596 SHA_Simple(private_blob, private_blob_len, binary);
597 for (i = 0; i < 20; i++)
598 sprintf(realhash+2*i, "%02x", binary[i]);
599
600 if (strcmp(hash, realhash)) {
601 /* An incorrect hash is an unconditional Error if the key is
602 * unencrypted. Otherwise, it means Wrong Passphrase. */
603 ret = cipher ? SSH2_WRONG_PASSPHRASE : NULL;
604 goto error;
605 }
606 }
607 sfree(hash);
608
609 /*
610 * Create and return the key.
611 */
612 ret = smalloc(sizeof(struct ssh2_userkey));
613 ret->alg = alg;
614 ret->comment = comment;
615 ret->data = alg->createkey(public_blob, public_blob_len,
616 private_blob, private_blob_len);
617 sfree(public_blob);
618 sfree(private_blob);
619 return ret;
620
621 /*
622 * Error processing.
623 */
624 error:
625 if (fp) fclose(fp);
626 if (comment) sfree(comment);
627 if (hash) sfree(hash);
628 if (public_blob) sfree(public_blob);
629 if (private_blob) sfree(private_blob);
630 return ret;
631 }
632
633 char *ssh2_userkey_loadpub(char *filename, char **algorithm, int *pub_blob_len) {
634 FILE *fp;
635 char header[40], *b;
636 const struct ssh_signkey *alg;
637 int cipher, cipherblk;
638 unsigned char *public_blob;
639 int public_blob_len;
640 int i;
641
642 public_blob = NULL;
643
644 fp = fopen(filename, "rb");
645 if (!fp)
646 goto error;
647
648 /* Read the first header line which contains the key type. */
649 if (!read_header(fp, header) || 0!=strcmp(header, "PuTTY-User-Key-File-1"))
650 goto error;
651 if ((b = read_body(fp)) == NULL)
652 goto error;
653 /* Select key algorithm structure. Currently only ssh-rsa. */
654 if (!strcmp(b, "ssh-rsa"))
655 alg = &ssh_rsa;
656 else {
657 sfree(b);
658 goto error;
659 }
660 sfree(b);
661
662 /* Read the Encryption header line. */
663 if (!read_header(fp, header) || 0!=strcmp(header, "Encryption"))
664 goto error;
665 if ((b = read_body(fp)) == NULL)
666 goto error;
667 sfree(b); /* we don't care */
668
669 /* Read the Comment header line. */
670 if (!read_header(fp, header) || 0!=strcmp(header, "Comment"))
671 goto error;
672 if ((b = read_body(fp)) == NULL)
673 goto error;
674 sfree(b); /* we don't care */
675
676 /* Read the Public-Lines header line and the public blob. */
677 if (!read_header(fp, header) || 0!=strcmp(header, "Public-Lines"))
678 goto error;
679 if ((b = read_body(fp)) == NULL)
680 goto error;
681 i = atoi(b);
682 sfree(b);
683 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
684 goto error;
685
686 fclose(fp);
687 *pub_blob_len = public_blob_len;
688 *algorithm = alg->name;
689 return public_blob;
690
691 /*
692 * Error processing.
693 */
694 error:
695 if (fp) fclose(fp);
696 if (public_blob) sfree(public_blob);
697 return NULL;
698 }
699
700 int ssh2_userkey_encrypted(char *filename, char **commentptr) {
701 FILE *fp;
702 char header[40], *b, *comment;
703 int ret;
704
705 if (commentptr) *commentptr = NULL;
706
707 fp = fopen(filename, "rb");
708 if (!fp)
709 return 0;
710 if (!read_header(fp, header) || 0!=strcmp(header, "PuTTY-User-Key-File-1")) {
711 fclose(fp); return 0;
712 }
713 if ((b = read_body(fp)) == NULL) {
714 fclose(fp); return 0;
715 }
716 sfree(b); /* we don't care about key type here */
717 /* Read the Encryption header line. */
718 if (!read_header(fp, header) || 0!=strcmp(header, "Encryption")) {
719 fclose(fp); return 0;
720 }
721 if ((b = read_body(fp)) == NULL) {
722 fclose(fp); return 0;
723 }
724
725 /* Read the Comment header line. */
726 if (!read_header(fp, header) || 0!=strcmp(header, "Comment")) {
727 fclose(fp); sfree(b); return 1;
728 }
729 if ((comment = read_body(fp)) == NULL) {
730 fclose(fp); sfree(b); return 1;
731 }
732
733 if (commentptr) *commentptr = comment;
734
735 fclose(fp);
736 if (!strcmp(b, "aes256-cbc"))
737 ret = 1;
738 else
739 ret = 0;
740 sfree(b);
741 return ret;
742 }
743
744 int base64_lines(int datalen) {
745 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
746 return (datalen+47) / 48;
747 }
748
749 void base64_encode_atom(unsigned char *data, int n, char *out) {
750 static const char base64_chars[] =
751 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
752
753 unsigned word;
754
755 word = data[0] << 16;
756 if (n > 1)
757 word |= data[1] << 8;
758 if (n > 2)
759 word |= data[2];
760 out[0] = base64_chars[(word >> 18) & 0x3F];
761 out[1] = base64_chars[(word >> 12) & 0x3F];
762 if (n > 1)
763 out[2] = base64_chars[(word >> 6) & 0x3F];
764 else
765 out[2] = '=';
766 if (n > 2)
767 out[3] = base64_chars[word & 0x3F];
768 else
769 out[3] = '=';
770 }
771
772 void base64_encode(FILE *fp, unsigned char *data, int datalen) {
773 int linelen = 0;
774 char out[4];
775 int n;
776
777 while (datalen > 0) {
778 if (linelen >= 64) {
779 linelen = 0;
780 fputc('\n', fp);
781 }
782 n = (datalen < 3 ? datalen : 3);
783 base64_encode_atom(data, n, out);
784 data += n;
785 datalen -= n;
786 fwrite(out, 1, 4, fp);
787 linelen += 4;
788 }
789 fputc('\n', fp);
790 }
791
792 int ssh2_save_userkey(char *filename, struct ssh2_userkey *key, char *passphrase) {
793 FILE *fp;
794 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
795 int pub_blob_len, priv_blob_len, priv_encrypted_len;
796 int passlen;
797 int cipherblk;
798 int i;
799 char *cipherstr;
800 unsigned char priv_hash[20];
801
802 /*
803 * Fetch the key component blobs.
804 */
805 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
806 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
807 if (!pub_blob || !priv_blob) {
808 sfree(pub_blob);
809 sfree(priv_blob);
810 return 0;
811 }
812
813 /*
814 * Determine encryption details, and encrypt the private blob.
815 */
816 if (passphrase) {
817 cipherstr = "aes256-cbc";
818 cipherblk = 16;
819 } else {
820 cipherstr = "none";
821 cipherblk = 1;
822 }
823 priv_encrypted_len = priv_blob_len + cipherblk - 1;
824 priv_encrypted_len -= priv_encrypted_len % cipherblk;
825 priv_blob_encrypted = smalloc(priv_encrypted_len);
826 memset(priv_blob_encrypted, 0, priv_encrypted_len);
827 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
828 /* Create padding based on the SHA hash of the unpadded blob. This prevents
829 * too easy a known-plaintext attack on the last block. */
830 SHA_Simple(priv_blob, priv_blob_len, priv_hash);
831 assert(priv_encrypted_len - priv_blob_len < 20);
832 memcpy(priv_blob_encrypted + priv_blob_len, priv_hash,
833 priv_encrypted_len - priv_blob_len);
834
835 /* Now create the _real_ private hash. */
836 SHA_Simple(priv_blob_encrypted, priv_encrypted_len, priv_hash);
837
838 if (passphrase) {
839 char key[40];
840 SHA_State s;
841
842 passlen = strlen(passphrase);
843
844 SHA_Init(&s);
845 SHA_Bytes(&s, "\0\0\0\0", 4);
846 SHA_Bytes(&s, passphrase, passlen);
847 SHA_Final(&s, key+0);
848 SHA_Init(&s);
849 SHA_Bytes(&s, "\0\0\0\1", 4);
850 SHA_Bytes(&s, passphrase, passlen);
851 SHA_Final(&s, key+20);
852 aes256_encrypt_pubkey(key, priv_blob_encrypted, priv_encrypted_len);
853 }
854
855 fp = fopen(filename, "w");
856 if (!fp)
857 return 0;
858 fprintf(fp, "PuTTY-User-Key-File-1: %s\n", key->alg->name);
859 fprintf(fp, "Encryption: %s\n", cipherstr);
860 fprintf(fp, "Comment: %s\n", key->comment);
861 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
862 base64_encode(fp, pub_blob, pub_blob_len);
863 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
864 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len);
865 fprintf(fp, "Private-Hash: ");
866 for (i = 0; i < 20; i++)
867 fprintf(fp, "%02x", priv_hash[i]);
868 fprintf(fp, "\n");
869 fclose(fp);
870 return 1;
871 }
872
873 /* ----------------------------------------------------------------------
874 * A function to determine which version of SSH to try on a private
875 * key file. Returns 0 on failure, 1 or 2 on success.
876 */
877 int keyfile_version(char *filename) {
878 FILE *fp;
879 int i;
880
881 fp = fopen(filename, "r");
882 if (!fp)
883 return 0;
884 i = fgetc(fp);
885 fclose(fp);
886 if (i == 'S')
887 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
888 if (i == 'P') /* "PuTTY-User-Key-File" etc */
889 return 2;
890 return 0; /* unrecognised or EOF */
891 }