Use va_copy() where available. This should fix a segfault in vsnprintf()
[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;
32874aea 77 if (len - i < j)
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);
111 memset(keybuf, 0, 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:
3eca8453 153 memset(buf, 0, sizeof(buf)); /* burn the evidence */
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
9a30e26b 165 fp = f_open(*filename, "rb");
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
9a30e26b 206 fp = f_open(*filename, "rb");
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
9a30e26b 244 fp = f_open(*filename, "rb");
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;
47a6b94c 260 fp = NULL;
3f2d010c 261 }
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);
361 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
6e522441 362 }
363
364 /*
365 * Done. Write the result to the file.
366 */
9a30e26b 367 fp = f_open(*filename, "wb");
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);
498 if (c == '\r' || c == '\n') {
499 c = fgetc(fp);
500 if (c != '\r' && c != '\n' && c != EOF)
501 ungetc(c, fp);
502 return text;
503 }
504 if (c == EOF) {
505 sfree(text);
506 return NULL;
507 }
fe41296f 508 if (len + 1 >= size) {
65a22376 509 size += 128;
3d88e64d 510 text = sresize(text, size, char);
65a22376 511 }
512 text[len++] = c;
513 text[len] = '\0';
514 }
515}
516
32874aea 517int base64_decode_atom(char *atom, unsigned char *out)
518{
65a22376 519 int vals[4];
520 int i, v, len;
521 unsigned word;
522 char c;
32874aea 523
65a22376 524 for (i = 0; i < 4; i++) {
525 c = atom[i];
526 if (c >= 'A' && c <= 'Z')
527 v = c - 'A';
528 else if (c >= 'a' && c <= 'z')
529 v = c - 'a' + 26;
530 else if (c >= '0' && c <= '9')
531 v = c - '0' + 52;
532 else if (c == '+')
533 v = 62;
534 else if (c == '/')
535 v = 63;
536 else if (c == '=')
537 v = -1;
538 else
539 return 0; /* invalid atom */
540 vals[i] = v;
541 }
542
543 if (vals[0] == -1 || vals[1] == -1)
544 return 0;
545 if (vals[2] == -1 && vals[3] != -1)
546 return 0;
547
548 if (vals[3] != -1)
549 len = 3;
550 else if (vals[2] != -1)
551 len = 2;
552 else
553 len = 1;
554
555 word = ((vals[0] << 18) |
32874aea 556 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
65a22376 557 out[0] = (word >> 16) & 0xFF;
558 if (len > 1)
559 out[1] = (word >> 8) & 0xFF;
560 if (len > 2)
561 out[2] = word & 0xFF;
562 return len;
563}
564
2247e107 565static unsigned char *read_blob(FILE * fp, int nlines, int *bloblen)
32874aea 566{
65a22376 567 unsigned char *blob;
568 char *line;
569 int linelen, len;
570 int i, j, k;
571
572 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
3d88e64d 573 blob = snewn(48 * nlines, unsigned char);
65a22376 574 len = 0;
575 for (i = 0; i < nlines; i++) {
576 line = read_body(fp);
577 if (!line) {
578 sfree(blob);
579 return NULL;
580 }
581 linelen = strlen(line);
582 if (linelen % 4 != 0 || linelen > 64) {
583 sfree(blob);
584 sfree(line);
585 return NULL;
586 }
587 for (j = 0; j < linelen; j += 4) {
32874aea 588 k = base64_decode_atom(line + j, blob + len);
65a22376 589 if (!k) {
590 sfree(line);
591 sfree(blob);
592 return NULL;
593 }
594 len += k;
595 }
596 sfree(line);
597 }
598 *bloblen = len;
599 return blob;
600}
601
602/*
603 * Magic error return value for when the passphrase is wrong.
604 */
605struct ssh2_userkey ssh2_wrong_passphrase = {
606 NULL, NULL, NULL
607};
608
47a6b94c 609const struct ssh_signkey *find_pubkey_alg(const char *name)
610{
611 if (!strcmp(name, "ssh-rsa"))
612 return &ssh_rsa;
613 else if (!strcmp(name, "ssh-dss"))
614 return &ssh_dss;
615 else
616 return NULL;
617}
618
9a30e26b 619struct ssh2_userkey *ssh2_load_userkey(const Filename *filename,
222d54dc 620 char *passphrase, const char **errorstr)
32874aea 621{
65a22376 622 FILE *fp;
7bedb13c 623 char header[40], *b, *encryption, *comment, *mac;
65a22376 624 const struct ssh_signkey *alg;
625 struct ssh2_userkey *ret;
626 int cipher, cipherblk;
627 unsigned char *public_blob, *private_blob;
628 int public_blob_len, private_blob_len;
7bedb13c 629 int i, is_mac, old_fmt;
5c72ca61 630 int passlen = passphrase ? strlen(passphrase) : 0;
222d54dc 631 const char *error = NULL;
65a22376 632
633 ret = NULL; /* return NULL for most errors */
f545e34b 634 encryption = comment = mac = NULL;
65a22376 635 public_blob = private_blob = NULL;
636
9a30e26b 637 fp = f_open(*filename, "rb");
222d54dc 638 if (!fp) {
639 error = "can't open file";
65a22376 640 goto error;
222d54dc 641 }
65a22376 642
643 /* Read the first header line which contains the key type. */
7bedb13c 644 if (!read_header(fp, header))
645 goto error;
646 if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
647 old_fmt = 0;
648 } else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
649 /* this is an old key file; warn and then continue */
650 old_keyfile_warning();
651 old_fmt = 1;
222d54dc 652 } else {
653 error = "not a PuTTY SSH-2 private key";
65a22376 654 goto error;
222d54dc 655 }
656 error = "file format error";
65a22376 657 if ((b = read_body(fp)) == NULL)
658 goto error;
5c72ca61 659 /* Select key algorithm structure. */
47a6b94c 660 alg = find_pubkey_alg(b);
661 if (!alg) {
65a22376 662 sfree(b);
663 goto error;
664 }
665 sfree(b);
32874aea 666
65a22376 667 /* Read the Encryption header line. */
32874aea 668 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
65a22376 669 goto error;
7bedb13c 670 if ((encryption = read_body(fp)) == NULL)
65a22376 671 goto error;
7bedb13c 672 if (!strcmp(encryption, "aes256-cbc")) {
32874aea 673 cipher = 1;
674 cipherblk = 16;
7bedb13c 675 } else if (!strcmp(encryption, "none")) {
32874aea 676 cipher = 0;
677 cipherblk = 1;
65a22376 678 } else {
7bedb13c 679 sfree(encryption);
65a22376 680 goto error;
681 }
65a22376 682
683 /* Read the Comment header line. */
32874aea 684 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
65a22376 685 goto error;
686 if ((comment = read_body(fp)) == NULL)
687 goto error;
688
689 /* Read the Public-Lines header line and the public blob. */
32874aea 690 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
65a22376 691 goto error;
692 if ((b = read_body(fp)) == NULL)
693 goto error;
694 i = atoi(b);
695 sfree(b);
696 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
697 goto error;
698
699 /* Read the Private-Lines header line and the Private blob. */
32874aea 700 if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
65a22376 701 goto error;
702 if ((b = read_body(fp)) == NULL)
703 goto error;
704 i = atoi(b);
705 sfree(b);
706 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
707 goto error;
708
5c72ca61 709 /* Read the Private-MAC or Private-Hash header line. */
710 if (!read_header(fp, header))
65a22376 711 goto error;
5c72ca61 712 if (0 == strcmp(header, "Private-MAC")) {
713 if ((mac = read_body(fp)) == NULL)
714 goto error;
715 is_mac = 1;
a92a9524 716 } else if (0 == strcmp(header, "Private-Hash") && old_fmt) {
5c72ca61 717 if ((mac = read_body(fp)) == NULL)
718 goto error;
719 is_mac = 0;
720 } else
65a22376 721 goto error;
722
723 fclose(fp);
724 fp = NULL;
725
726 /*
727 * Decrypt the private blob.
728 */
729 if (cipher) {
730 unsigned char key[40];
731 SHA_State s;
65a22376 732
733 if (!passphrase)
734 goto error;
735 if (private_blob_len % cipherblk)
736 goto error;
737
65a22376 738 SHA_Init(&s);
739 SHA_Bytes(&s, "\0\0\0\0", 4);
740 SHA_Bytes(&s, passphrase, passlen);
32874aea 741 SHA_Final(&s, key + 0);
65a22376 742 SHA_Init(&s);
743 SHA_Bytes(&s, "\0\0\0\1", 4);
744 SHA_Bytes(&s, passphrase, passlen);
32874aea 745 SHA_Final(&s, key + 20);
65a22376 746 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
747 }
748
749 /*
7bedb13c 750 * Verify the MAC.
65a22376 751 */
752 {
5c72ca61 753 char realmac[41];
65a22376 754 unsigned char binary[20];
7bedb13c 755 unsigned char *macdata;
756 int maclen;
757 int free_macdata;
758
759 if (old_fmt) {
760 /* MAC (or hash) only covers the private blob. */
761 macdata = private_blob;
762 maclen = private_blob_len;
763 free_macdata = 0;
764 } else {
765 unsigned char *p;
766 int namelen = strlen(alg->name);
767 int enclen = strlen(encryption);
768 int commlen = strlen(comment);
769 maclen = (4 + namelen +
770 4 + enclen +
771 4 + commlen +
772 4 + public_blob_len +
773 4 + private_blob_len);
3d88e64d 774 macdata = snewn(maclen, unsigned char);
7bedb13c 775 p = macdata;
776#define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
777 DO_STR(alg->name, namelen);
778 DO_STR(encryption, enclen);
779 DO_STR(comment, commlen);
780 DO_STR(public_blob, public_blob_len);
781 DO_STR(private_blob, private_blob_len);
782
783 free_macdata = 1;
784 }
65a22376 785
5c72ca61 786 if (is_mac) {
787 SHA_State s;
788 unsigned char mackey[20];
789 char header[] = "putty-private-key-file-mac-key";
790
5c72ca61 791 SHA_Init(&s);
792 SHA_Bytes(&s, header, sizeof(header)-1);
39ace9b0 793 if (cipher && passphrase)
7bedb13c 794 SHA_Bytes(&s, passphrase, passlen);
5c72ca61 795 SHA_Final(&s, mackey);
796
7bedb13c 797 hmac_sha1_simple(mackey, 20, macdata, maclen, binary);
5c72ca61 798
799 memset(mackey, 0, sizeof(mackey));
800 memset(&s, 0, sizeof(s));
801 } else {
7bedb13c 802 SHA_Simple(macdata, maclen, binary);
5c72ca61 803 }
7bedb13c 804
805 if (free_macdata) {
806 memset(macdata, 0, maclen);
807 sfree(macdata);
808 }
809
65a22376 810 for (i = 0; i < 20; i++)
5c72ca61 811 sprintf(realmac + 2 * i, "%02x", binary[i]);
65a22376 812
5c72ca61 813 if (strcmp(mac, realmac)) {
814 /* An incorrect MAC is an unconditional Error if the key is
65a22376 815 * unencrypted. Otherwise, it means Wrong Passphrase. */
222d54dc 816 if (cipher) {
b81cca98 817 error = "wrong passphrase";
222d54dc 818 ret = SSH2_WRONG_PASSPHRASE;
819 } else {
820 error = "MAC failed";
821 ret = NULL;
822 }
65a22376 823 goto error;
824 }
825 }
5c72ca61 826 sfree(mac);
65a22376 827
828 /*
829 * Create and return the key.
830 */
3d88e64d 831 ret = snew(struct ssh2_userkey);
65a22376 832 ret->alg = alg;
833 ret->comment = comment;
834 ret->data = alg->createkey(public_blob, public_blob_len,
835 private_blob, private_blob_len);
98f022f5 836 if (!ret->data) {
837 sfree(ret->comment);
838 sfree(ret);
839 ret = NULL;
222d54dc 840 error = "createkey failed";
841 goto error;
98f022f5 842 }
65a22376 843 sfree(public_blob);
844 sfree(private_blob);
7bedb13c 845 sfree(encryption);
2d8cd396 846 if (errorstr)
847 *errorstr = NULL;
65a22376 848 return ret;
849
850 /*
851 * Error processing.
852 */
32874aea 853 error:
854 if (fp)
855 fclose(fp);
856 if (comment)
857 sfree(comment);
7bedb13c 858 if (encryption)
859 sfree(encryption);
5c72ca61 860 if (mac)
861 sfree(mac);
32874aea 862 if (public_blob)
863 sfree(public_blob);
864 if (private_blob)
865 sfree(private_blob);
222d54dc 866 if (errorstr)
867 *errorstr = error;
65a22376 868 return ret;
869}
870
9a30e26b 871char *ssh2_userkey_loadpub(const Filename *filename, char **algorithm,
06897bd7 872 int *pub_blob_len, char **commentptr,
873 const char **errorstr)
32874aea 874{
65a22376 875 FILE *fp;
876 char header[40], *b;
877 const struct ssh_signkey *alg;
65a22376 878 unsigned char *public_blob;
879 int public_blob_len;
880 int i;
222d54dc 881 const char *error = NULL;
06897bd7 882 char *comment;
65a22376 883
884 public_blob = NULL;
885
9a30e26b 886 fp = f_open(*filename, "rb");
222d54dc 887 if (!fp) {
888 error = "can't open file";
65a22376 889 goto error;
222d54dc 890 }
65a22376 891
892 /* Read the first header line which contains the key type. */
32874aea 893 if (!read_header(fp, header)
7bedb13c 894 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
222d54dc 895 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
896 error = "not a PuTTY SSH-2 private key";
65a22376 897 goto error;
222d54dc 898 }
899 error = "file format error";
65a22376 900 if ((b = read_body(fp)) == NULL)
901 goto error;
fbc7c9b4 902 /* Select key algorithm structure. */
47a6b94c 903 alg = find_pubkey_alg(b);
904 if (!alg) {
65a22376 905 sfree(b);
906 goto error;
907 }
908 sfree(b);
32874aea 909
65a22376 910 /* Read the Encryption header line. */
32874aea 911 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
65a22376 912 goto error;
913 if ((b = read_body(fp)) == NULL)
914 goto error;
915 sfree(b); /* we don't care */
916
917 /* Read the Comment header line. */
32874aea 918 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
65a22376 919 goto error;
06897bd7 920 if ((comment = read_body(fp)) == NULL)
65a22376 921 goto error;
06897bd7 922
923 if (commentptr)
924 *commentptr = comment;
925 else
926 sfree(comment);
65a22376 927
928 /* Read the Public-Lines header line and the public blob. */
32874aea 929 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
65a22376 930 goto error;
931 if ((b = read_body(fp)) == NULL)
932 goto error;
933 i = atoi(b);
934 sfree(b);
935 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
936 goto error;
937
938 fclose(fp);
3f2d010c 939 if (pub_blob_len)
940 *pub_blob_len = public_blob_len;
941 if (algorithm)
942 *algorithm = alg->name;
2247e107 943 return (char *)public_blob;
65a22376 944
945 /*
946 * Error processing.
947 */
32874aea 948 error:
949 if (fp)
950 fclose(fp);
951 if (public_blob)
952 sfree(public_blob);
222d54dc 953 if (errorstr)
954 *errorstr = error;
65a22376 955 return NULL;
956}
957
9a30e26b 958int ssh2_userkey_encrypted(const Filename *filename, char **commentptr)
32874aea 959{
65a22376 960 FILE *fp;
961 char header[40], *b, *comment;
962 int ret;
963
32874aea 964 if (commentptr)
965 *commentptr = NULL;
65a22376 966
9a30e26b 967 fp = f_open(*filename, "rb");
65a22376 968 if (!fp)
969 return 0;
32874aea 970 if (!read_header(fp, header)
7bedb13c 971 || (0 != strcmp(header, "PuTTY-User-Key-File-2") &&
972 0 != strcmp(header, "PuTTY-User-Key-File-1"))) {
32874aea 973 fclose(fp);
974 return 0;
65a22376 975 }
976 if ((b = read_body(fp)) == NULL) {
32874aea 977 fclose(fp);
978 return 0;
65a22376 979 }
980 sfree(b); /* we don't care about key type here */
981 /* Read the Encryption header line. */
32874aea 982 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
983 fclose(fp);
984 return 0;
65a22376 985 }
986 if ((b = read_body(fp)) == NULL) {
32874aea 987 fclose(fp);
988 return 0;
65a22376 989 }
990
991 /* Read the Comment header line. */
32874aea 992 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
993 fclose(fp);
994 sfree(b);
995 return 1;
65a22376 996 }
997 if ((comment = read_body(fp)) == NULL) {
32874aea 998 fclose(fp);
999 sfree(b);
1000 return 1;
65a22376 1001 }
1002
32874aea 1003 if (commentptr)
1004 *commentptr = comment;
65a22376 1005
1006 fclose(fp);
1007 if (!strcmp(b, "aes256-cbc"))
1008 ret = 1;
1009 else
1010 ret = 0;
1011 sfree(b);
1012 return ret;
1013}
1014
32874aea 1015int base64_lines(int datalen)
1016{
65a22376 1017 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
32874aea 1018 return (datalen + 47) / 48;
65a22376 1019}
1020
96d19bc9 1021void base64_encode(FILE * fp, unsigned char *data, int datalen, int cpl)
32874aea 1022{
65a22376 1023 int linelen = 0;
1024 char out[4];
96d19bc9 1025 int n, i;
65a22376 1026
1027 while (datalen > 0) {
65a22376 1028 n = (datalen < 3 ? datalen : 3);
1029 base64_encode_atom(data, n, out);
1030 data += n;
1031 datalen -= n;
96d19bc9 1032 for (i = 0; i < 4; i++) {
1033 if (linelen >= cpl) {
1034 linelen = 0;
1035 fputc('\n', fp);
1036 }
1037 fputc(out[i], fp);
1038 linelen++;
1039 }
65a22376 1040 }
1041 fputc('\n', fp);
1042}
1043
9a30e26b 1044int ssh2_save_userkey(const Filename *filename, struct ssh2_userkey *key,
32874aea 1045 char *passphrase)
1046{
65a22376 1047 FILE *fp;
1048 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
1049 int pub_blob_len, priv_blob_len, priv_encrypted_len;
1050 int passlen;
1051 int cipherblk;
7bedb13c 1052 int i;
65a22376 1053 char *cipherstr;
5c72ca61 1054 unsigned char priv_mac[20];
65a22376 1055
1056 /*
1057 * Fetch the key component blobs.
1058 */
1059 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
1060 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
1061 if (!pub_blob || !priv_blob) {
1062 sfree(pub_blob);
1063 sfree(priv_blob);
1064 return 0;
1065 }
1066
1067 /*
1068 * Determine encryption details, and encrypt the private blob.
1069 */
1070 if (passphrase) {
1071 cipherstr = "aes256-cbc";
1072 cipherblk = 16;
1073 } else {
1074 cipherstr = "none";
1075 cipherblk = 1;
1076 }
1077 priv_encrypted_len = priv_blob_len + cipherblk - 1;
1078 priv_encrypted_len -= priv_encrypted_len % cipherblk;
3d88e64d 1079 priv_blob_encrypted = snewn(priv_encrypted_len, unsigned char);
65a22376 1080 memset(priv_blob_encrypted, 0, priv_encrypted_len);
1081 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
1082 /* Create padding based on the SHA hash of the unpadded blob. This prevents
1083 * too easy a known-plaintext attack on the last block. */
5c72ca61 1084 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
65a22376 1085 assert(priv_encrypted_len - priv_blob_len < 20);
5c72ca61 1086 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
65a22376 1087 priv_encrypted_len - priv_blob_len);
1088
7bedb13c 1089 /* Now create the MAC. */
1090 {
1091 unsigned char *macdata;
1092 int maclen;
1093 unsigned char *p;
1094 int namelen = strlen(key->alg->name);
1095 int enclen = strlen(cipherstr);
1096 int commlen = strlen(key->comment);
5c72ca61 1097 SHA_State s;
1098 unsigned char mackey[20];
1099 char header[] = "putty-private-key-file-mac-key";
1100
7bedb13c 1101 maclen = (4 + namelen +
1102 4 + enclen +
1103 4 + commlen +
1104 4 + pub_blob_len +
1105 4 + priv_encrypted_len);
3d88e64d 1106 macdata = snewn(maclen, unsigned char);
7bedb13c 1107 p = macdata;
1108#define DO_STR(s,len) PUT_32BIT(p,(len));memcpy(p+4,(s),(len));p+=4+(len)
1109 DO_STR(key->alg->name, namelen);
1110 DO_STR(cipherstr, enclen);
1111 DO_STR(key->comment, commlen);
1112 DO_STR(pub_blob, pub_blob_len);
1113 DO_STR(priv_blob_encrypted, priv_encrypted_len);
5c72ca61 1114
1115 SHA_Init(&s);
1116 SHA_Bytes(&s, header, sizeof(header)-1);
7bedb13c 1117 if (passphrase)
1118 SHA_Bytes(&s, passphrase, strlen(passphrase));
5c72ca61 1119 SHA_Final(&s, mackey);
7bedb13c 1120 hmac_sha1_simple(mackey, 20, macdata, maclen, priv_mac);
1121 memset(macdata, 0, maclen);
1122 sfree(macdata);
5c72ca61 1123 memset(mackey, 0, sizeof(mackey));
1124 memset(&s, 0, sizeof(s));
5c72ca61 1125 }
65a22376 1126
1127 if (passphrase) {
2247e107 1128 unsigned char key[40];
65a22376 1129 SHA_State s;
1130
1131 passlen = strlen(passphrase);
1132
1133 SHA_Init(&s);
1134 SHA_Bytes(&s, "\0\0\0\0", 4);
1135 SHA_Bytes(&s, passphrase, passlen);
32874aea 1136 SHA_Final(&s, key + 0);
65a22376 1137 SHA_Init(&s);
1138 SHA_Bytes(&s, "\0\0\0\1", 4);
1139 SHA_Bytes(&s, passphrase, passlen);
32874aea 1140 SHA_Final(&s, key + 20);
1141 aes256_encrypt_pubkey(key, priv_blob_encrypted,
1142 priv_encrypted_len);
5c72ca61 1143
1144 memset(key, 0, sizeof(key));
1145 memset(&s, 0, sizeof(s));
65a22376 1146 }
1147
9a30e26b 1148 fp = f_open(*filename, "w");
65a22376 1149 if (!fp)
1150 return 0;
7bedb13c 1151 fprintf(fp, "PuTTY-User-Key-File-2: %s\n", key->alg->name);
65a22376 1152 fprintf(fp, "Encryption: %s\n", cipherstr);
1153 fprintf(fp, "Comment: %s\n", key->comment);
1154 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
96d19bc9 1155 base64_encode(fp, pub_blob, pub_blob_len, 64);
65a22376 1156 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
96d19bc9 1157 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len, 64);
7bedb13c 1158 fprintf(fp, "Private-MAC: ");
65a22376 1159 for (i = 0; i < 20; i++)
5c72ca61 1160 fprintf(fp, "%02x", priv_mac[i]);
65a22376 1161 fprintf(fp, "\n");
1162 fclose(fp);
7bedb13c 1163
1164 sfree(pub_blob);
1165 memset(priv_blob, 0, priv_blob_len);
1166 sfree(priv_blob);
1167 sfree(priv_blob_encrypted);
65a22376 1168 return 1;
1169}
1170
1171/* ----------------------------------------------------------------------
231ee168 1172 * A function to determine the type of a private key file. Returns
1173 * 0 on failure, 1 or 2 on success.
65a22376 1174 */
9a30e26b 1175int key_type(const Filename *filename)
32874aea 1176{
65a22376 1177 FILE *fp;
231ee168 1178 char buf[32];
1179 const char putty2_sig[] = "PuTTY-User-Key-File-";
1180 const char sshcom_sig[] = "---- BEGIN SSH2 ENCRYPTED PRIVAT";
1181 const char openssh_sig[] = "-----BEGIN ";
65a22376 1182 int i;
1183
9a30e26b 1184 fp = f_open(*filename, "r");
65a22376 1185 if (!fp)
231ee168 1186 return SSH_KEYTYPE_UNOPENABLE;
1187 i = fread(buf, 1, sizeof(buf), fp);
65a22376 1188 fclose(fp);
231ee168 1189 if (i < 0)
1190 return SSH_KEYTYPE_UNOPENABLE;
1191 if (i < 32)
1192 return SSH_KEYTYPE_UNKNOWN;
1193 if (!memcmp(buf, rsa_signature, sizeof(rsa_signature)-1))
1194 return SSH_KEYTYPE_SSH1;
1195 if (!memcmp(buf, putty2_sig, sizeof(putty2_sig)-1))
1196 return SSH_KEYTYPE_SSH2;
1197 if (!memcmp(buf, openssh_sig, sizeof(openssh_sig)-1))
1198 return SSH_KEYTYPE_OPENSSH;
1199 if (!memcmp(buf, sshcom_sig, sizeof(sshcom_sig)-1))
1200 return SSH_KEYTYPE_SSHCOM;
1201 return SSH_KEYTYPE_UNKNOWN; /* unrecognised or EOF */
1202}
1203
1204/*
1205 * Convert the type word to a string, for `wrong type' error
1206 * messages.
1207 */
1208char *key_type_to_str(int type)
1209{
1210 switch (type) {
1211 case SSH_KEYTYPE_UNOPENABLE: return "unable to open file"; break;
1212 case SSH_KEYTYPE_UNKNOWN: return "not a private key"; break;
2e85c969 1213 case SSH_KEYTYPE_SSH1: return "SSH-1 private key"; break;
1214 case SSH_KEYTYPE_SSH2: return "PuTTY SSH-2 private key"; break;
1215 case SSH_KEYTYPE_OPENSSH: return "OpenSSH SSH-2 private key"; break;
1216 case SSH_KEYTYPE_SSHCOM: return "ssh.com SSH-2 private key"; break;
231ee168 1217 default: return "INTERNAL ERROR"; break;
1218 }
65a22376 1219}