Unify GET_32BIT()/PUT_32BIT() et al from numerous source files into misc.h.
[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 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, NULL, 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, const char **errorstr)
870 {
871 FILE *fp;
872 char header[40], *b;
873 const struct ssh_signkey *alg;
874 unsigned char *public_blob;
875 int public_blob_len;
876 int i;
877 const char *error = NULL;
878
879 public_blob = NULL;
880
881 fp = f_open(*filename, "rb");
882 if (!fp) {
883 error = "can't open file";
884 goto error;
885 }
886
887 /* Read the first header line which contains the key type. */
888 if (!read_header(fp, header)
889 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
890 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
891 error = "not a PuTTY SSH-2 private key";
892 goto error;
893 }
894 error = "file format error";
895 if ((b = read_body(fp)) == NULL)
896 goto error;
897 /* Select key algorithm structure. */
898 alg = find_pubkey_alg(b);
899 if (!alg) {
900 sfree(b);
901 goto error;
902 }
903 sfree(b);
904
905 /* Read the Encryption header line. */
906 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
907 goto error;
908 if ((b = read_body(fp)) == NULL)
909 goto error;
910 sfree(b); /* we don't care */
911
912 /* Read the Comment header line. */
913 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
914 goto error;
915 if ((b = read_body(fp)) == NULL)
916 goto error;
917 sfree(b); /* we don't care */
918
919 /* Read the Public-Lines header line and the public blob. */
920 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
921 goto error;
922 if ((b = read_body(fp)) == NULL)
923 goto error;
924 i = atoi(b);
925 sfree(b);
926 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
927 goto error;
928
929 fclose(fp);
930 if (pub_blob_len)
931 *pub_blob_len = public_blob_len;
932 if (algorithm)
933 *algorithm = alg->name;
934 return (char *)public_blob;
935
936 /*
937 * Error processing.
938 */
939 error:
940 if (fp)
941 fclose(fp);
942 if (public_blob)
943 sfree(public_blob);
944 if (errorstr)
945 *errorstr = error;
946 return NULL;
947 }
948
949 int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
950 {
951 FILE *fp;
952 char header[40], *b, *comment;
953 int ret;
954
955 if (commentptr)
956 *commentptr = NULL;
957
958 fp = f_open(*filename, "rb");
959 if (!fp)
960 return 0;
961 if (!read_header(fp, header)
962 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
963 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
964 fclose(fp);
965 return 0;
966 }
967 if ((b = read_body(fp)) == NULL) {
968 fclose(fp);
969 return 0;
970 }
971 sfree(b); /* we don't care about key type here */
972 /* Read the Encryption header line. */
973 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
974 fclose(fp);
975 return 0;
976 }
977 if ((b = read_body(fp)) == NULL) {
978 fclose(fp);
979 return 0;
980 }
981
982 /* Read the Comment header line. */
983 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
984 fclose(fp);
985 sfree(b);
986 return 1;
987 }
988 if ((comment = read_body(fp)) == NULL) {
989 fclose(fp);
990 sfree(b);
991 return 1;
992 }
993
994 if (commentptr)
995 *commentptr = comment;
996
997 fclose(fp);
998 if (!strcmp(b, "aes256-cbc"))
999 ret = 1;
1000 else
1001 ret = 0;
1002 sfree(b);
1003 return ret;
1004 }
1005
1006 int base64_lines(int datalen)
1007 {
1008 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
1009 return (datalen + 47) / 48;
1010 }
1011
1012 void base64_encode(FILE * fp, unsigned char *data, int datalen, int cpl)
1013 {
1014 int linelen = 0;
1015 char out[4];
1016 int n, i;
1017
1018 while (datalen > 0) {
1019 n = (datalen < 3 ? datalen : 3);
1020 base64_encode_atom(data, n, out);
1021 data += n;
1022 datalen -= n;
1023 for (i = 0; i < 4; i++) {
1024 if (linelen >= cpl) {
1025 linelen = 0;
1026 fputc('\n', fp);
1027 }
1028 fputc(out[i], fp);
1029 linelen++;
1030 }
1031 }
1032 fputc('\n', fp);
1033 }
1034
1035 int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
1036 char *passphrase)
1037 {
1038 FILE *fp;
1039 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1040 int pub_blob_len, priv_blob_len, priv_encrypted_len;
1041 int passlen;
1042 int cipherblk;
1043 int i;
1044 char *cipherstr;
1045 unsigned char priv_mac[20];
1046
1047 /*
1048 * Fetch the key component blobs.
1049 */
1050 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1051 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1052 if (!pub_blob || !priv_blob) {
1053 sfree(pub_blob);
1054 sfree(priv_blob);
1055 return 0;
1056 }
1057
1058 /*
1059 * Determine encryption details, and encrypt the private blob.
1060 */
1061 if (passphrase) {
1062 cipherstr = "aes256-cbc";
1063 cipherblk = 16;
1064 } else {
1065 cipherstr = "none";
1066 cipherblk = 1;
1067 }
1068 priv_encrypted_len = priv_blob_len + cipherblk - 1;
1069 priv_encrypted_len -= priv_encrypted_len % cipherblk;
1070 priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
1071 memset(priv_blob_encrypted, 0, priv_encrypted_len);
1072 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1073 /* Create padding based on the SHA hash of the unpadded blob. This prevents
1074 * too easy a known-plaintext attack on the last block. */
1075 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
1076 assert(priv_encrypted_len - priv_blob_len < 20);
1077 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
1078 priv_encrypted_len - priv_blob_len);
1079
1080 /* Now create the MAC. */
1081 {
1082 unsigned char *macdata;
1083 int maclen;
1084 unsigned char *p;
1085 int namelen = strlen(key->alg->name);
1086 int enclen = strlen(cipherstr);
1087 int commlen = strlen(key->comment);
1088 SHA_State s;
1089 unsigned char mackey[20];
1090 char header[] = "putty-private-key-file-mac-key";
1091
1092 maclen = (4 + namelen +
1093 4 + enclen +
1094 4 + commlen +
1095 4 + pub_blob_len +
1096 4 + priv_encrypted_len);
1097 macdata = snewn(maclen, unsigned char);
1098 p = macdata;
1099 #define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1100 DO_STR(key->alg->name, namelen);
1101 DO_STR(cipherstr, enclen);
1102 DO_STR(key->comment, commlen);
1103 DO_STR(pub_blob, pub_blob_len);
1104 DO_STR(priv_blob_encrypted, priv_encrypted_len);
1105
1106 SHA_Init(&s);
1107 SHA_Bytes(&s, header, sizeof(header)-1);
1108 if (passphrase)
1109 SHA_Bytes(&s, passphrase, strlen(passphrase));
1110 SHA_Final(&s, mackey);
1111 hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1112 memset(macdata, 0, maclen);
1113 sfree(macdata);
1114 memset(mackey, 0, sizeof(mackey));
1115 memset(&s, 0, sizeof(s));
1116 }
1117
1118 if (passphrase) {
1119 unsigned char key[40];
1120 SHA_State s;
1121
1122 passlen = strlen(passphrase);
1123
1124 SHA_Init(&s);
1125 SHA_Bytes(&s, "\0\0\0\0", 4);
1126 SHA_Bytes(&s, passphrase, passlen);
1127 SHA_Final(&s, key + 0);
1128 SHA_Init(&s);
1129 SHA_Bytes(&s, "\0\0\0\1", 4);
1130 SHA_Bytes(&s, passphrase, passlen);
1131 SHA_Final(&s, key + 20);
1132 aes256_encrypt_pubkey(key, priv_blob_encrypted,
1133 priv_encrypted_len);
1134
1135 memset(key, 0, sizeof(key));
1136 memset(&s, 0, sizeof(s));
1137 }
1138
1139 fp = f_open(*filename, "w");
1140 if (!fp)
1141 return 0;
1142 fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
1143 fprintf(fp, "Encryption: %s\n", cipherstr);
1144 fprintf(fp, "Comment: %s\n", key->comment);
1145 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1146 base64_encode(fp, pub_blob, pub_blob_len, 64);
1147 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1148 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
1149 fprintf(fp, "Private-MAC: ");
1150 for (i = 0; i < 20; i++)
1151 fprintf(fp, "%02x", priv_mac[i]);
1152 fprintf(fp, "\n");
1153 fclose(fp);
1154
1155 sfree(pub_blob);
1156 memset(priv_blob, 0, priv_blob_len);
1157 sfree(priv_blob);
1158 sfree(priv_blob_encrypted);
1159 return 1;
1160 }
1161
1162 /* ----------------------------------------------------------------------
1163 * A function to determine the type of a private key file. Returns
1164 * 0 on failure, 1 or 2 on success.
1165 */
1166 int key_type(const Filename *filename)
1167 {
1168 FILE *fp;
1169 char buf[32];
1170 const char putty2_sig[] = "PuTTY-User-Key-File-";
1171 const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1172 const char openssh_sig[] = "-----BEGIN ";
1173 int i;
1174
1175 fp = f_open(*filename, "r");
1176 if (!fp)
1177 return SSH_KEYTYPE_UNOPENABLE;
1178 i = fread(buf, 1, sizeof(buf), fp);
1179 fclose(fp);
1180 if (i < 0)
1181 return SSH_KEYTYPE_UNOPENABLE;
1182 if (i < 32)
1183 return SSH_KEYTYPE_UNKNOWN;
1184 if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1185 return SSH_KEYTYPE_SSH1;
1186 if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1187 return SSH_KEYTYPE_SSH2;
1188 if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1189 return SSH_KEYTYPE_OPENSSH;
1190 if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1191 return SSH_KEYTYPE_SSHCOM;
1192 return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
1193 }
1194
1195 /*
1196 * Convert the type word to a string, for `wrong type' error
1197 * messages.
1198 */
1199 char *key_type_to_str(int type)
1200 {
1201 switch (type) {
1202 case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1203 case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;
1204 case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
1205 case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
1206 case SSH_KEYTYPE_OPENSSH: return "OpenSSH SSH-2 private key"; break;
1207 case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
1208 default: return "INTERNAL ERROR"; break;
1209 }
1210 }