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