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