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