Add another missing bounds check in the SSH-1 private key loader.
[u/mdw/putty] / sshpubk.c
CommitLineData
3eca8453 1/*
a52f067e 2 * Generic SSH public-key handling operations. In particular,
3 * reading of SSH public-key files, and also the generic `sign'
2e85c969 4 * operation for SSH-2 (which checks the type of the key and
a52f067e 5 * dispatches to the appropriate key-type specific function).
3eca8453 6 */
7
8#include <stdio.h>
a52f067e 9#include <stdlib.h>
65a22376 10#include <assert.h>
3eca8453 11
9a30e26b 12#include "putty.h"
3eca8453 13#include "ssh.h"
7bedb13c 14#include "misc.h"
3eca8453 15
3eca8453 16#define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
17
a52f067e 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
3f2d010c 24static int loadrsakey_main(FILE * fp, struct RSAKey *key, int pub_only,
222d54dc 25 char **commentptr, char *passphrase,
26 const char **error)
32874aea 27{
3eca8453 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;
a52f067e 34 char *comment;
3eca8453 35
222d54dc 36 *error = NULL;
37
a52f067e 38 /* Slurp the whole file (minus the header) into a buffer. */
3eca8453 39 len = fread(buf, 1, sizeof(buf), fp);
40 fclose(fp);
222d54dc 41 if (len < 0 || len == sizeof(buf)) {
42 *error = "error reading file";
32874aea 43 goto end; /* file too big or not read */
222d54dc 44 }
3eca8453 45
a52f067e 46 i = 0;
222d54dc 47 *error = "file format error";
3eca8453 48
a52f067e 49 /*
50 * A zero byte. (The signature includes a terminating NUL.)
51 */
32874aea 52 if (len - i < 1 || buf[i] != 0)
53 goto end;
a52f067e 54 i++;
3eca8453 55
a52f067e 56 /* One byte giving encryption type, and one reserved uint32. */
32874aea 57 if (len - i < 1)
58 goto end;
3eca8453 59 ciphertype = buf[i];
60 if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
32874aea 61 goto end;
3eca8453 62 i++;
32874aea 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! */
3eca8453 67 i += 4;
68
2e85c969 69 /* Now the serious stuff. An ordinary SSH-1 public key. */
0016d70b 70 i += makekey(buf + i, len, key, NULL, 1);
71 if (i < 0)
32874aea 72 goto end; /* overran */
3eca8453 73
74 /* Next, the comment field. */
32874aea 75 j = GET_32BIT(buf + i);
5c58ad2d 76 i += 4;
56668e6d 77 if (j < 0 || len - i < j)
32874aea 78 goto end;
3d88e64d 79 comment = snewn(j + 1, char);
a52f067e 80 if (comment) {
32874aea 81 memcpy(comment, buf + i, j);
82 comment[j] = '\0';
5c58ad2d 83 }
84 i += j;
a52f067e 85 if (commentptr)
d4963650 86 *commentptr = dupstr(comment);
a52f067e 87 if (key)
32874aea 88 key->comment = comment;
d4963650 89 else
90 sfree(comment);
91
92 if (pub_only) {
93 ret = 1;
94 goto end;
95 }
96
a52f067e 97 if (!key) {
222d54dc 98 ret = ciphertype != 0;
99 *error = NULL;
100 goto end;
a52f067e 101 }
3eca8453 102
103 /*
104 * Decrypt remainder of buffer.
105 */
106 if (ciphertype) {
32874aea 107 MD5Init(&md5c);
2247e107 108 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
32874aea 109 MD5Final(keybuf, &md5c);
110 des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
dfb88efd 111 smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
3eca8453 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 */
32874aea 118 if (len - i < 4)
119 goto end;
120 if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
222d54dc 121 *error = "wrong passphrase";
32874aea 122 ret = -1;
123 goto end;
124 }
3eca8453 125 i += 4;
126
127 /*
128 * After that, we have one further bignum which is our
6e522441 129 * decryption exponent, and then the three auxiliary values
130 * (iqmp, q, p).
3eca8453 131 */
0016d70b 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;
3eca8453 144
98f022f5 145 if (!rsa_verify(key)) {
222d54dc 146 *error = "rsa_verify failed";
98f022f5 147 freersakey(key);
148 ret = 0;
149 } else
150 ret = 1;
151
32874aea 152 end:
dfb88efd 153 smemclr(buf, sizeof(buf)); /* burn the evidence */
3eca8453 154 return ret;
155}
156
222d54dc 157int loadrsakey(const Filename *filename, struct RSAKey *key, char *passphrase,
158 const char **errorstr)
32874aea 159{
3eca8453 160 FILE *fp;
2247e107 161 char buf[64];
222d54dc 162 int ret = 0;
163 const char *error = NULL;
3eca8453 164
962468d4 165 fp = f_open(filename, "rb", FALSE);
222d54dc 166 if (!fp) {
167 error = "can't open file";
168 goto end;
169 }
3eca8453 170
a52f067e 171 /*
172 * Read the first line of the file and see if it's a v1 private
173 * key file.
174 */
32874aea 175 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
e19fadd7 176 /*
177 * This routine will take care of calling fclose() for us.
178 */
222d54dc 179 ret = loadrsakey_main(fp, key, FALSE, NULL, passphrase, &error);
47a6b94c 180 fp = NULL;
222d54dc 181 goto end;
a52f067e 182 }
183
184 /*
185 * Otherwise, we have nothing. Return empty-handed.
186 */
222d54dc 187 error = "not an SSH-1 RSA file";
188
189 end:
47a6b94c 190 if (fp)
191 fclose(fp);
222d54dc 192 if ((ret != 1) && errorstr)
193 *errorstr = error;
194 return ret;
3eca8453 195}
a52f067e 196
197/*
198 * See whether an RSA key is encrypted. Return its comment field as
199 * well.
200 */
9a30e26b 201int rsakey_encrypted(const Filename *filename, char **comment)
32874aea 202{
a52f067e 203 FILE *fp;
2247e107 204 char buf[64];
a52f067e 205
962468d4 206 fp = f_open(filename, "rb", FALSE);
a52f067e 207 if (!fp)
32874aea 208 return 0; /* doesn't even exist */
a52f067e 209
210 /*
211 * Read the first line of the file and see if it's a v1 private
212 * key file.
213 */
32874aea 214 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
222d54dc 215 const char *dummy;
e19fadd7 216 /*
217 * This routine will take care of calling fclose() for us.
218 */
222d54dc 219 return loadrsakey_main(fp, NULL, FALSE, comment, NULL, &dummy);
a52f067e 220 }
404f728b 221 fclose(fp);
32874aea 222 return 0; /* wasn't the right kind of file */
a52f067e 223}
6e522441 224
225/*
3f2d010c 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 */
222d54dc 230int rsakey_pubblob(const Filename *filename, void **blob, int *bloblen,
4bcf919e 231 char **commentptr, const char **errorstr)
3f2d010c 232{
233 FILE *fp;
2247e107 234 char buf[64];
3f2d010c 235 struct RSAKey key;
236 int ret;
222d54dc 237 const char *error = NULL;
3f2d010c 238
239 /* Default return if we fail. */
240 *blob = NULL;
241 *bloblen = 0;
242 ret = 0;
243
962468d4 244 fp = f_open(filename, "rb", FALSE);
222d54dc 245 if (!fp) {
246 error = "can't open file";
247 goto end;
248 }
3f2d010c 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));
4bcf919e 256 if (loadrsakey_main(fp, &key, TRUE, commentptr, NULL, &error)) {
3f2d010c 257 *blob = rsa_public_blob(&key, bloblen);
258 freersakey(&key);
259 ret = 1;
260 }
8a9ec857 261 fp = NULL; /* loadrsakey_main unconditionally closes fp */
222d54dc 262 } else {
263 error = "not an SSH-1 RSA file";
3f2d010c 264 }
222d54dc 265
266 end:
e19fadd7 267 if (fp)
268 fclose(fp);
222d54dc 269 if ((ret != 1) && errorstr)
270 *errorstr = error;
3f2d010c 271 return ret;
272}
273
274/*
6e522441 275 * Save an RSA key file. Return nonzero on success.
276 */
9a30e26b 277int saversakey(const Filename *filename, struct RSAKey *key, char *passphrase)
32874aea 278{
6e522441 279 unsigned char buf[16384];
280 unsigned char keybuf[16];
281 struct MD5Context md5c;
49bad831 282 unsigned char *p, *estart;
6e522441 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);
32874aea 297 PUT_32BIT(p, 0);
298 p += 4;
6e522441 299
300 /*
2e85c969 301 * An ordinary SSH-1 public key consists of: a uint32
6e522441 302 * containing the bit count, then two bignums containing the
303 * modulus and exponent respectively.
304 */
32874aea 305 PUT_32BIT(p, bignum_bitcount(key->modulus));
306 p += 4;
6e522441 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) {
32874aea 314 PUT_32BIT(p, strlen(key->comment));
315 p += 4;
316 memcpy(p, key->comment, strlen(key->comment));
317 p += strlen(key->comment);
6e522441 318 } else {
32874aea 319 PUT_32BIT(p, 0);
320 p += 4;
6e522441 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();
32874aea 333 p[0] = p[-2];
334 p[1] = p[-1];
335 p += 2;
6e522441 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);
65a22376 342 p += ssh1_write_bignum(p, key->iqmp);
343 p += ssh1_write_bignum(p, key->q);
344 p += ssh1_write_bignum(p, key->p);
6e522441 345
346 /*
347 * Now write zeros until the encrypted portion is a multiple of
348 * 8 bytes.
349 */
32874aea 350 while ((p - estart) % 8)
351 *p++ = '\0';
6e522441 352
353 /*
354 * Now encrypt the encrypted portion.
355 */
356 if (passphrase) {
32874aea 357 MD5Init(&md5c);
2247e107 358 MD5Update(&md5c, (unsigned char *)passphrase, strlen(passphrase));
32874aea 359 MD5Final(keybuf, &md5c);
360 des3_encrypt_pubkey(keybuf, estart, p - estart);
dfb88efd 361 smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
6e522441 362 }
363
364 /*
365 * Done. Write the result to the file.
366 */
962468d4 367 fp = f_open(filename, "wb", TRUE);
6e522441 368 if (fp) {
32874aea 369 int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
6402ecf9 370 if (fclose(fp))
371 ret = 0;
32874aea 372 return ret;
6e522441 373 } else
32874aea 374 return 0;
6e522441 375}
65a22376 376
377/* ----------------------------------------------------------------------
2e85c969 378 * SSH-2 private key load/store functions.
65a22376 379 */
380
381/*
2e85c969 382 * PuTTY's own format for SSH-2 keys is as follows:
5c72ca61 383 *
65a22376 384 * The file is text. Lines are terminated by CRLF, although CR-only
385 * and LF-only are tolerated on input.
5c72ca61 386 *
7bedb13c 387 * The first line says "PuTTY-User-Key-File-2: " plus the name of the
5c72ca61 388 * algorithm ("ssh-dss", "ssh-rsa" etc).
389 *
65a22376 390 * The next line says "Encryption: " plus an encryption type.
391 * Currently the only supported encryption types are "aes256-cbc"
392 * and "none".
5c72ca61 393 *
65a22376 394 * The next line says "Comment: " plus the comment string.
5c72ca61 395 *
65a22376 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
2e85c969 398 * part of the key. This is encoded as the standard SSH-2 public key
65a22376 399 * blob (with no initial length): so for RSA, for example, it will
400 * read
5c72ca61 401 *
65a22376 402 * string "ssh-rsa"
403 * mpint exponent
404 * mpint modulus
5c72ca61 405 *
65a22376 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
5c72ca61 410 *
65a22376 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)
5c72ca61 416 *
417 * And for "ssh-dss", it will be composed of
418 *
419 * mpint x (the private key parameter)
7bedb13c 420 * [ string hash 20-byte hash of mpints p || q || g only in old format ]
5c72ca61 421 *
7bedb13c 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)
65a22376 432 *
5c72ca61 433 * The key to the MAC is itself a SHA-1 hash of:
65a22376 434 *
5c72ca61 435 * data "putty-private-key-file-mac-key"
436 * data passphrase
437 *
28ad39e0 438 * (An empty passphrase is used for unencrypted keys.)
5c72ca61 439 *
65a22376 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:
5c72ca61 443 *
65a22376 444 * uint32 sequence-number
5c72ca61 445 * data passphrase
446 *
65a22376 447 * where the sequence-number increases from zero. As many of these
448 * hashes are used as necessary.
5c72ca61 449 *
7bedb13c 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
a92a9524 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).
65a22376 458 */
459
32874aea 460static int read_header(FILE * fp, char *header)
461{
65a22376 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
32874aea 484static char *read_body(FILE * fp)
485{
65a22376 486 char *text;
487 int len;
488 int size;
489 int c;
490
491 size = 128;
3d88e64d 492 text = snewn(size, char);
65a22376 493 len = 0;
494 text[len] = '\0';
495
496 while (1) {
497 c = fgetc(fp);
37ec7a11 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 }
65a22376 504 return text;
505 }
fe41296f 506 if (len + 1 >= size) {
65a22376 507 size += 128;
3d88e64d 508 text = sresize(text, size, char);
65a22376 509 }
510 text[len++] = c;
511 text[len] = '\0';
512 }
513}
514
32874aea 515int base64_decode_atom(char *atom, unsigned char *out)
516{
65a22376 517 int vals[4];
518 int i, v, len;
519 unsigned word;
520 char c;
32874aea 521
65a22376 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) |
32874aea 554 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
65a22376 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
2247e107 563static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)
32874aea 564{
65a22376 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. */
3d88e64d 571 blob = snewn(48 * nlines, unsigned char);
65a22376 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) {
32874aea 586 k = base64_decode_atom(line + j, blob + len);
65a22376 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 */
603struct ssh2_userkey ssh2_wrong_passphrase = {
604 NULL, NULL, NULL
605};
606
47a6b94c 607const 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
9a30e26b 617struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,
222d54dc 618 char *passphrase, const char **errorstr)
32874aea 619{
65a22376 620 FILE *fp;
7bedb13c 621 char header[40], *b, *encryption, *comment, *mac;
65a22376 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;
7bedb13c 627 int i, is_mac, old_fmt;
5c72ca61 628 int passlen = passphrase ? strlen(passphrase) : 0;
222d54dc 629 const char *error = NULL;
65a22376 630
631 ret = NULL; /* return NULL for most errors */
f545e34b 632 encryption = comment = mac = NULL;
65a22376 633 public_blob = private_blob = NULL;
634
962468d4 635 fp = f_open(filename, "rb", FALSE);
222d54dc 636 if (!fp) {
637 error = "can't open file";
65a22376 638 goto error;
222d54dc 639 }
65a22376 640
641 /* Read the first header line which contains the key type. */
7bedb13c 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;
6e3c47cb 650 } else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
651 /* this is a key file FROM THE FUTURE; refuse it, but with a
652 * more specific error message than the generic one below */
653 error = "PuTTY key format too new";
654 goto error;
222d54dc 655 } else {
656 error = "not a PuTTY SSH-2 private key";
65a22376 657 goto error;
222d54dc 658 }
659 error = "file format error";
65a22376 660 if ((b = read_body(fp)) == NULL)
661 goto error;
5c72ca61 662 /* Select key algorithm structure. */
47a6b94c 663 alg = find_pubkey_alg(b);
664 if (!alg) {
65a22376 665 sfree(b);
666 goto error;
667 }
668 sfree(b);
32874aea 669
65a22376 670 /* Read the Encryption header line. */
32874aea 671 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
65a22376 672 goto error;
7bedb13c 673 if ((encryption = read_body(fp)) == NULL)
65a22376 674 goto error;
7bedb13c 675 if (!strcmp(encryption, "aes256-cbc")) {
32874aea 676 cipher = 1;
677 cipherblk = 16;
7bedb13c 678 } else if (!strcmp(encryption, "none")) {
32874aea 679 cipher = 0;
680 cipherblk = 1;
65a22376 681 } else {
65a22376 682 goto error;
683 }
65a22376 684
685 /* Read the Comment header line. */
32874aea 686 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
65a22376 687 goto error;
688 if ((comment = read_body(fp)) == NULL)
689 goto error;
690
691 /* Read the Public-Lines header line and the public blob. */
32874aea 692 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
65a22376 693 goto error;
694 if ((b = read_body(fp)) == NULL)
695 goto error;
696 i = atoi(b);
697 sfree(b);
698 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
699 goto error;
700
701 /* Read the Private-Lines header line and the Private blob. */
32874aea 702 if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
65a22376 703 goto error;
704 if ((b = read_body(fp)) == NULL)
705 goto error;
706 i = atoi(b);
707 sfree(b);
708 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
709 goto error;
710
5c72ca61 711 /* Read the Private-MAC or Private-Hash header line. */
712 if (!read_header(fp, header))
65a22376 713 goto error;
5c72ca61 714 if (0 == strcmp(header, "Private-MAC")) {
715 if ((mac = read_body(fp)) == NULL)
716 goto error;
717 is_mac = 1;
a92a9524 718 } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {
5c72ca61 719 if ((mac = read_body(fp)) == NULL)
720 goto error;
721 is_mac = 0;
722 } else
65a22376 723 goto error;
724
725 fclose(fp);
726 fp = NULL;
727
728 /*
729 * Decrypt the private blob.
730 */
731 if (cipher) {
732 unsigned char key[40];
733 SHA_State s;
65a22376 734
735 if (!passphrase)
736 goto error;
737 if (private_blob_len % cipherblk)
738 goto error;
739
65a22376 740 SHA_Init(&s);
741 SHA_Bytes(&s, "\0\0\0\0", 4);
742 SHA_Bytes(&s, passphrase, passlen);
32874aea 743 SHA_Final(&s, key + 0);
65a22376 744 SHA_Init(&s);
745 SHA_Bytes(&s, "\0\0\0\1", 4);
746 SHA_Bytes(&s, passphrase, passlen);
32874aea 747 SHA_Final(&s, key + 20);
65a22376 748 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
749 }
750
751 /*
7bedb13c 752 * Verify the MAC.
65a22376 753 */
754 {
5c72ca61 755 char realmac[41];
65a22376 756 unsigned char binary[20];
7bedb13c 757 unsigned char *macdata;
758 int maclen;
759 int free_macdata;
760
761 if (old_fmt) {
762 /* MAC (or hash) only covers the private blob. */
763 macdata = private_blob;
764 maclen = private_blob_len;
765 free_macdata = 0;
766 } else {
767 unsigned char *p;
768 int namelen = strlen(alg->name);
769 int enclen = strlen(encryption);
770 int commlen = strlen(comment);
771 maclen = (4 + namelen +
772 4 + enclen +
773 4 + commlen +
774 4 + public_blob_len +
775 4 + private_blob_len);
3d88e64d 776 macdata = snewn(maclen, unsigned char);
7bedb13c 777 p = macdata;
778#define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
779 DO_STR(alg->name, namelen);
780 DO_STR(encryption, enclen);
781 DO_STR(comment, commlen);
782 DO_STR(public_blob, public_blob_len);
783 DO_STR(private_blob, private_blob_len);
784
785 free_macdata = 1;
786 }
65a22376 787
5c72ca61 788 if (is_mac) {
789 SHA_State s;
790 unsigned char mackey[20];
791 char header[] = "putty-private-key-file-mac-key";
792
5c72ca61 793 SHA_Init(&s);
794 SHA_Bytes(&s, header, sizeof(header)-1);
39ace9b0 795 if (cipher && passphrase)
7bedb13c 796 SHA_Bytes(&s, passphrase, passlen);
5c72ca61 797 SHA_Final(&s, mackey);
798
7bedb13c 799 hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
5c72ca61 800
dfb88efd 801 smemclr(mackey, sizeof(mackey));
802 smemclr(&s, sizeof(s));
5c72ca61 803 } else {
7bedb13c 804 SHA_Simple(macdata, maclen, binary);
5c72ca61 805 }
7bedb13c 806
807 if (free_macdata) {
dfb88efd 808 smemclr(macdata, maclen);
7bedb13c 809 sfree(macdata);
810 }
811
65a22376 812 for (i = 0; i < 20; i++)
5c72ca61 813 sprintf(realmac + 2 * i, "%02x", binary[i]);
65a22376 814
5c72ca61 815 if (strcmp(mac, realmac)) {
816 /* An incorrect MAC is an unconditional Error if the key is
65a22376 817 * unencrypted. Otherwise, it means Wrong Passphrase. */
222d54dc 818 if (cipher) {
b81cca98 819 error = "wrong passphrase";
222d54dc 820 ret = SSH2_WRONG_PASSPHRASE;
821 } else {
822 error = "MAC failed";
823 ret = NULL;
824 }
65a22376 825 goto error;
826 }
827 }
5c72ca61 828 sfree(mac);
65a22376 829
830 /*
831 * Create and return the key.
832 */
3d88e64d 833 ret = snew(struct ssh2_userkey);
65a22376 834 ret->alg = alg;
835 ret->comment = comment;
836 ret->data = alg->createkey(public_blob, public_blob_len,
837 private_blob, private_blob_len);
98f022f5 838 if (!ret->data) {
839 sfree(ret->comment);
840 sfree(ret);
841 ret = NULL;
222d54dc 842 error = "createkey failed";
843 goto error;
98f022f5 844 }
65a22376 845 sfree(public_blob);
846 sfree(private_blob);
7bedb13c 847 sfree(encryption);
2d8cd396 848 if (errorstr)
849 *errorstr = NULL;
65a22376 850 return ret;
851
852 /*
853 * Error processing.
854 */
32874aea 855 error:
856 if (fp)
857 fclose(fp);
858 if (comment)
859 sfree(comment);
7bedb13c 860 if (encryption)
861 sfree(encryption);
5c72ca61 862 if (mac)
863 sfree(mac);
32874aea 864 if (public_blob)
865 sfree(public_blob);
866 if (private_blob)
867 sfree(private_blob);
222d54dc 868 if (errorstr)
869 *errorstr = error;
65a22376 870 return ret;
871}
872
8a9977e5 873unsigned char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
874 int *pub_blob_len, char **commentptr,
875 const char **errorstr)
32874aea 876{
65a22376 877 FILE *fp;
878 char header[40], *b;
879 const struct ssh_signkey *alg;
65a22376 880 unsigned char *public_blob;
881 int public_blob_len;
882 int i;
222d54dc 883 const char *error = NULL;
06897bd7 884 char *comment;
65a22376 885
886 public_blob = NULL;
887
962468d4 888 fp = f_open(filename, "rb", FALSE);
222d54dc 889 if (!fp) {
890 error = "can't open file";
65a22376 891 goto error;
222d54dc 892 }
65a22376 893
894 /* Read the first header line which contains the key type. */
32874aea 895 if (!read_header(fp, header)
7bedb13c 896 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
222d54dc 897 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
6e3c47cb 898 if (0 == strncmp(header, "PuTTY-User-Key-File-", 20))
899 error = "PuTTY key format too new";
900 else
901 error = "not a PuTTY SSH-2 private key";
65a22376 902 goto error;
222d54dc 903 }
904 error = "file format error";
65a22376 905 if ((b = read_body(fp)) == NULL)
906 goto error;
fbc7c9b4 907 /* Select key algorithm structure. */
47a6b94c 908 alg = find_pubkey_alg(b);
909 if (!alg) {
65a22376 910 sfree(b);
911 goto error;
912 }
913 sfree(b);
32874aea 914
65a22376 915 /* Read the Encryption header line. */
32874aea 916 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
65a22376 917 goto error;
918 if ((b = read_body(fp)) == NULL)
919 goto error;
920 sfree(b); /* we don't care */
921
922 /* Read the Comment header line. */
32874aea 923 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
65a22376 924 goto error;
06897bd7 925 if ((comment = read_body(fp)) == NULL)
65a22376 926 goto error;
06897bd7 927
928 if (commentptr)
929 *commentptr = comment;
930 else
931 sfree(comment);
65a22376 932
933 /* Read the Public-Lines header line and the public blob. */
32874aea 934 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
65a22376 935 goto error;
936 if ((b = read_body(fp)) == NULL)
937 goto error;
938 i = atoi(b);
939 sfree(b);
940 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
941 goto error;
942
943 fclose(fp);
3f2d010c 944 if (pub_blob_len)
945 *pub_blob_len = public_blob_len;
946 if (algorithm)
947 *algorithm = alg->name;
8a9977e5 948 return public_blob;
65a22376 949
950 /*
951 * Error processing.
952 */
32874aea 953 error:
954 if (fp)
955 fclose(fp);
956 if (public_blob)
957 sfree(public_blob);
222d54dc 958 if (errorstr)
959 *errorstr = error;
65a22376 960 return NULL;
961}
962
9a30e26b 963int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
32874aea 964{
65a22376 965 FILE *fp;
966 char header[40], *b, *comment;
967 int ret;
968
32874aea 969 if (commentptr)
970 *commentptr = NULL;
65a22376 971
962468d4 972 fp = f_open(filename, "rb", FALSE);
65a22376 973 if (!fp)
974 return 0;
32874aea 975 if (!read_header(fp, header)
7bedb13c 976 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
977 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
32874aea 978 fclose(fp);
979 return 0;
65a22376 980 }
981 if ((b = read_body(fp)) == NULL) {
32874aea 982 fclose(fp);
983 return 0;
65a22376 984 }
985 sfree(b); /* we don't care about key type here */
986 /* Read the Encryption header line. */
32874aea 987 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
988 fclose(fp);
989 return 0;
65a22376 990 }
991 if ((b = read_body(fp)) == NULL) {
32874aea 992 fclose(fp);
993 return 0;
65a22376 994 }
995
996 /* Read the Comment header line. */
32874aea 997 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
998 fclose(fp);
999 sfree(b);
1000 return 1;
65a22376 1001 }
1002 if ((comment = read_body(fp)) == NULL) {
32874aea 1003 fclose(fp);
1004 sfree(b);
1005 return 1;
65a22376 1006 }
1007
32874aea 1008 if (commentptr)
1009 *commentptr = comment;
65a22376 1010
1011 fclose(fp);
1012 if (!strcmp(b, "aes256-cbc"))
1013 ret = 1;
1014 else
1015 ret = 0;
1016 sfree(b);
1017 return ret;
1018}
1019
32874aea 1020int base64_lines(int datalen)
1021{
65a22376 1022 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
32874aea 1023 return (datalen + 47) / 48;
65a22376 1024}
1025
96d19bc9 1026void base64_encode(FILE * fp, unsigned char *data, int datalen, int cpl)
32874aea 1027{
65a22376 1028 int linelen = 0;
1029 char out[4];
96d19bc9 1030 int n, i;
65a22376 1031
1032 while (datalen > 0) {
65a22376 1033 n = (datalen < 3 ? datalen : 3);
1034 base64_encode_atom(data, n, out);
1035 data += n;
1036 datalen -= n;
96d19bc9 1037 for (i = 0; i < 4; i++) {
1038 if (linelen >= cpl) {
1039 linelen = 0;
1040 fputc('\n', fp);
1041 }
1042 fputc(out[i], fp);
1043 linelen++;
1044 }
65a22376 1045 }
1046 fputc('\n', fp);
1047}
1048
9a30e26b 1049int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
32874aea 1050 char *passphrase)
1051{
65a22376 1052 FILE *fp;
1053 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1054 int pub_blob_len, priv_blob_len, priv_encrypted_len;
1055 int passlen;
1056 int cipherblk;
7bedb13c 1057 int i;
65a22376 1058 char *cipherstr;
5c72ca61 1059 unsigned char priv_mac[20];
65a22376 1060
1061 /*
1062 * Fetch the key component blobs.
1063 */
1064 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1065 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1066 if (!pub_blob || !priv_blob) {
1067 sfree(pub_blob);
1068 sfree(priv_blob);
1069 return 0;
1070 }
1071
1072 /*
1073 * Determine encryption details, and encrypt the private blob.
1074 */
1075 if (passphrase) {
1076 cipherstr = "aes256-cbc";
1077 cipherblk = 16;
1078 } else {
1079 cipherstr = "none";
1080 cipherblk = 1;
1081 }
1082 priv_encrypted_len = priv_blob_len + cipherblk - 1;
1083 priv_encrypted_len -= priv_encrypted_len % cipherblk;
3d88e64d 1084 priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
65a22376 1085 memset(priv_blob_encrypted, 0, priv_encrypted_len);
1086 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1087 /* Create padding based on the SHA hash of the unpadded blob. This prevents
1088 * too easy a known-plaintext attack on the last block. */
5c72ca61 1089 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
65a22376 1090 assert(priv_encrypted_len - priv_blob_len < 20);
5c72ca61 1091 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
65a22376 1092 priv_encrypted_len - priv_blob_len);
1093
7bedb13c 1094 /* Now create the MAC. */
1095 {
1096 unsigned char *macdata;
1097 int maclen;
1098 unsigned char *p;
1099 int namelen = strlen(key->alg->name);
1100 int enclen = strlen(cipherstr);
1101 int commlen = strlen(key->comment);
5c72ca61 1102 SHA_State s;
1103 unsigned char mackey[20];
1104 char header[] = "putty-private-key-file-mac-key";
1105
7bedb13c 1106 maclen = (4 + namelen +
1107 4 + enclen +
1108 4 + commlen +
1109 4 + pub_blob_len +
1110 4 + priv_encrypted_len);
3d88e64d 1111 macdata = snewn(maclen, unsigned char);
7bedb13c 1112 p = macdata;
1113#define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1114 DO_STR(key->alg->name, namelen);
1115 DO_STR(cipherstr, enclen);
1116 DO_STR(key->comment, commlen);
1117 DO_STR(pub_blob, pub_blob_len);
1118 DO_STR(priv_blob_encrypted, priv_encrypted_len);
5c72ca61 1119
1120 SHA_Init(&s);
1121 SHA_Bytes(&s, header, sizeof(header)-1);
7bedb13c 1122 if (passphrase)
1123 SHA_Bytes(&s, passphrase, strlen(passphrase));
5c72ca61 1124 SHA_Final(&s, mackey);
7bedb13c 1125 hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
dfb88efd 1126 smemclr(macdata, maclen);
7bedb13c 1127 sfree(macdata);
dfb88efd 1128 smemclr(mackey, sizeof(mackey));
1129 smemclr(&s, sizeof(s));
5c72ca61 1130 }
65a22376 1131
1132 if (passphrase) {
2247e107 1133 unsigned char key[40];
65a22376 1134 SHA_State s;
1135
1136 passlen = strlen(passphrase);
1137
1138 SHA_Init(&s);
1139 SHA_Bytes(&s, "\0\0\0\0", 4);
1140 SHA_Bytes(&s, passphrase, passlen);
32874aea 1141 SHA_Final(&s, key + 0);
65a22376 1142 SHA_Init(&s);
1143 SHA_Bytes(&s, "\0\0\0\1", 4);
1144 SHA_Bytes(&s, passphrase, passlen);
32874aea 1145 SHA_Final(&s, key + 20);
1146 aes256_encrypt_pubkey(key, priv_blob_encrypted,
1147 priv_encrypted_len);
5c72ca61 1148
dfb88efd 1149 smemclr(key, sizeof(key));
1150 smemclr(&s, sizeof(s));
65a22376 1151 }
1152
962468d4 1153 fp = f_open(filename, "w", TRUE);
65a22376 1154 if (!fp)
1155 return 0;
7bedb13c 1156 fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
65a22376 1157 fprintf(fp, "Encryption: %s\n", cipherstr);
1158 fprintf(fp, "Comment: %s\n", key->comment);
1159 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
96d19bc9 1160 base64_encode(fp, pub_blob, pub_blob_len, 64);
65a22376 1161 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
96d19bc9 1162 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
7bedb13c 1163 fprintf(fp, "Private-MAC: ");
65a22376 1164 for (i = 0; i < 20; i++)
5c72ca61 1165 fprintf(fp, "%02x", priv_mac[i]);
65a22376 1166 fprintf(fp, "\n");
1167 fclose(fp);
7bedb13c 1168
1169 sfree(pub_blob);
dfb88efd 1170 smemclr(priv_blob, priv_blob_len);
7bedb13c 1171 sfree(priv_blob);
1172 sfree(priv_blob_encrypted);
65a22376 1173 return 1;
1174}
1175
1176/* ----------------------------------------------------------------------
231ee168 1177 * A function to determine the type of a private key file. Returns
1178 * 0 on failure, 1 or 2 on success.
65a22376 1179 */
9a30e26b 1180int key_type(const Filename *filename)
32874aea 1181{
65a22376 1182 FILE *fp;
231ee168 1183 char buf[32];
1184 const char putty2_sig[] = "PuTTY-User-Key-File-";
1185 const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1186 const char openssh_sig[] = "-----BEGIN ";
65a22376 1187 int i;
1188
962468d4 1189 fp = f_open(filename, "r", FALSE);
65a22376 1190 if (!fp)
231ee168 1191 return SSH_KEYTYPE_UNOPENABLE;
1192 i = fread(buf, 1, sizeof(buf), fp);
65a22376 1193 fclose(fp);
231ee168 1194 if (i < 0)
1195 return SSH_KEYTYPE_UNOPENABLE;
1196 if (i < 32)
1197 return SSH_KEYTYPE_UNKNOWN;
1198 if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1199 return SSH_KEYTYPE_SSH1;
1200 if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1201 return SSH_KEYTYPE_SSH2;
1202 if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1203 return SSH_KEYTYPE_OPENSSH;
1204 if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1205 return SSH_KEYTYPE_SSHCOM;
1206 return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
1207}
1208
1209/*
1210 * Convert the type word to a string, for `wrong type' error
1211 * messages.
1212 */
1213char *key_type_to_str(int type)
1214{
1215 switch (type) {
1216 case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1217 case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;
2e85c969 1218 case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
1219 case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
1220 case SSH_KEYTYPE_OPENSSH: return "OpenSSH SSH-2 private key"; break;
1221 case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
231ee168 1222 default: return "INTERNAL ERROR"; break;
1223 }
65a22376 1224}