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