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