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