Improved error messages if you use the wrong key type: you should
[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 #include "misc.h"
14
15 #define PUT_32BIT(cp, value) do { \
16 (cp)[3] = (value); \
17 (cp)[2] = (value) >> 8; \
18 (cp)[1] = (value) >> 16; \
19 (cp)[0] = (value) >> 24; } while (0)
20
21 #define GET_32BIT(cp) \
22 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
23 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
24 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
25 ((unsigned long)(unsigned char)(cp)[3]))
26
27 #define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
28
29 #define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
30 (x)-'a'<26 ? (x)-'a'+26 :\
31 (x)-'0'<10 ? (x)-'0'+52 :\
32 (x)=='+' ? 62 : \
33 (x)=='/' ? 63 : 0 )
34
35 static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only,
36 char **commentptr, char *passphrase)
37 {
38 unsigned char buf[16384];
39 unsigned char keybuf[16];
40 int len;
41 int i, j, ciphertype;
42 int ret = 0;
43 struct MD5Context md5c;
44 char *comment;
45
46 /* Slurp the whole file (minus the header) into a buffer. */
47 len = fread(buf, 1, sizeof(buf), fp);
48 fclose(fp);
49 if (len < 0 || len == sizeof(buf))
50 goto end; /* file too big or not read */
51
52 i = 0;
53
54 /*
55 * A zero byte. (The signature includes a terminating NUL.)
56 */
57 if (len - i < 1 || buf[i] != 0)
58 goto end;
59 i++;
60
61 /* One byte giving encryption type, and one reserved uint32. */
62 if (len - i < 1)
63 goto end;
64 ciphertype = buf[i];
65 if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
66 goto end;
67 i++;
68 if (len - i < 4)
69 goto end; /* reserved field not present */
70 if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
71 || buf[i + 3] != 0) goto end; /* reserved field nonzero, panic! */
72 i += 4;
73
74 /* Now the serious stuff. An ordinary SSH 1 public key. */
75 i += makekey(buf + i, key, NULL, 1);
76 if (len - i < 0)
77 goto end; /* overran */
78
79 if (pub_only) {
80 ret = 1;
81 goto end;
82 }
83
84 /* Next, the comment field. */
85 j = GET_32BIT(buf + i);
86 i += 4;
87 if (len - i < j)
88 goto end;
89 comment = smalloc(j + 1);
90 if (comment) {
91 memcpy(comment, buf + i, j);
92 comment[j] = '\0';
93 }
94 i += j;
95 if (commentptr)
96 *commentptr = comment;
97 if (key)
98 key->comment = comment;
99 if (!key) {
100 return ciphertype != 0;
101 }
102
103 /*
104 * Decrypt remainder of buffer.
105 */
106 if (ciphertype) {
107 MD5Init(&md5c);
108 MD5Update(&md5c, passphrase, strlen(passphrase));
109 MD5Final(keybuf, &md5c);
110 des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
111 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
112 }
113
114 /*
115 * We are now in the secret part of the key. The first four
116 * bytes should be of the form a, b, a, b.
117 */
118 if (len - i < 4)
119 goto end;
120 if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
121 ret = -1;
122 goto end;
123 }
124 i += 4;
125
126 /*
127 * After that, we have one further bignum which is our
128 * decryption exponent, and then the three auxiliary values
129 * (iqmp, q, p).
130 */
131 i += makeprivate(buf + i, key);
132 if (len - i < 0)
133 goto end;
134 i += ssh1_read_bignum(buf + i, &key->iqmp);
135 if (len - i < 0)
136 goto end;
137 i += ssh1_read_bignum(buf + i, &key->q);
138 if (len - i < 0)
139 goto end;
140 i += ssh1_read_bignum(buf + i, &key->p);
141 if (len - i < 0)
142 goto end;
143
144 if (!rsa_verify(key)) {
145 freersakey(key);
146 ret = 0;
147 } else
148 ret = 1;
149
150 end:
151 memset(buf, 0, sizeof(buf)); /* burn the evidence */
152 return ret;
153 }
154
155 int loadrsakey(char *filename, struct RSAKey *key, char *passphrase)
156 {
157 FILE *fp;
158 unsigned char buf[64];
159
160 fp = fopen(filename, "rb");
161 if (!fp)
162 return 0; /* doesn't even exist */
163
164 /*
165 * Read the first line of the file and see if it's a v1 private
166 * key file.
167 */
168 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
169 return loadrsakey_main(fp, key, FALSE, NULL, passphrase);
170 }
171
172 /*
173 * Otherwise, we have nothing. Return empty-handed.
174 */
175 fclose(fp);
176 return 0;
177 }
178
179 /*
180 * See whether an RSA key is encrypted. Return its comment field as
181 * well.
182 */
183 int rsakey_encrypted(char *filename, char **comment)
184 {
185 FILE *fp;
186 unsigned char buf[64];
187
188 fp = fopen(filename, "rb");
189 if (!fp)
190 return 0; /* doesn't even exist */
191
192 /*
193 * Read the first line of the file and see if it's a v1 private
194 * key file.
195 */
196 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
197 return loadrsakey_main(fp, NULL, FALSE, comment, NULL);
198 }
199 fclose(fp);
200 return 0; /* wasn't the right kind of file */
201 }
202
203 /*
204 * Return a malloc'ed chunk of memory containing the public blob of
205 * an RSA key, as given in the agent protocol (modulus bits,
206 * exponent, modulus).
207 */
208 int rsakey_pubblob(char *filename, void **blob, int *bloblen)
209 {
210 FILE *fp;
211 unsigned char buf[64];
212 struct RSAKey key;
213 int ret;
214
215 /* Default return if we fail. */
216 *blob = NULL;
217 *bloblen = 0;
218 ret = 0;
219
220 fp = fopen(filename, "rb");
221 if (!fp)
222 return 0; /* doesn't even exist */
223
224 /*
225 * Read the first line of the file and see if it's a v1 private
226 * key file.
227 */
228 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
229 memset(&key, 0, sizeof(key));
230 if (loadrsakey_main(fp, &key, TRUE, NULL, NULL)) {
231 *blob = rsa_public_blob(&key, bloblen);
232 freersakey(&key);
233 ret = 1;
234 }
235 }
236 fclose(fp);
237 return ret;
238 }
239
240 /*
241 * Save an RSA key file. Return nonzero on success.
242 */
243 int saversakey(char *filename, struct RSAKey *key, char *passphrase)
244 {
245 unsigned char buf[16384];
246 unsigned char keybuf[16];
247 struct MD5Context md5c;
248 unsigned char *p, *estart;
249 FILE *fp;
250
251 /*
252 * Write the initial signature.
253 */
254 p = buf;
255 memcpy(p, rsa_signature, sizeof(rsa_signature));
256 p += sizeof(rsa_signature);
257
258 /*
259 * One byte giving encryption type, and one reserved (zero)
260 * uint32.
261 */
262 *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
263 PUT_32BIT(p, 0);
264 p += 4;
265
266 /*
267 * An ordinary SSH 1 public key consists of: a uint32
268 * containing the bit count, then two bignums containing the
269 * modulus and exponent respectively.
270 */
271 PUT_32BIT(p, bignum_bitcount(key->modulus));
272 p += 4;
273 p += ssh1_write_bignum(p, key->modulus);
274 p += ssh1_write_bignum(p, key->exponent);
275
276 /*
277 * A string containing the comment field.
278 */
279 if (key->comment) {
280 PUT_32BIT(p, strlen(key->comment));
281 p += 4;
282 memcpy(p, key->comment, strlen(key->comment));
283 p += strlen(key->comment);
284 } else {
285 PUT_32BIT(p, 0);
286 p += 4;
287 }
288
289 /*
290 * The encrypted portion starts here.
291 */
292 estart = p;
293
294 /*
295 * Two bytes, then the same two bytes repeated.
296 */
297 *p++ = random_byte();
298 *p++ = random_byte();
299 p[0] = p[-2];
300 p[1] = p[-1];
301 p += 2;
302
303 /*
304 * Four more bignums: the decryption exponent, then iqmp, then
305 * q, then p.
306 */
307 p += ssh1_write_bignum(p, key->private_exponent);
308 p += ssh1_write_bignum(p, key->iqmp);
309 p += ssh1_write_bignum(p, key->q);
310 p += ssh1_write_bignum(p, key->p);
311
312 /*
313 * Now write zeros until the encrypted portion is a multiple of
314 * 8 bytes.
315 */
316 while ((p - estart) % 8)
317 *p++ = '\0';
318
319 /*
320 * Now encrypt the encrypted portion.
321 */
322 if (passphrase) {
323 MD5Init(&md5c);
324 MD5Update(&md5c, passphrase, strlen(passphrase));
325 MD5Final(keybuf, &md5c);
326 des3_encrypt_pubkey(keybuf, estart, p - estart);
327 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
328 }
329
330 /*
331 * Done. Write the result to the file.
332 */
333 fp = fopen(filename, "wb");
334 if (fp) {
335 int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
336 ret = ret && (fclose(fp) == 0);
337 return ret;
338 } else
339 return 0;
340 }
341
342 /* ----------------------------------------------------------------------
343 * SSH2 private key load/store functions.
344 */
345
346 /*
347 * PuTTY's own format for SSH2 keys is as follows:
348 *
349 * The file is text. Lines are terminated by CRLF, although CR-only
350 * and LF-only are tolerated on input.
351 *
352 * The first line says "PuTTY-User-Key-File-2: " plus the name of the
353 * algorithm ("ssh-dss", "ssh-rsa" etc).
354 *
355 * The next line says "Encryption: " plus an encryption type.
356 * Currently the only supported encryption types are "aes256-cbc"
357 * and "none".
358 *
359 * The next line says "Comment: " plus the comment string.
360 *
361 * Next there is a line saying "Public-Lines: " plus a number N.
362 * The following N lines contain a base64 encoding of the public
363 * part of the key. This is encoded as the standard SSH2 public key
364 * blob (with no initial length): so for RSA, for example, it will
365 * read
366 *
367 * string "ssh-rsa"
368 * mpint exponent
369 * mpint modulus
370 *
371 * Next, there is a line saying "Private-Lines: " plus a number N,
372 * and then N lines containing the (potentially encrypted) private
373 * part of the key. For the key type "ssh-rsa", this will be
374 * composed of
375 *
376 * mpint private_exponent
377 * mpint p (the larger of the two primes)
378 * mpint q (the smaller prime)
379 * mpint iqmp (the inverse of q modulo p)
380 * data padding (to reach a multiple of the cipher block size)
381 *
382 * And for "ssh-dss", it will be composed of
383 *
384 * mpint x (the private key parameter)
385 * [ string hash 20-byte hash of mpints p || q || g only in old format ]
386 *
387 * Finally, there is a line saying "Private-MAC: " plus a hex
388 * representation of a HMAC-SHA-1 of:
389 *
390 * string name of algorithm ("ssh-dss", "ssh-rsa")
391 * string encryption type
392 * string comment
393 * string public-blob
394 * string private-plaintext (the plaintext version of the
395 * private part, including the final
396 * padding)
397 *
398 * The key to the MAC is itself a SHA-1 hash of:
399 *
400 * data "putty-private-key-file-mac-key"
401 * data passphrase
402 *
403 * Encrypted keys should have a MAC, whereas unencrypted ones must
404 * have a hash.
405 *
406 * If the key is encrypted, the encryption key is derived from the
407 * passphrase by means of a succession of SHA-1 hashes. Each hash
408 * is the hash of:
409 *
410 * uint32 sequence-number
411 * data passphrase
412 *
413 * where the sequence-number increases from zero. As many of these
414 * hashes are used as necessary.
415 *
416 * For backwards compatibility with snapshots between 0.51 and
417 * 0.52, we also support the older key file format, which begins
418 * with "PuTTY-User-Key-File-1" (version number differs). In this
419 * format the Private-MAC: field only covers the private-plaintext
420 * field and nothing else (and without the 4-byte string length on
421 * the front too). Moreover, for RSA keys the Private-MAC: field
422 * can be replaced with a Private-Hash: field which is a plain
423 * SHA-1 hash instead of an HMAC. This is not allowable in DSA
424 * keys. (Yes, the old format was a mess. Guess why it changed :-)
425 */
426
427 static int read_header(FILE * fp, char *header)
428 {
429 int len = 39;
430 int c;
431
432 while (len > 0) {
433 c = fgetc(fp);
434 if (c == '\n' || c == '\r' || c == EOF)
435 return 0; /* failure */
436 if (c == ':') {
437 c = fgetc(fp);
438 if (c != ' ')
439 return 0;
440 *header = '\0';
441 return 1; /* success! */
442 }
443 if (len == 0)
444 return 0; /* failure */
445 *header++ = c;
446 len--;
447 }
448 return 0; /* failure */
449 }
450
451 static char *read_body(FILE * fp)
452 {
453 char *text;
454 int len;
455 int size;
456 int c;
457
458 size = 128;
459 text = smalloc(size);
460 len = 0;
461 text[len] = '\0';
462
463 while (1) {
464 c = fgetc(fp);
465 if (c == '\r' || c == '\n') {
466 c = fgetc(fp);
467 if (c != '\r' && c != '\n' && c != EOF)
468 ungetc(c, fp);
469 return text;
470 }
471 if (c == EOF) {
472 sfree(text);
473 return NULL;
474 }
475 if (len + 1 > size) {
476 size += 128;
477 text = srealloc(text, size);
478 }
479 text[len++] = c;
480 text[len] = '\0';
481 }
482 }
483
484 int base64_decode_atom(char *atom, unsigned char *out)
485 {
486 int vals[4];
487 int i, v, len;
488 unsigned word;
489 char c;
490
491 for (i = 0; i < 4; i++) {
492 c = atom[i];
493 if (c >= 'A' && c <= 'Z')
494 v = c - 'A';
495 else if (c >= 'a' && c <= 'z')
496 v = c - 'a' + 26;
497 else if (c >= '0' && c <= '9')
498 v = c - '0' + 52;
499 else if (c == '+')
500 v = 62;
501 else if (c == '/')
502 v = 63;
503 else if (c == '=')
504 v = -1;
505 else
506 return 0; /* invalid atom */
507 vals[i] = v;
508 }
509
510 if (vals[0] == -1 || vals[1] == -1)
511 return 0;
512 if (vals[2] == -1 && vals[3] != -1)
513 return 0;
514
515 if (vals[3] != -1)
516 len = 3;
517 else if (vals[2] != -1)
518 len = 2;
519 else
520 len = 1;
521
522 word = ((vals[0] << 18) |
523 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
524 out[0] = (word >> 16) & 0xFF;
525 if (len > 1)
526 out[1] = (word >> 8) & 0xFF;
527 if (len > 2)
528 out[2] = word & 0xFF;
529 return len;
530 }
531
532 static char *read_blob(FILE * fp, int nlines, int *bloblen)
533 {
534 unsigned char *blob;
535 char *line;
536 int linelen, len;
537 int i, j, k;
538
539 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
540 blob = smalloc(48 * nlines);
541 len = 0;
542 for (i = 0; i < nlines; i++) {
543 line = read_body(fp);
544 if (!line) {
545 sfree(blob);
546 return NULL;
547 }
548 linelen = strlen(line);
549 if (linelen % 4 != 0 || linelen > 64) {
550 sfree(blob);
551 sfree(line);
552 return NULL;
553 }
554 for (j = 0; j < linelen; j += 4) {
555 k = base64_decode_atom(line + j, blob + len);
556 if (!k) {
557 sfree(line);
558 sfree(blob);
559 return NULL;
560 }
561 len += k;
562 }
563 sfree(line);
564 }
565 *bloblen = len;
566 return blob;
567 }
568
569 /*
570 * Magic error return value for when the passphrase is wrong.
571 */
572 struct ssh2_userkey ssh2_wrong_passphrase = {
573 NULL, NULL, NULL
574 };
575
576 struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase)
577 {
578 FILE *fp;
579 char header[40], *b, *encryption, *comment, *mac;
580 const struct ssh_signkey *alg;
581 struct ssh2_userkey *ret;
582 int cipher, cipherblk;
583 unsigned char *public_blob, *private_blob;
584 int public_blob_len, private_blob_len;
585 int i, is_mac, old_fmt;
586 int passlen = passphrase ? strlen(passphrase) : 0;
587
588 ret = NULL; /* return NULL for most errors */
589 comment = mac = NULL;
590 public_blob = private_blob = NULL;
591
592 fp = fopen(filename, "rb");
593 if (!fp)
594 goto error;
595
596 /* Read the first header line which contains the key type. */
597 if (!read_header(fp, header))
598 goto error;
599 if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
600 old_fmt = 0;
601 } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
602 /* this is an old key file; warn and then continue */
603 old_keyfile_warning();
604 old_fmt = 1;
605 } else
606 goto error;
607 if ((b = read_body(fp)) == NULL)
608 goto error;
609 /* Select key algorithm structure. */
610 if (!strcmp(b, "ssh-rsa"))
611 alg = &ssh_rsa;
612 else if (!strcmp(b, "ssh-dss"))
613 alg = &ssh_dss;
614 else {
615 sfree(b);
616 goto error;
617 }
618 sfree(b);
619
620 /* Read the Encryption header line. */
621 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
622 goto error;
623 if ((encryption = read_body(fp)) == NULL)
624 goto error;
625 if (!strcmp(encryption, "aes256-cbc")) {
626 cipher = 1;
627 cipherblk = 16;
628 } else if (!strcmp(encryption, "none")) {
629 cipher = 0;
630 cipherblk = 1;
631 } else {
632 sfree(encryption);
633 goto error;
634 }
635
636 /* Read the Comment header line. */
637 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
638 goto error;
639 if ((comment = read_body(fp)) == NULL)
640 goto error;
641
642 /* Read the Public-Lines header line and the public blob. */
643 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
644 goto error;
645 if ((b = read_body(fp)) == NULL)
646 goto error;
647 i = atoi(b);
648 sfree(b);
649 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
650 goto error;
651
652 /* Read the Private-Lines header line and the Private blob. */
653 if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
654 goto error;
655 if ((b = read_body(fp)) == NULL)
656 goto error;
657 i = atoi(b);
658 sfree(b);
659 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
660 goto error;
661
662 /* Read the Private-MAC or Private-Hash header line. */
663 if (!read_header(fp, header))
664 goto error;
665 if (0 == strcmp(header, "Private-MAC")) {
666 if ((mac = read_body(fp)) == NULL)
667 goto error;
668 is_mac = 1;
669 } else if (0 == strcmp(header, "Private-Hash") &&
670 alg == &ssh_rsa && old_fmt) {
671 if ((mac = read_body(fp)) == NULL)
672 goto error;
673 is_mac = 0;
674 } else
675 goto error;
676
677 fclose(fp);
678 fp = NULL;
679
680 /*
681 * Decrypt the private blob.
682 */
683 if (cipher) {
684 unsigned char key[40];
685 SHA_State s;
686
687 if (!passphrase)
688 goto error;
689 if (private_blob_len % cipherblk)
690 goto error;
691
692 SHA_Init(&s);
693 SHA_Bytes(&s, "\0\0\0\0", 4);
694 SHA_Bytes(&s, passphrase, passlen);
695 SHA_Final(&s, key + 0);
696 SHA_Init(&s);
697 SHA_Bytes(&s, "\0\0\0\1", 4);
698 SHA_Bytes(&s, passphrase, passlen);
699 SHA_Final(&s, key + 20);
700 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
701 }
702
703 /*
704 * Verify the MAC.
705 */
706 {
707 char realmac[41];
708 unsigned char binary[20];
709 unsigned char *macdata;
710 int maclen;
711 int free_macdata;
712
713 if (old_fmt) {
714 /* MAC (or hash) only covers the private blob. */
715 macdata = private_blob;
716 maclen = private_blob_len;
717 free_macdata = 0;
718 } else {
719 unsigned char *p;
720 int namelen = strlen(alg->name);
721 int enclen = strlen(encryption);
722 int commlen = strlen(comment);
723 maclen = (4 + namelen +
724 4 + enclen +
725 4 + commlen +
726 4 + public_blob_len +
727 4 + private_blob_len);
728 macdata = smalloc(maclen);
729 p = macdata;
730 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
731 DO_STR(alg->name, namelen);
732 DO_STR(encryption, enclen);
733 DO_STR(comment, commlen);
734 DO_STR(public_blob, public_blob_len);
735 DO_STR(private_blob, private_blob_len);
736
737 free_macdata = 1;
738 }
739
740 if (is_mac) {
741 SHA_State s;
742 unsigned char mackey[20];
743 char header[] = "putty-private-key-file-mac-key";
744
745 SHA_Init(&s);
746 SHA_Bytes(&s, header, sizeof(header)-1);
747 if (passphrase)
748 SHA_Bytes(&s, passphrase, passlen);
749 SHA_Final(&s, mackey);
750
751 hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
752
753 memset(mackey, 0, sizeof(mackey));
754 memset(&s, 0, sizeof(s));
755 } else {
756 SHA_Simple(macdata, maclen, binary);
757 }
758
759 if (free_macdata) {
760 memset(macdata, 0, maclen);
761 sfree(macdata);
762 }
763
764 for (i = 0; i < 20; i++)
765 sprintf(realmac + 2 * i, "%02x", binary[i]);
766
767 if (strcmp(mac, realmac)) {
768 /* An incorrect MAC is an unconditional Error if the key is
769 * unencrypted. Otherwise, it means Wrong Passphrase. */
770 ret = cipher ? SSH2_WRONG_PASSPHRASE : NULL;
771 goto error;
772 }
773 }
774 sfree(mac);
775
776 /*
777 * Create and return the key.
778 */
779 ret = smalloc(sizeof(struct ssh2_userkey));
780 ret->alg = alg;
781 ret->comment = comment;
782 ret->data = alg->createkey(public_blob, public_blob_len,
783 private_blob, private_blob_len);
784 if (!ret->data) {
785 sfree(ret->comment);
786 sfree(ret);
787 ret = NULL;
788 }
789 sfree(public_blob);
790 sfree(private_blob);
791 sfree(encryption);
792 return ret;
793
794 /*
795 * Error processing.
796 */
797 error:
798 if (fp)
799 fclose(fp);
800 if (comment)
801 sfree(comment);
802 if (encryption)
803 sfree(encryption);
804 if (mac)
805 sfree(mac);
806 if (public_blob)
807 sfree(public_blob);
808 if (private_blob)
809 sfree(private_blob);
810 return ret;
811 }
812
813 char *ssh2_userkey_loadpub(char *filename, char **algorithm,
814 int *pub_blob_len)
815 {
816 FILE *fp;
817 char header[40], *b;
818 const struct ssh_signkey *alg;
819 unsigned char *public_blob;
820 int public_blob_len;
821 int i;
822
823 public_blob = NULL;
824
825 fp = fopen(filename, "rb");
826 if (!fp)
827 goto error;
828
829 /* Read the first header line which contains the key type. */
830 if (!read_header(fp, header)
831 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
832 0 != strcmp(header, "PuTTY-User-Key-File-1")))
833 goto error;
834 if ((b = read_body(fp)) == NULL)
835 goto error;
836 /* Select key algorithm structure. Currently only ssh-rsa. */
837 if (!strcmp(b, "ssh-rsa"))
838 alg = &ssh_rsa;
839 else if (!strcmp(b, "ssh-dss"))
840 alg = &ssh_dss;
841 else {
842 sfree(b);
843 goto error;
844 }
845 sfree(b);
846
847 /* Read the Encryption header line. */
848 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
849 goto error;
850 if ((b = read_body(fp)) == NULL)
851 goto error;
852 sfree(b); /* we don't care */
853
854 /* Read the Comment header line. */
855 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
856 goto error;
857 if ((b = read_body(fp)) == NULL)
858 goto error;
859 sfree(b); /* we don't care */
860
861 /* Read the Public-Lines header line and the public blob. */
862 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
863 goto error;
864 if ((b = read_body(fp)) == NULL)
865 goto error;
866 i = atoi(b);
867 sfree(b);
868 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
869 goto error;
870
871 fclose(fp);
872 if (pub_blob_len)
873 *pub_blob_len = public_blob_len;
874 if (algorithm)
875 *algorithm = alg->name;
876 return public_blob;
877
878 /*
879 * Error processing.
880 */
881 error:
882 if (fp)
883 fclose(fp);
884 if (public_blob)
885 sfree(public_blob);
886 return NULL;
887 }
888
889 int ssh2_userkey_encrypted(char *filename, char **commentptr)
890 {
891 FILE *fp;
892 char header[40], *b, *comment;
893 int ret;
894
895 if (commentptr)
896 *commentptr = NULL;
897
898 fp = fopen(filename, "rb");
899 if (!fp)
900 return 0;
901 if (!read_header(fp, header)
902 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
903 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
904 fclose(fp);
905 return 0;
906 }
907 if ((b = read_body(fp)) == NULL) {
908 fclose(fp);
909 return 0;
910 }
911 sfree(b); /* we don't care about key type here */
912 /* Read the Encryption header line. */
913 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
914 fclose(fp);
915 return 0;
916 }
917 if ((b = read_body(fp)) == NULL) {
918 fclose(fp);
919 return 0;
920 }
921
922 /* Read the Comment header line. */
923 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
924 fclose(fp);
925 sfree(b);
926 return 1;
927 }
928 if ((comment = read_body(fp)) == NULL) {
929 fclose(fp);
930 sfree(b);
931 return 1;
932 }
933
934 if (commentptr)
935 *commentptr = comment;
936
937 fclose(fp);
938 if (!strcmp(b, "aes256-cbc"))
939 ret = 1;
940 else
941 ret = 0;
942 sfree(b);
943 return ret;
944 }
945
946 int base64_lines(int datalen)
947 {
948 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
949 return (datalen + 47) / 48;
950 }
951
952 void base64_encode_atom(unsigned char *data, int n, char *out)
953 {
954 static const char base64_chars[] =
955 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
956
957 unsigned word;
958
959 word = data[0] << 16;
960 if (n > 1)
961 word |= data[1] << 8;
962 if (n > 2)
963 word |= data[2];
964 out[0] = base64_chars[(word >> 18) & 0x3F];
965 out[1] = base64_chars[(word >> 12) & 0x3F];
966 if (n > 1)
967 out[2] = base64_chars[(word >> 6) & 0x3F];
968 else
969 out[2] = '=';
970 if (n > 2)
971 out[3] = base64_chars[word & 0x3F];
972 else
973 out[3] = '=';
974 }
975
976 void base64_encode(FILE * fp, unsigned char *data, int datalen)
977 {
978 int linelen = 0;
979 char out[4];
980 int n;
981
982 while (datalen > 0) {
983 if (linelen >= 64) {
984 linelen = 0;
985 fputc('\n', fp);
986 }
987 n = (datalen < 3 ? datalen : 3);
988 base64_encode_atom(data, n, out);
989 data += n;
990 datalen -= n;
991 fwrite(out, 1, 4, fp);
992 linelen += 4;
993 }
994 fputc('\n', fp);
995 }
996
997 int ssh2_save_userkey(char *filename, struct ssh2_userkey *key,
998 char *passphrase)
999 {
1000 FILE *fp;
1001 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1002 int pub_blob_len, priv_blob_len, priv_encrypted_len;
1003 int passlen;
1004 int cipherblk;
1005 int i;
1006 char *cipherstr;
1007 unsigned char priv_mac[20];
1008
1009 /*
1010 * Fetch the key component blobs.
1011 */
1012 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1013 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1014 if (!pub_blob || !priv_blob) {
1015 sfree(pub_blob);
1016 sfree(priv_blob);
1017 return 0;
1018 }
1019
1020 /*
1021 * Determine encryption details, and encrypt the private blob.
1022 */
1023 if (passphrase) {
1024 cipherstr = "aes256-cbc";
1025 cipherblk = 16;
1026 } else {
1027 cipherstr = "none";
1028 cipherblk = 1;
1029 }
1030 priv_encrypted_len = priv_blob_len + cipherblk - 1;
1031 priv_encrypted_len -= priv_encrypted_len % cipherblk;
1032 priv_blob_encrypted = smalloc(priv_encrypted_len);
1033 memset(priv_blob_encrypted, 0, priv_encrypted_len);
1034 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1035 /* Create padding based on the SHA hash of the unpadded blob. This prevents
1036 * too easy a known-plaintext attack on the last block. */
1037 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
1038 assert(priv_encrypted_len - priv_blob_len < 20);
1039 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
1040 priv_encrypted_len - priv_blob_len);
1041
1042 /* Now create the MAC. */
1043 {
1044 unsigned char *macdata;
1045 int maclen;
1046 unsigned char *p;
1047 int namelen = strlen(key->alg->name);
1048 int enclen = strlen(cipherstr);
1049 int commlen = strlen(key->comment);
1050 SHA_State s;
1051 unsigned char mackey[20];
1052 char header[] = "putty-private-key-file-mac-key";
1053
1054 maclen = (4 + namelen +
1055 4 + enclen +
1056 4 + commlen +
1057 4 + pub_blob_len +
1058 4 + priv_encrypted_len);
1059 macdata = smalloc(maclen);
1060 p = macdata;
1061 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1062 DO_STR(key->alg->name, namelen);
1063 DO_STR(cipherstr, enclen);
1064 DO_STR(key->comment, commlen);
1065 DO_STR(pub_blob, pub_blob_len);
1066 DO_STR(priv_blob_encrypted, priv_encrypted_len);
1067
1068 SHA_Init(&s);
1069 SHA_Bytes(&s, header, sizeof(header)-1);
1070 if (passphrase)
1071 SHA_Bytes(&s, passphrase, strlen(passphrase));
1072 SHA_Final(&s, mackey);
1073 hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1074 memset(macdata, 0, maclen);
1075 sfree(macdata);
1076 memset(mackey, 0, sizeof(mackey));
1077 memset(&s, 0, sizeof(s));
1078 }
1079
1080 if (passphrase) {
1081 char key[40];
1082 SHA_State s;
1083
1084 passlen = strlen(passphrase);
1085
1086 SHA_Init(&s);
1087 SHA_Bytes(&s, "\0\0\0\0", 4);
1088 SHA_Bytes(&s, passphrase, passlen);
1089 SHA_Final(&s, key + 0);
1090 SHA_Init(&s);
1091 SHA_Bytes(&s, "\0\0\0\1", 4);
1092 SHA_Bytes(&s, passphrase, passlen);
1093 SHA_Final(&s, key + 20);
1094 aes256_encrypt_pubkey(key, priv_blob_encrypted,
1095 priv_encrypted_len);
1096
1097 memset(key, 0, sizeof(key));
1098 memset(&s, 0, sizeof(s));
1099 }
1100
1101 fp = fopen(filename, "w");
1102 if (!fp)
1103 return 0;
1104 fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
1105 fprintf(fp, "Encryption: %s\n", cipherstr);
1106 fprintf(fp, "Comment: %s\n", key->comment);
1107 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1108 base64_encode(fp, pub_blob, pub_blob_len);
1109 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1110 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len);
1111 fprintf(fp, "Private-MAC: ");
1112 for (i = 0; i < 20; i++)
1113 fprintf(fp, "%02x", priv_mac[i]);
1114 fprintf(fp, "\n");
1115 fclose(fp);
1116
1117 sfree(pub_blob);
1118 memset(priv_blob, 0, priv_blob_len);
1119 sfree(priv_blob);
1120 sfree(priv_blob_encrypted);
1121 return 1;
1122 }
1123
1124 /* ----------------------------------------------------------------------
1125 * A function to determine the type of a private key file. Returns
1126 * 0 on failure, 1 or 2 on success.
1127 */
1128 int key_type(char *filename)
1129 {
1130 FILE *fp;
1131 char buf[32];
1132 const char putty2_sig[] = "PuTTY-User-Key-File-";
1133 const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1134 const char openssh_sig[] = "-----BEGIN ";
1135 int i;
1136
1137 fp = fopen(filename, "r");
1138 if (!fp)
1139 return SSH_KEYTYPE_UNOPENABLE;
1140 i = fread(buf, 1, sizeof(buf), fp);
1141 fclose(fp);
1142 if (i < 0)
1143 return SSH_KEYTYPE_UNOPENABLE;
1144 if (i < 32)
1145 return SSH_KEYTYPE_UNKNOWN;
1146 if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1147 return SSH_KEYTYPE_SSH1;
1148 if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1149 return SSH_KEYTYPE_SSH2;
1150 if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1151 return SSH_KEYTYPE_OPENSSH;
1152 if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1153 return SSH_KEYTYPE_SSHCOM;
1154 return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
1155 }
1156
1157 /*
1158 * Convert the type word to a string, for `wrong type' error
1159 * messages.
1160 */
1161 char *key_type_to_str(int type)
1162 {
1163 switch (type) {
1164 case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1165 case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;
1166 case SSH_KEYTYPE_SSH1: return "SSH1 private key"; break;
1167 case SSH_KEYTYPE_SSH2: return "PuTTY SSH2 private key"; break;
1168 case SSH_KEYTYPE_OPENSSH: return "OpenSSH SSH2 private key"; break;
1169 case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH2 private key"; break;
1170 default: return "INTERNAL ERROR"; break;
1171 }
1172 }