Oops - fix another segfault in that -L and -R code
[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
3eca8453 12#include "ssh.h"
13
6e522441 14#define PUT_32BIT(cp, value) do { \
15 (cp)[3] = (value); \
16 (cp)[2] = (value) >> 8; \
17 (cp)[1] = (value) >> 16; \
18 (cp)[0] = (value) >> 24; } while (0)
19
3eca8453 20#define GET_32BIT(cp) \
21 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
22 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
23 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
24 ((unsigned long)(unsigned char)(cp)[3]))
25
26#define rsa_signature "SSH PRIVATE KEY FILE FORMAT 1.1\n"
27
a52f067e 28#define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
29 (x)-'a'<26 ? (x)-'a'+26 :\
30 (x)-'0'<10 ? (x)-'0'+52 :\
31 (x)=='+' ? 62 : \
32 (x)=='/' ? 63 : 0 )
33
32874aea 34static int loadrsakey_main(FILE * fp, struct RSAKey *key,
35 char **commentptr, char *passphrase)
36{
3eca8453 37 unsigned char buf[16384];
38 unsigned char keybuf[16];
39 int len;
40 int i, j, ciphertype;
41 int ret = 0;
42 struct MD5Context md5c;
a52f067e 43 char *comment;
3eca8453 44
a52f067e 45 /* Slurp the whole file (minus the header) into a buffer. */
3eca8453 46 len = fread(buf, 1, sizeof(buf), fp);
47 fclose(fp);
48 if (len < 0 || len == sizeof(buf))
32874aea 49 goto end; /* file too big or not read */
3eca8453 50
a52f067e 51 i = 0;
3eca8453 52
a52f067e 53 /*
54 * A zero byte. (The signature includes a terminating NUL.)
55 */
32874aea 56 if (len - i < 1 || buf[i] != 0)
57 goto end;
a52f067e 58 i++;
3eca8453 59
a52f067e 60 /* One byte giving encryption type, and one reserved uint32. */
32874aea 61 if (len - i < 1)
62 goto end;
3eca8453 63 ciphertype = buf[i];
64 if (ciphertype != 0 && ciphertype != SSH_CIPHER_3DES)
32874aea 65 goto end;
3eca8453 66 i++;
32874aea 67 if (len - i < 4)
68 goto end; /* reserved field not present */
69 if (buf[i] != 0 || buf[i + 1] != 0 || buf[i + 2] != 0
70 || buf[i + 3] != 0) goto end; /* reserved field nonzero, panic! */
3eca8453 71 i += 4;
72
73 /* Now the serious stuff. An ordinary SSH 1 public key. */
32874aea 74 i += makekey(buf + i, key, NULL, 1);
75 if (len - i < 0)
76 goto end; /* overran */
3eca8453 77
78 /* Next, the comment field. */
32874aea 79 j = GET_32BIT(buf + i);
5c58ad2d 80 i += 4;
32874aea 81 if (len - i < j)
82 goto end;
83 comment = smalloc(j + 1);
a52f067e 84 if (comment) {
32874aea 85 memcpy(comment, buf + i, j);
86 comment[j] = '\0';
5c58ad2d 87 }
88 i += j;
a52f067e 89 if (commentptr)
32874aea 90 *commentptr = comment;
a52f067e 91 if (key)
32874aea 92 key->comment = comment;
a52f067e 93 if (!key) {
32874aea 94 return ciphertype != 0;
a52f067e 95 }
3eca8453 96
97 /*
98 * Decrypt remainder of buffer.
99 */
100 if (ciphertype) {
32874aea 101 MD5Init(&md5c);
102 MD5Update(&md5c, passphrase, strlen(passphrase));
103 MD5Final(keybuf, &md5c);
104 des3_decrypt_pubkey(keybuf, buf + i, (len - i + 7) & ~7);
105 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
3eca8453 106 }
107
108 /*
109 * We are now in the secret part of the key. The first four
110 * bytes should be of the form a, b, a, b.
111 */
32874aea 112 if (len - i < 4)
113 goto end;
114 if (buf[i] != buf[i + 2] || buf[i + 1] != buf[i + 3]) {
115 ret = -1;
116 goto end;
117 }
3eca8453 118 i += 4;
119
120 /*
121 * After that, we have one further bignum which is our
6e522441 122 * decryption exponent, and then the three auxiliary values
123 * (iqmp, q, p).
3eca8453 124 */
32874aea 125 i += makeprivate(buf + i, key);
126 if (len - i < 0)
127 goto end;
128 i += ssh1_read_bignum(buf + i, &key->iqmp);
129 if (len - i < 0)
130 goto end;
131 i += ssh1_read_bignum(buf + i, &key->q);
132 if (len - i < 0)
133 goto end;
134 i += ssh1_read_bignum(buf + i, &key->p);
135 if (len - i < 0)
136 goto end;
3eca8453 137
98f022f5 138 if (!rsa_verify(key)) {
139 freersakey(key);
140 ret = 0;
141 } else
142 ret = 1;
143
32874aea 144 end:
3eca8453 145 memset(buf, 0, sizeof(buf)); /* burn the evidence */
146 return ret;
147}
148
32874aea 149int loadrsakey(char *filename, struct RSAKey *key, char *passphrase)
150{
3eca8453 151 FILE *fp;
a52f067e 152 unsigned char buf[64];
3eca8453 153
154 fp = fopen(filename, "rb");
155 if (!fp)
32874aea 156 return 0; /* doesn't even exist */
3eca8453 157
a52f067e 158 /*
159 * Read the first line of the file and see if it's a v1 private
160 * key file.
161 */
32874aea 162 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
163 return loadrsakey_main(fp, key, NULL, passphrase);
a52f067e 164 }
165
166 /*
167 * Otherwise, we have nothing. Return empty-handed.
168 */
3eca8453 169 fclose(fp);
3eca8453 170 return 0;
171}
a52f067e 172
173/*
174 * See whether an RSA key is encrypted. Return its comment field as
175 * well.
176 */
32874aea 177int rsakey_encrypted(char *filename, char **comment)
178{
a52f067e 179 FILE *fp;
180 unsigned char buf[64];
181
182 fp = fopen(filename, "rb");
183 if (!fp)
32874aea 184 return 0; /* doesn't even exist */
a52f067e 185
186 /*
187 * Read the first line of the file and see if it's a v1 private
188 * key file.
189 */
32874aea 190 if (fgets(buf, sizeof(buf), fp) && !strcmp(buf, rsa_signature)) {
191 return loadrsakey_main(fp, NULL, comment, NULL);
a52f067e 192 }
404f728b 193 fclose(fp);
32874aea 194 return 0; /* wasn't the right kind of file */
a52f067e 195}
6e522441 196
197/*
198 * Save an RSA key file. Return nonzero on success.
199 */
32874aea 200int saversakey(char *filename, struct RSAKey *key, char *passphrase)
201{
6e522441 202 unsigned char buf[16384];
203 unsigned char keybuf[16];
204 struct MD5Context md5c;
49bad831 205 unsigned char *p, *estart;
6e522441 206 FILE *fp;
207
208 /*
209 * Write the initial signature.
210 */
211 p = buf;
212 memcpy(p, rsa_signature, sizeof(rsa_signature));
213 p += sizeof(rsa_signature);
214
215 /*
216 * One byte giving encryption type, and one reserved (zero)
217 * uint32.
218 */
219 *p++ = (passphrase ? SSH_CIPHER_3DES : 0);
32874aea 220 PUT_32BIT(p, 0);
221 p += 4;
6e522441 222
223 /*
224 * An ordinary SSH 1 public key consists of: a uint32
225 * containing the bit count, then two bignums containing the
226 * modulus and exponent respectively.
227 */
32874aea 228 PUT_32BIT(p, bignum_bitcount(key->modulus));
229 p += 4;
6e522441 230 p += ssh1_write_bignum(p, key->modulus);
231 p += ssh1_write_bignum(p, key->exponent);
232
233 /*
234 * A string containing the comment field.
235 */
236 if (key->comment) {
32874aea 237 PUT_32BIT(p, strlen(key->comment));
238 p += 4;
239 memcpy(p, key->comment, strlen(key->comment));
240 p += strlen(key->comment);
6e522441 241 } else {
32874aea 242 PUT_32BIT(p, 0);
243 p += 4;
6e522441 244 }
245
246 /*
247 * The encrypted portion starts here.
248 */
249 estart = p;
250
251 /*
252 * Two bytes, then the same two bytes repeated.
253 */
254 *p++ = random_byte();
255 *p++ = random_byte();
32874aea 256 p[0] = p[-2];
257 p[1] = p[-1];
258 p += 2;
6e522441 259
260 /*
261 * Four more bignums: the decryption exponent, then iqmp, then
262 * q, then p.
263 */
264 p += ssh1_write_bignum(p, key->private_exponent);
65a22376 265 p += ssh1_write_bignum(p, key->iqmp);
266 p += ssh1_write_bignum(p, key->q);
267 p += ssh1_write_bignum(p, key->p);
6e522441 268
269 /*
270 * Now write zeros until the encrypted portion is a multiple of
271 * 8 bytes.
272 */
32874aea 273 while ((p - estart) % 8)
274 *p++ = '\0';
6e522441 275
276 /*
277 * Now encrypt the encrypted portion.
278 */
279 if (passphrase) {
32874aea 280 MD5Init(&md5c);
281 MD5Update(&md5c, passphrase, strlen(passphrase));
282 MD5Final(keybuf, &md5c);
283 des3_encrypt_pubkey(keybuf, estart, p - estart);
284 memset(keybuf, 0, sizeof(keybuf)); /* burn the evidence */
6e522441 285 }
286
287 /*
288 * Done. Write the result to the file.
289 */
290 fp = fopen(filename, "wb");
291 if (fp) {
32874aea 292 int ret = (fwrite(buf, 1, p - buf, fp) == (size_t) (p - buf));
293 ret = ret && (fclose(fp) == 0);
294 return ret;
6e522441 295 } else
32874aea 296 return 0;
6e522441 297}
65a22376 298
299/* ----------------------------------------------------------------------
300 * SSH2 private key load/store functions.
301 */
302
303/*
304 * PuTTY's own format for SSH2 keys is as follows:
5c72ca61 305 *
65a22376 306 * The file is text. Lines are terminated by CRLF, although CR-only
307 * and LF-only are tolerated on input.
5c72ca61 308 *
65a22376 309 * The first line says "PuTTY-User-Key-File-1: " plus the name of the
5c72ca61 310 * algorithm ("ssh-dss", "ssh-rsa" etc).
311 *
65a22376 312 * The next line says "Encryption: " plus an encryption type.
313 * Currently the only supported encryption types are "aes256-cbc"
314 * and "none".
5c72ca61 315 *
65a22376 316 * The next line says "Comment: " plus the comment string.
5c72ca61 317 *
65a22376 318 * Next there is a line saying "Public-Lines: " plus a number N.
319 * The following N lines contain a base64 encoding of the public
320 * part of the key. This is encoded as the standard SSH2 public key
321 * blob (with no initial length): so for RSA, for example, it will
322 * read
5c72ca61 323 *
65a22376 324 * string "ssh-rsa"
325 * mpint exponent
326 * mpint modulus
5c72ca61 327 *
65a22376 328 * Next, there is a line saying "Private-Lines: " plus a number N,
329 * and then N lines containing the (potentially encrypted) private
330 * part of the key. For the key type "ssh-rsa", this will be
331 * composed of
5c72ca61 332 *
65a22376 333 * mpint private_exponent
334 * mpint p (the larger of the two primes)
335 * mpint q (the smaller prime)
336 * mpint iqmp (the inverse of q modulo p)
337 * data padding (to reach a multiple of the cipher block size)
5c72ca61 338 *
339 * And for "ssh-dss", it will be composed of
340 *
341 * mpint x (the private key parameter)
342 * string hash (20-byte hash of mpints p || q || g)
343 *
344 * Finally, there is a line saying _either_
345 *
346 * - "Private-Hash: " plus a hex representation of a SHA-1 hash of
347 * the plaintext version of the private part, including the
348 * final padding.
349 *
350 * or
351 *
352 * - "Private-MAC: " plus a hex representation of a HMAC-SHA-1 of
353 * the plaintext version of the private part, including the
354 * final padding.
65a22376 355 *
5c72ca61 356 * The key to the MAC is itself a SHA-1 hash of:
65a22376 357 *
5c72ca61 358 * data "putty-private-key-file-mac-key"
359 * data passphrase
360 *
361 * Encrypted keys should have a MAC, whereas unencrypted ones must
362 * have a hash.
363 *
65a22376 364 * If the key is encrypted, the encryption key is derived from the
365 * passphrase by means of a succession of SHA-1 hashes. Each hash
366 * is the hash of:
5c72ca61 367 *
65a22376 368 * uint32 sequence-number
5c72ca61 369 * data passphrase
370 *
65a22376 371 * where the sequence-number increases from zero. As many of these
372 * hashes are used as necessary.
5c72ca61 373 *
98f022f5 374 * NOTE! It is important that all _public_ data can be verified
375 * with reference to the _private_ data. There exist attacks based
376 * on modifying the public key but leaving the private section
377 * intact.
5c72ca61 378 *
98f022f5 379 * With RSA, this is easy: verify that n = p*q, and also verify
5c72ca61 380 * that e*d == 1 modulo (p-1)(q-1). With DSA, we need to store
381 * extra data in the private section other than just x, namely a
382 * hash of p||q||g. (It's then easy to verify that y is equal to
383 * g^x mod p.)
65a22376 384 */
385
32874aea 386static int read_header(FILE * fp, char *header)
387{
65a22376 388 int len = 39;
389 int c;
390
391 while (len > 0) {
392 c = fgetc(fp);
393 if (c == '\n' || c == '\r' || c == EOF)
394 return 0; /* failure */
395 if (c == ':') {
396 c = fgetc(fp);
397 if (c != ' ')
398 return 0;
399 *header = '\0';
400 return 1; /* success! */
401 }
402 if (len == 0)
403 return 0; /* failure */
404 *header++ = c;
405 len--;
406 }
407 return 0; /* failure */
408}
409
32874aea 410static char *read_body(FILE * fp)
411{
65a22376 412 char *text;
413 int len;
414 int size;
415 int c;
416
417 size = 128;
418 text = smalloc(size);
419 len = 0;
420 text[len] = '\0';
421
422 while (1) {
423 c = fgetc(fp);
424 if (c == '\r' || c == '\n') {
425 c = fgetc(fp);
426 if (c != '\r' && c != '\n' && c != EOF)
427 ungetc(c, fp);
428 return text;
429 }
430 if (c == EOF) {
431 sfree(text);
432 return NULL;
433 }
434 if (len + 1 > size) {
435 size += 128;
436 text = srealloc(text, size);
437 }
438 text[len++] = c;
439 text[len] = '\0';
440 }
441}
442
32874aea 443int base64_decode_atom(char *atom, unsigned char *out)
444{
65a22376 445 int vals[4];
446 int i, v, len;
447 unsigned word;
448 char c;
32874aea 449
65a22376 450 for (i = 0; i < 4; i++) {
451 c = atom[i];
452 if (c >= 'A' && c <= 'Z')
453 v = c - 'A';
454 else if (c >= 'a' && c <= 'z')
455 v = c - 'a' + 26;
456 else if (c >= '0' && c <= '9')
457 v = c - '0' + 52;
458 else if (c == '+')
459 v = 62;
460 else if (c == '/')
461 v = 63;
462 else if (c == '=')
463 v = -1;
464 else
465 return 0; /* invalid atom */
466 vals[i] = v;
467 }
468
469 if (vals[0] == -1 || vals[1] == -1)
470 return 0;
471 if (vals[2] == -1 && vals[3] != -1)
472 return 0;
473
474 if (vals[3] != -1)
475 len = 3;
476 else if (vals[2] != -1)
477 len = 2;
478 else
479 len = 1;
480
481 word = ((vals[0] << 18) |
32874aea 482 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
65a22376 483 out[0] = (word >> 16) & 0xFF;
484 if (len > 1)
485 out[1] = (word >> 8) & 0xFF;
486 if (len > 2)
487 out[2] = word & 0xFF;
488 return len;
489}
490
32874aea 491static char *read_blob(FILE * fp, int nlines, int *bloblen)
492{
65a22376 493 unsigned char *blob;
494 char *line;
495 int linelen, len;
496 int i, j, k;
497
498 /* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
499 blob = smalloc(48 * nlines);
500 len = 0;
501 for (i = 0; i < nlines; i++) {
502 line = read_body(fp);
503 if (!line) {
504 sfree(blob);
505 return NULL;
506 }
507 linelen = strlen(line);
508 if (linelen % 4 != 0 || linelen > 64) {
509 sfree(blob);
510 sfree(line);
511 return NULL;
512 }
513 for (j = 0; j < linelen; j += 4) {
32874aea 514 k = base64_decode_atom(line + j, blob + len);
65a22376 515 if (!k) {
516 sfree(line);
517 sfree(blob);
518 return NULL;
519 }
520 len += k;
521 }
522 sfree(line);
523 }
524 *bloblen = len;
525 return blob;
526}
527
528/*
529 * Magic error return value for when the passphrase is wrong.
530 */
531struct ssh2_userkey ssh2_wrong_passphrase = {
532 NULL, NULL, NULL
533};
534
32874aea 535struct ssh2_userkey *ssh2_load_userkey(char *filename, char *passphrase)
536{
65a22376 537 FILE *fp;
5c72ca61 538 char header[40], *b, *comment, *mac;
65a22376 539 const struct ssh_signkey *alg;
540 struct ssh2_userkey *ret;
541 int cipher, cipherblk;
542 unsigned char *public_blob, *private_blob;
543 int public_blob_len, private_blob_len;
5c72ca61 544 int i, is_mac;
545 int passlen = passphrase ? strlen(passphrase) : 0;
65a22376 546
547 ret = NULL; /* return NULL for most errors */
5c72ca61 548 comment = mac = NULL;
65a22376 549 public_blob = private_blob = NULL;
550
551 fp = fopen(filename, "rb");
552 if (!fp)
553 goto error;
554
555 /* Read the first header line which contains the key type. */
32874aea 556 if (!read_header(fp, header)
557 || 0 != strcmp(header, "PuTTY-User-Key-File-1"))
65a22376 558 goto error;
559 if ((b = read_body(fp)) == NULL)
560 goto error;
5c72ca61 561 /* Select key algorithm structure. */
65a22376 562 if (!strcmp(b, "ssh-rsa"))
563 alg = &ssh_rsa;
5c72ca61 564 else if (!strcmp(b, "ssh-dss"))
565 alg = &ssh_dss;
65a22376 566 else {
567 sfree(b);
568 goto error;
569 }
570 sfree(b);
32874aea 571
65a22376 572 /* Read the Encryption header line. */
32874aea 573 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
65a22376 574 goto error;
575 if ((b = read_body(fp)) == NULL)
576 goto error;
577 if (!strcmp(b, "aes256-cbc")) {
32874aea 578 cipher = 1;
579 cipherblk = 16;
65a22376 580 } else if (!strcmp(b, "none")) {
32874aea 581 cipher = 0;
582 cipherblk = 1;
65a22376 583 } else {
584 sfree(b);
585 goto error;
586 }
587 sfree(b);
588
589 /* Read the Comment header line. */
32874aea 590 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
65a22376 591 goto error;
592 if ((comment = read_body(fp)) == NULL)
593 goto error;
594
595 /* Read the Public-Lines header line and the public blob. */
32874aea 596 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
65a22376 597 goto error;
598 if ((b = read_body(fp)) == NULL)
599 goto error;
600 i = atoi(b);
601 sfree(b);
602 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
603 goto error;
604
605 /* Read the Private-Lines header line and the Private blob. */
32874aea 606 if (!read_header(fp, header) || 0 != strcmp(header, "Private-Lines"))
65a22376 607 goto error;
608 if ((b = read_body(fp)) == NULL)
609 goto error;
610 i = atoi(b);
611 sfree(b);
612 if ((private_blob = read_blob(fp, i, &private_blob_len)) == NULL)
613 goto error;
614
5c72ca61 615 /* Read the Private-MAC or Private-Hash header line. */
616 if (!read_header(fp, header))
65a22376 617 goto error;
5c72ca61 618 if (0 == strcmp(header, "Private-MAC")) {
619 if ((mac = read_body(fp)) == NULL)
620 goto error;
621 is_mac = 1;
622 } else if (0 == strcmp(header, "Private-Hash")) {
623 if ((mac = read_body(fp)) == NULL)
624 goto error;
625 is_mac = 0;
626 } else
65a22376 627 goto error;
628
629 fclose(fp);
630 fp = NULL;
631
632 /*
633 * Decrypt the private blob.
634 */
635 if (cipher) {
636 unsigned char key[40];
637 SHA_State s;
65a22376 638
639 if (!passphrase)
640 goto error;
641 if (private_blob_len % cipherblk)
642 goto error;
643
65a22376 644 SHA_Init(&s);
645 SHA_Bytes(&s, "\0\0\0\0", 4);
646 SHA_Bytes(&s, passphrase, passlen);
32874aea 647 SHA_Final(&s, key + 0);
65a22376 648 SHA_Init(&s);
649 SHA_Bytes(&s, "\0\0\0\1", 4);
650 SHA_Bytes(&s, passphrase, passlen);
32874aea 651 SHA_Final(&s, key + 20);
65a22376 652 aes256_decrypt_pubkey(key, private_blob, private_blob_len);
653 }
654
655 /*
656 * Verify the private hash.
657 */
658 {
5c72ca61 659 char realmac[41];
65a22376 660 unsigned char binary[20];
65a22376 661
5c72ca61 662 if (is_mac) {
663 SHA_State s;
664 unsigned char mackey[20];
665 char header[] = "putty-private-key-file-mac-key";
666
667 if (!passphrase) /* can't have MAC in unencrypted key */
668 goto error;
669
670 SHA_Init(&s);
671 SHA_Bytes(&s, header, sizeof(header)-1);
672 SHA_Bytes(&s, passphrase, passlen);
673 SHA_Final(&s, mackey);
674
675 hmac_sha1_simple(mackey, 20, private_blob, private_blob_len,
676 binary);
677
678 memset(mackey, 0, sizeof(mackey));
679 memset(&s, 0, sizeof(s));
680 } else {
681 SHA_Simple(private_blob, private_blob_len, binary);
682 }
65a22376 683 for (i = 0; i < 20; i++)
5c72ca61 684 sprintf(realmac + 2 * i, "%02x", binary[i]);
65a22376 685
5c72ca61 686 if (strcmp(mac, realmac)) {
687 /* An incorrect MAC is an unconditional Error if the key is
65a22376 688 * unencrypted. Otherwise, it means Wrong Passphrase. */
689 ret = cipher ? SSH2_WRONG_PASSPHRASE : NULL;
690 goto error;
691 }
692 }
5c72ca61 693 sfree(mac);
65a22376 694
695 /*
696 * Create and return the key.
697 */
698 ret = smalloc(sizeof(struct ssh2_userkey));
699 ret->alg = alg;
700 ret->comment = comment;
701 ret->data = alg->createkey(public_blob, public_blob_len,
702 private_blob, private_blob_len);
98f022f5 703 if (!ret->data) {
704 sfree(ret->comment);
705 sfree(ret);
706 ret = NULL;
707 }
65a22376 708 sfree(public_blob);
709 sfree(private_blob);
710 return ret;
711
712 /*
713 * Error processing.
714 */
32874aea 715 error:
716 if (fp)
717 fclose(fp);
718 if (comment)
719 sfree(comment);
5c72ca61 720 if (mac)
721 sfree(mac);
32874aea 722 if (public_blob)
723 sfree(public_blob);
724 if (private_blob)
725 sfree(private_blob);
65a22376 726 return ret;
727}
728
32874aea 729char *ssh2_userkey_loadpub(char *filename, char **algorithm,
730 int *pub_blob_len)
731{
65a22376 732 FILE *fp;
733 char header[40], *b;
734 const struct ssh_signkey *alg;
65a22376 735 unsigned char *public_blob;
736 int public_blob_len;
737 int i;
738
739 public_blob = NULL;
740
741 fp = fopen(filename, "rb");
742 if (!fp)
743 goto error;
744
745 /* Read the first header line which contains the key type. */
32874aea 746 if (!read_header(fp, header)
747 || 0 != strcmp(header, "PuTTY-User-Key-File-1"))
65a22376 748 goto error;
749 if ((b = read_body(fp)) == NULL)
750 goto error;
751 /* Select key algorithm structure. Currently only ssh-rsa. */
752 if (!strcmp(b, "ssh-rsa"))
753 alg = &ssh_rsa;
5c72ca61 754 else if (!strcmp(b, "ssh-dss"))
755 alg = &ssh_dss;
65a22376 756 else {
757 sfree(b);
758 goto error;
759 }
760 sfree(b);
32874aea 761
65a22376 762 /* Read the Encryption header line. */
32874aea 763 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption"))
65a22376 764 goto error;
765 if ((b = read_body(fp)) == NULL)
766 goto error;
767 sfree(b); /* we don't care */
768
769 /* Read the Comment header line. */
32874aea 770 if (!read_header(fp, header) || 0 != strcmp(header, "Comment"))
65a22376 771 goto error;
772 if ((b = read_body(fp)) == NULL)
773 goto error;
774 sfree(b); /* we don't care */
775
776 /* Read the Public-Lines header line and the public blob. */
32874aea 777 if (!read_header(fp, header) || 0 != strcmp(header, "Public-Lines"))
65a22376 778 goto error;
779 if ((b = read_body(fp)) == NULL)
780 goto error;
781 i = atoi(b);
782 sfree(b);
783 if ((public_blob = read_blob(fp, i, &public_blob_len)) == NULL)
784 goto error;
785
786 fclose(fp);
787 *pub_blob_len = public_blob_len;
788 *algorithm = alg->name;
789 return public_blob;
790
791 /*
792 * Error processing.
793 */
32874aea 794 error:
795 if (fp)
796 fclose(fp);
797 if (public_blob)
798 sfree(public_blob);
65a22376 799 return NULL;
800}
801
32874aea 802int ssh2_userkey_encrypted(char *filename, char **commentptr)
803{
65a22376 804 FILE *fp;
805 char header[40], *b, *comment;
806 int ret;
807
32874aea 808 if (commentptr)
809 *commentptr = NULL;
65a22376 810
811 fp = fopen(filename, "rb");
812 if (!fp)
813 return 0;
32874aea 814 if (!read_header(fp, header)
815 || 0 != strcmp(header, "PuTTY-User-Key-File-1")) {
816 fclose(fp);
817 return 0;
65a22376 818 }
819 if ((b = read_body(fp)) == NULL) {
32874aea 820 fclose(fp);
821 return 0;
65a22376 822 }
823 sfree(b); /* we don't care about key type here */
824 /* Read the Encryption header line. */
32874aea 825 if (!read_header(fp, header) || 0 != strcmp(header, "Encryption")) {
826 fclose(fp);
827 return 0;
65a22376 828 }
829 if ((b = read_body(fp)) == NULL) {
32874aea 830 fclose(fp);
831 return 0;
65a22376 832 }
833
834 /* Read the Comment header line. */
32874aea 835 if (!read_header(fp, header) || 0 != strcmp(header, "Comment")) {
836 fclose(fp);
837 sfree(b);
838 return 1;
65a22376 839 }
840 if ((comment = read_body(fp)) == NULL) {
32874aea 841 fclose(fp);
842 sfree(b);
843 return 1;
65a22376 844 }
845
32874aea 846 if (commentptr)
847 *commentptr = comment;
65a22376 848
849 fclose(fp);
850 if (!strcmp(b, "aes256-cbc"))
851 ret = 1;
852 else
853 ret = 0;
854 sfree(b);
855 return ret;
856}
857
32874aea 858int base64_lines(int datalen)
859{
65a22376 860 /* When encoding, we use 64 chars/line, which equals 48 real chars. */
32874aea 861 return (datalen + 47) / 48;
65a22376 862}
863
32874aea 864void base64_encode_atom(unsigned char *data, int n, char *out)
865{
65a22376 866 static const char base64_chars[] =
867 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
868
869 unsigned word;
870
871 word = data[0] << 16;
872 if (n > 1)
873 word |= data[1] << 8;
874 if (n > 2)
875 word |= data[2];
876 out[0] = base64_chars[(word >> 18) & 0x3F];
877 out[1] = base64_chars[(word >> 12) & 0x3F];
878 if (n > 1)
879 out[2] = base64_chars[(word >> 6) & 0x3F];
880 else
881 out[2] = '=';
882 if (n > 2)
883 out[3] = base64_chars[word & 0x3F];
884 else
885 out[3] = '=';
886}
887
32874aea 888void base64_encode(FILE * fp, unsigned char *data, int datalen)
889{
65a22376 890 int linelen = 0;
891 char out[4];
892 int n;
893
894 while (datalen > 0) {
895 if (linelen >= 64) {
896 linelen = 0;
897 fputc('\n', fp);
898 }
899 n = (datalen < 3 ? datalen : 3);
900 base64_encode_atom(data, n, out);
901 data += n;
902 datalen -= n;
903 fwrite(out, 1, 4, fp);
904 linelen += 4;
905 }
906 fputc('\n', fp);
907}
908
32874aea 909int ssh2_save_userkey(char *filename, struct ssh2_userkey *key,
910 char *passphrase)
911{
65a22376 912 FILE *fp;
913 unsigned char *pub_blob, *priv_blob, *priv_blob_encrypted;
914 int pub_blob_len, priv_blob_len, priv_encrypted_len;
915 int passlen;
916 int cipherblk;
5c72ca61 917 int i, is_mac;
65a22376 918 char *cipherstr;
5c72ca61 919 unsigned char priv_mac[20];
65a22376 920
921 /*
922 * Fetch the key component blobs.
923 */
924 pub_blob = key->alg->public_blob(key->data, &pub_blob_len);
925 priv_blob = key->alg->private_blob(key->data, &priv_blob_len);
926 if (!pub_blob || !priv_blob) {
927 sfree(pub_blob);
928 sfree(priv_blob);
929 return 0;
930 }
931
932 /*
933 * Determine encryption details, and encrypt the private blob.
934 */
935 if (passphrase) {
936 cipherstr = "aes256-cbc";
937 cipherblk = 16;
938 } else {
939 cipherstr = "none";
940 cipherblk = 1;
941 }
942 priv_encrypted_len = priv_blob_len + cipherblk - 1;
943 priv_encrypted_len -= priv_encrypted_len % cipherblk;
944 priv_blob_encrypted = smalloc(priv_encrypted_len);
945 memset(priv_blob_encrypted, 0, priv_encrypted_len);
946 memcpy(priv_blob_encrypted, priv_blob, priv_blob_len);
947 /* Create padding based on the SHA hash of the unpadded blob. This prevents
948 * too easy a known-plaintext attack on the last block. */
5c72ca61 949 SHA_Simple(priv_blob, priv_blob_len, priv_mac);
65a22376 950 assert(priv_encrypted_len - priv_blob_len < 20);
5c72ca61 951 memcpy(priv_blob_encrypted + priv_blob_len, priv_mac,
65a22376 952 priv_encrypted_len - priv_blob_len);
953
5c72ca61 954 /* Now create the private MAC. */
955 if (passphrase) {
956 SHA_State s;
957 unsigned char mackey[20];
958 char header[] = "putty-private-key-file-mac-key";
959
960 passlen = strlen(passphrase);
961
962 SHA_Init(&s);
963 SHA_Bytes(&s, header, sizeof(header)-1);
964 SHA_Bytes(&s, passphrase, passlen);
965 SHA_Final(&s, mackey);
966
967 hmac_sha1_simple(mackey, 20,
968 priv_blob_encrypted, priv_encrypted_len,
969 priv_mac);
970 is_mac = 1;
971
972 memset(mackey, 0, sizeof(mackey));
973 memset(&s, 0, sizeof(s));
974 } else {
975 SHA_Simple(priv_blob_encrypted, priv_encrypted_len, priv_mac);
976 is_mac = 0;
977 }
65a22376 978
979 if (passphrase) {
980 char key[40];
981 SHA_State s;
982
983 passlen = strlen(passphrase);
984
985 SHA_Init(&s);
986 SHA_Bytes(&s, "\0\0\0\0", 4);
987 SHA_Bytes(&s, passphrase, passlen);
32874aea 988 SHA_Final(&s, key + 0);
65a22376 989 SHA_Init(&s);
990 SHA_Bytes(&s, "\0\0\0\1", 4);
991 SHA_Bytes(&s, passphrase, passlen);
32874aea 992 SHA_Final(&s, key + 20);
993 aes256_encrypt_pubkey(key, priv_blob_encrypted,
994 priv_encrypted_len);
5c72ca61 995
996 memset(key, 0, sizeof(key));
997 memset(&s, 0, sizeof(s));
65a22376 998 }
999
1000 fp = fopen(filename, "w");
1001 if (!fp)
1002 return 0;
1003 fprintf(fp, "PuTTY-User-Key-File-1: %s\n", key->alg->name);
1004 fprintf(fp, "Encryption: %s\n", cipherstr);
1005 fprintf(fp, "Comment: %s\n", key->comment);
1006 fprintf(fp, "Public-Lines: %d\n", base64_lines(pub_blob_len));
1007 base64_encode(fp, pub_blob, pub_blob_len);
1008 fprintf(fp, "Private-Lines: %d\n", base64_lines(priv_encrypted_len));
1009 base64_encode(fp, priv_blob_encrypted, priv_encrypted_len);
5c72ca61 1010 if (is_mac)
1011 fprintf(fp, "Private-MAC: ");
1012 else
1013 fprintf(fp, "Private-Hash: ");
65a22376 1014 for (i = 0; i < 20; i++)
5c72ca61 1015 fprintf(fp, "%02x", priv_mac[i]);
65a22376 1016 fprintf(fp, "\n");
1017 fclose(fp);
1018 return 1;
1019}
1020
1021/* ----------------------------------------------------------------------
1022 * A function to determine which version of SSH to try on a private
1023 * key file. Returns 0 on failure, 1 or 2 on success.
1024 */
32874aea 1025int keyfile_version(char *filename)
1026{
65a22376 1027 FILE *fp;
1028 int i;
1029
1030 fp = fopen(filename, "r");
1031 if (!fp)
1032 return 0;
1033 i = fgetc(fp);
1034 fclose(fp);
1035 if (i == 'S')
1036 return 1; /* "SSH PRIVATE KEY FORMAT" etc */
1037 if (i == 'P') /* "PuTTY-User-Key-File" etc */
1038 return 2;
1039 return 0; /* unrecognised or EOF */
1040}