-
Notifications
You must be signed in to change notification settings - Fork 2
/
sshpubk.c
1967 lines (1731 loc) · 56.6 KB
/
sshpubk.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Generic SSH public-key handling operations. In particular,
* reading of SSH public-key files, and also the generic `sign'
* operation for SSH-2 (which checks the type of the key and
* dispatches to the appropriate key-type specific function).
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include "putty.h"
#include "mpint.h"
#include "ssh.h"
#include "misc.h"
/*
* Fairly arbitrary size limit on any public or private key blob.
* Chosen to match AGENT_MAX_MSGLEN, on the basis that any key too
* large to transfer over the ssh-agent protocol is probably too large
* to be useful in general.
*
* MAX_KEY_BLOB_LINES is the corresponding limit on the Public-Lines
* or Private-Lines header field in a key file.
*/
#define MAX_KEY_BLOB_SIZE 262144
#define MAX_KEY_BLOB_LINES (MAX_KEY_BLOB_SIZE / 48)
/*
* Corresponding limit on the size of a key _file_ itself, based on
* base64-encoding the key blob and then adding a few Kb for
* surrounding metadata.
*/
#define MAX_KEY_FILE_SIZE (MAX_KEY_BLOB_SIZE * 4 / 3 + 4096)
static const ptrlen rsa1_signature =
PTRLEN_DECL_LITERAL("SSH PRIVATE KEY FILE FORMAT 1.1\n\0");
#define BASE64_TOINT(x) ( (x)-'A'<26 ? (x)-'A'+0 :\
(x)-'a'<26 ? (x)-'a'+26 :\
(x)-'0'<10 ? (x)-'0'+52 :\
(x)=='+' ? 62 : \
(x)=='/' ? 63 : 0 )
LoadedFile *lf_new(size_t max_size)
{
LoadedFile *lf = snew_plus(LoadedFile, max_size);
lf->data = snew_plus_get_aux(lf);
lf->len = 0;
lf->max_size = max_size;
return lf;
}
void lf_free(LoadedFile *lf)
{
smemclr(lf->data, lf->max_size);
smemclr(lf, sizeof(LoadedFile));
sfree(lf);
}
LoadFileStatus lf_load_fp(LoadedFile *lf, FILE *fp)
{
lf->len = 0;
while (lf->len < lf->max_size) {
size_t retd = fread(lf->data + lf->len, 1, lf->max_size - lf->len, fp);
if (ferror(fp))
return LF_ERROR;
if (retd == 0)
break;
lf->len += retd;
}
LoadFileStatus status = LF_OK;
if (lf->len == lf->max_size) {
/* The file might be too long to fit in our fixed-size
* structure. Try reading one more byte, to check. */
if (fgetc(fp) != EOF)
status = LF_TOO_BIG;
}
BinarySource_INIT(lf, lf->data, lf->len);
return status;
}
LoadFileStatus lf_load(LoadedFile *lf, const Filename *filename)
{
FILE *fp = f_open(filename, "rb", false);
if (!fp)
return LF_ERROR;
LoadFileStatus status = lf_load_fp(lf, fp);
fclose(fp);
return status;
}
static inline bool lf_load_keyfile_helper(LoadFileStatus status,
const char **errptr)
{
const char *error;
switch (status) {
case LF_OK:
return true;
case LF_TOO_BIG:
error = "file is too large to be a key file";
break;
case LF_ERROR:
error = strerror(errno);
break;
default:
unreachable("bad status value in lf_load_keyfile_helper");
}
if (errptr)
*errptr = error;
return false;
}
LoadedFile *lf_load_keyfile(const Filename *filename, const char **errptr)
{
LoadedFile *lf = lf_new(MAX_KEY_FILE_SIZE);
if (!lf_load_keyfile_helper(lf_load(lf, filename), errptr)) {
lf_free(lf);
return NULL;
}
return lf;
}
LoadedFile *lf_load_keyfile_fp(FILE *fp, const char **errptr)
{
LoadedFile *lf = lf_new(MAX_KEY_FILE_SIZE);
if (!lf_load_keyfile_helper(lf_load_fp(lf, fp), errptr)) {
lf_free(lf);
return NULL;
}
return lf;
}
static bool expect_signature(BinarySource *src, ptrlen realsig)
{
ptrlen thissig = get_data(src, realsig.len);
return !get_err(src) && ptrlen_eq_ptrlen(realsig, thissig);
}
static int rsa1_load_s_internal(BinarySource *src, RSAKey *key, bool pub_only,
char **commentptr, const char *passphrase,
const char **error)
{
strbuf *buf = NULL;
int ciphertype;
int ret = 0;
ptrlen comment;
*error = "not an SSH-1 RSA file";
if (!expect_signature(src, rsa1_signature))
goto end;
*error = "file format error";
/* One byte giving encryption type, and one reserved uint32. */
ciphertype = get_byte(src);
if (ciphertype != 0 && ciphertype != SSH1_CIPHER_3DES)
goto end;
if (get_uint32(src) != 0)
goto end; /* reserved field nonzero, panic! */
/* Now the serious stuff. An ordinary SSH-1 public key. */
get_rsa_ssh1_pub(src, key, RSA_SSH1_MODULUS_FIRST);
/* Next, the comment field. */
comment = get_string(src);
if (commentptr)
*commentptr = mkstr(comment);
if (key)
key->comment = mkstr(comment);
if (pub_only) {
ret = 1;
goto end;
}
if (!key) {
ret = ciphertype != 0;
*error = NULL;
goto end;
}
/*
* Decrypt remainder of buffer.
*/
if (ciphertype) {
size_t enclen = get_avail(src);
if (enclen & 7)
goto end;
buf = strbuf_dup_nm(get_data(src, enclen));
unsigned char keybuf[16];
hash_simple(&ssh_md5, ptrlen_from_asciz(passphrase), keybuf);
des3_decrypt_pubkey(keybuf, buf->u, enclen);
smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(buf));
}
/*
* We are now in the secret part of the key. The first four
* bytes should be of the form a, b, a, b.
*/
{
int b0a = get_byte(src);
int b1a = get_byte(src);
int b0b = get_byte(src);
int b1b = get_byte(src);
if (b0a != b0b || b1a != b1b) {
*error = "wrong passphrase";
ret = -1;
goto end;
}
}
/*
* After that, we have one further bignum which is our
* decryption exponent, and then the three auxiliary values
* (iqmp, q, p).
*/
get_rsa_ssh1_priv(src, key);
key->iqmp = get_mp_ssh1(src);
key->q = get_mp_ssh1(src);
key->p = get_mp_ssh1(src);
if (!rsa_verify(key)) {
*error = "rsa_verify failed";
freersakey(key);
ret = 0;
} else {
*error = NULL;
ret = 1;
}
end:
if (buf)
strbuf_free(buf);
return ret;
}
int rsa1_load_s(BinarySource *src, RSAKey *key,
const char *passphrase, const char **errstr)
{
return rsa1_load_s_internal(src, key, false, NULL, passphrase, errstr);
}
int rsa1_load_f(const Filename *filename, RSAKey *key,
const char *passphrase, const char **errstr)
{
LoadedFile *lf = lf_load_keyfile(filename, errstr);
if (!lf)
return false;
int toret = rsa1_load_s(BinarySource_UPCAST(lf), key, passphrase, errstr);
lf_free(lf);
return toret;
}
/*
* See whether an RSA key is encrypted. Return its comment field as
* well.
*/
bool rsa1_encrypted_s(BinarySource *src, char **comment)
{
const char *dummy;
return rsa1_load_s_internal(src, NULL, false, comment, NULL, &dummy) == 1;
}
bool rsa1_encrypted_f(const Filename *filename, char **comment)
{
LoadedFile *lf = lf_load_keyfile(filename, NULL);
if (!lf)
return false; /* couldn't even open the file */
bool toret = rsa1_encrypted_s(BinarySource_UPCAST(lf), comment);
lf_free(lf);
return toret;
}
/*
* Read the public part of an SSH-1 RSA key from a file (public or
* private), and generate its public blob in exponent-first order.
*/
int rsa1_loadpub_s(BinarySource *src, BinarySink *bs,
char **commentptr, const char **errorstr)
{
RSAKey key;
int ret;
const char *error = NULL;
/* Default return if we fail. */
ret = 0;
bool is_privkey_file = expect_signature(src, rsa1_signature);
BinarySource_REWIND(src);
if (is_privkey_file) {
/*
* Load just the public half from an SSH-1 private key file.
*/
memset(&key, 0, sizeof(key));
if (rsa1_load_s_internal(src, &key, true, commentptr, NULL, &error)) {
rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST);
freersakey(&key);
ret = 1;
}
} else {
/*
* Try interpreting the file as an SSH-1 public key.
*/
char *line, *p, *bitsp, *expp, *modp, *commentp;
line = mkstr(get_chomped_line(src));
p = line;
bitsp = p;
p += strspn(p, "0123456789");
if (*p != ' ')
goto not_public_either;
*p++ = '\0';
expp = p;
p += strspn(p, "0123456789");
if (*p != ' ')
goto not_public_either;
*p++ = '\0';
modp = p;
p += strspn(p, "0123456789");
if (*p) {
if (*p != ' ')
goto not_public_either;
*p++ = '\0';
commentp = p;
} else {
commentp = NULL;
}
memset(&key, 0, sizeof(key));
key.exponent = mp_from_decimal(expp);
key.modulus = mp_from_decimal(modp);
if (atoi(bitsp) != mp_get_nbits(key.modulus)) {
mp_free(key.exponent);
mp_free(key.modulus);
sfree(line);
error = "key bit count does not match in SSH-1 public key file";
goto end;
}
if (commentptr)
*commentptr = commentp ? dupstr(commentp) : NULL;
rsa_ssh1_public_blob(bs, &key, RSA_SSH1_EXPONENT_FIRST);
freersakey(&key);
sfree(line);
return 1;
not_public_either:
sfree(line);
error = "not an SSH-1 RSA file";
}
end:
if ((ret != 1) && errorstr)
*errorstr = error;
return ret;
}
int rsa1_loadpub_f(const Filename *filename, BinarySink *bs,
char **commentptr, const char **errorstr)
{
LoadedFile *lf = lf_load_keyfile(filename, errorstr);
if (!lf)
return 0;
int toret = rsa1_loadpub_s(BinarySource_UPCAST(lf), bs,
commentptr, errorstr);
lf_free(lf);
return toret;
}
strbuf *rsa1_save_sb(RSAKey *key, const char *passphrase)
{
strbuf *buf = strbuf_new_nm();
int estart;
/*
* The public part of the key.
*/
put_datapl(buf, rsa1_signature);
put_byte(buf, passphrase ? SSH1_CIPHER_3DES : 0); /* encryption type */
put_uint32(buf, 0); /* reserved */
rsa_ssh1_public_blob(BinarySink_UPCAST(buf), key,
RSA_SSH1_MODULUS_FIRST);
put_stringz(buf, NULLTOEMPTY(key->comment));
/*
* The encrypted portion starts here.
*/
estart = buf->len;
/*
* Two bytes, then the same two bytes repeated.
*/
{
uint8_t bytes[2];
random_read(bytes, 2);
put_data(buf, bytes, 2);
put_data(buf, bytes, 2);
}
/*
* Four more bignums: the decryption exponent, then iqmp, then
* q, then p.
*/
put_mp_ssh1(buf, key->private_exponent);
put_mp_ssh1(buf, key->iqmp);
put_mp_ssh1(buf, key->q);
put_mp_ssh1(buf, key->p);
/*
* Now write zeros until the encrypted portion is a multiple of
* 8 bytes.
*/
put_padding(buf, (estart - buf->len) & 7, 0);
/*
* Now encrypt the encrypted portion.
*/
if (passphrase) {
unsigned char keybuf[16];
hash_simple(&ssh_md5, ptrlen_from_asciz(passphrase), keybuf);
des3_encrypt_pubkey(keybuf, buf->u + estart, buf->len - estart);
smemclr(keybuf, sizeof(keybuf)); /* burn the evidence */
}
return buf;
}
/*
* Save an RSA key file. Return true on success.
*/
bool rsa1_save_f(const Filename *filename, RSAKey *key, const char *passphrase)
{
FILE *fp = f_open(filename, "wb", true);
if (!fp)
return false;
strbuf *buf = rsa1_save_sb(key, passphrase);
bool toret = fwrite(buf->s, 1, buf->len, fp) == buf->len;
if (fclose(fp))
toret = false;
strbuf_free(buf);
return toret;
}
/* ----------------------------------------------------------------------
* SSH-2 private key load/store functions.
*
* PuTTY's own file format for SSH-2 keys is given in doc/ppk.but, aka
* the "PPK file format" appendix in the PuTTY manual.
*/
static bool read_header(BinarySource *src, char *header)
{
int len = 39;
int c;
while (1) {
c = get_byte(src);
if (c == '\n' || c == '\r' || get_err(src))
return false; /* failure */
if (c == ':') {
c = get_byte(src);
if (c != ' ')
return false;
*header = '\0';
return true; /* success! */
}
if (len == 0)
return false; /* failure */
*header++ = c;
len--;
}
return false; /* failure */
}
static char *read_body(BinarySource *src)
{
strbuf *buf = strbuf_new_nm();
while (1) {
int c = get_byte(src);
if (c == '\r' || c == '\n' || get_err(src)) {
if (!get_err(src)) {
c = get_byte(src);
if (c != '\r' && c != '\n' && !get_err(src))
src->pos--;
}
return strbuf_to_str(buf);
}
put_byte(buf, c);
}
}
static bool read_blob(BinarySource *src, int nlines, BinarySink *bs)
{
char *line;
int linelen;
int i, j, k;
/* We expect at most 64 base64 characters, ie 48 real bytes, per line. */
for (i = 0; i < nlines; i++) {
line = read_body(src);
if (!line)
return false;
linelen = strlen(line);
if (linelen % 4 != 0 || linelen > 64) {
sfree(line);
return false;
}
for (j = 0; j < linelen; j += 4) {
unsigned char decoded[3];
k = base64_decode_atom(line + j, decoded);
if (!k) {
sfree(line);
return false;
}
put_data(bs, decoded, k);
}
sfree(line);
}
return true;
}
/*
* Magic error return value for when the passphrase is wrong.
*/
ssh2_userkey ssh2_wrong_passphrase = { NULL, NULL };
const ssh_keyalg *const all_keyalgs[] = {
&ssh_rsa,
&ssh_rsa_sha256,
&ssh_rsa_sha512,
&ssh_dsa,
&ssh_ecdsa_nistp256,
&ssh_ecdsa_nistp384,
&ssh_ecdsa_nistp521,
&ssh_ecdsa_ed25519,
&ssh_ecdsa_ed448,
&opensshcert_ssh_dsa,
&opensshcert_ssh_rsa,
&opensshcert_ssh_rsa_sha256,
&opensshcert_ssh_rsa_sha512,
&opensshcert_ssh_ecdsa_ed25519,
&opensshcert_ssh_ecdsa_nistp256,
&opensshcert_ssh_ecdsa_nistp384,
&opensshcert_ssh_ecdsa_nistp521,
};
const size_t n_keyalgs = lenof(all_keyalgs);
const ssh_keyalg *find_pubkey_alg_len(ptrlen name)
{
for (size_t i = 0; i < n_keyalgs; i++)
if (ptrlen_eq_string(name, all_keyalgs[i]->ssh_id))
return all_keyalgs[i];
return NULL;
}
const ssh_keyalg *find_pubkey_alg(const char *name)
{
return find_pubkey_alg_len(ptrlen_from_asciz(name));
}
ptrlen pubkey_blob_to_alg_name(ptrlen blob)
{
BinarySource src[1];
BinarySource_BARE_INIT_PL(src, blob);
return get_string(src);
}
const ssh_keyalg *pubkey_blob_to_alg(ptrlen blob)
{
return find_pubkey_alg_len(pubkey_blob_to_alg_name(blob));
}
struct ppk_cipher {
const char *name;
size_t blocklen, keylen, ivlen;
};
static const struct ppk_cipher ppk_cipher_none = { "none", 1, 0, 0 };
static const struct ppk_cipher ppk_cipher_aes256_cbc = { "aes256-cbc", 16, 32, 16 };
static void ssh2_ppk_derive_keys(
unsigned fmt_version, const struct ppk_cipher *ciphertype,
ptrlen passphrase, strbuf *storage, ptrlen *cipherkey, ptrlen *cipheriv,
ptrlen *mackey, ptrlen passphrase_salt, ppk_save_parameters *params)
{
size_t mac_keylen;
switch (fmt_version) {
case 3: {
if (ciphertype->keylen == 0) {
mac_keylen = 0;
break;
}
ptrlen empty = PTRLEN_LITERAL("");
mac_keylen = 32;
uint32_t taglen = ciphertype->keylen + ciphertype->ivlen + mac_keylen;
if (params->argon2_passes_auto) {
uint32_t passes;
argon2_choose_passes(
params->argon2_flavour, params->argon2_mem,
params->argon2_milliseconds, &passes,
params->argon2_parallelism, taglen,
passphrase, passphrase_salt, empty, empty, storage);
params->argon2_passes_auto = false;
params->argon2_passes = passes;
} else {
argon2(params->argon2_flavour, params->argon2_mem,
params->argon2_passes, params->argon2_parallelism, taglen,
passphrase, passphrase_salt, empty, empty, storage);
}
break;
}
case 2:
case 1: {
/* Counter-mode iteration to generate cipher key data. */
for (unsigned ctr = 0; ctr * 20 < ciphertype->keylen; ctr++) {
ssh_hash *h = ssh_hash_new(&ssh_sha1);
put_uint32(h, ctr);
put_datapl(h, passphrase);
ssh_hash_final(h, strbuf_append(storage, 20));
}
strbuf_shrink_to(storage, ciphertype->keylen);
/* In this version of the format, the CBC IV was always all 0. */
put_padding(storage, ciphertype->ivlen, 0);
/* Completely separate hash for the MAC key. */
ssh_hash *h = ssh_hash_new(&ssh_sha1);
mac_keylen = ssh_hash_alg(h)->hlen;
put_datapl(h, PTRLEN_LITERAL("putty-private-key-file-mac-key"));
put_datapl(h, passphrase);
ssh_hash_final(h, strbuf_append(storage, mac_keylen));
break;
}
default:
unreachable("bad format version in ssh2_ppk_derive_keys");
}
BinarySource src[1];
BinarySource_BARE_INIT_PL(src, ptrlen_from_strbuf(storage));
*cipherkey = get_data(src, ciphertype->keylen);
*cipheriv = get_data(src, ciphertype->ivlen);
*mackey = get_data(src, mac_keylen);
}
static int userkey_parse_line_counter(const char *text)
{
char *endptr;
unsigned long ul = strtoul(text, &endptr, 10);
if (*text && !*endptr && ul < MAX_KEY_BLOB_LINES)
return ul;
else
return -1;
}
static bool str_to_uint32_t(const char *s, uint32_t *out)
{
char *endptr;
unsigned long converted = strtoul(s, &endptr, 10);
if (*s && !*endptr && converted <= ~(uint32_t)0) {
*out = converted;
return true;
} else {
return false;
}
}
ssh2_userkey *ppk_load_s(BinarySource *src, const char *passphrase,
const char **errorstr)
{
char header[40], *b, *encryption, *comment, *mac;
const ssh_keyalg *alg;
ssh2_userkey *ret;
strbuf *public_blob, *private_blob, *cipher_mac_keys_blob;
strbuf *passphrase_salt = strbuf_new();
ptrlen cipherkey, cipheriv, mackey;
const struct ppk_cipher *ciphertype;
int i;
bool is_mac;
unsigned fmt_version;
const char *error = NULL;
ppk_save_parameters params;
ret = NULL; /* return NULL for most errors */
encryption = comment = mac = NULL;
public_blob = private_blob = cipher_mac_keys_blob = NULL;
/* Read the first header line which contains the key type. */
if (!read_header(src, header)) {
error = "no header line found in key file";
goto error;
}
if (0 == strcmp(header, "PuTTY-User-Key-File-3")) {
fmt_version = 3;
} else if (0 == strcmp(header, "PuTTY-User-Key-File-2")) {
fmt_version = 2;
} else if (0 == strcmp(header, "PuTTY-User-Key-File-1")) {
/* this is an old key file; warn and then continue */
old_keyfile_warning();
fmt_version = 1;
} else if (0 == strncmp(header, "PuTTY-User-Key-File-", 20)) {
/* this is a key file FROM THE FUTURE; refuse it, but with a
* more specific error message than the generic one below */
error = "PuTTY key format too new";
goto error;
} else {
error = "not a PuTTY SSH-2 private key";
goto error;
}
error = "file format error";
if ((b = read_body(src)) == NULL)
goto error;
/* Select key algorithm structure. */
alg = find_pubkey_alg(b);
if (!alg) {
sfree(b);
goto error;
}
sfree(b);
/* Read the Encryption header line. */
if (!read_header(src, header) || 0 != strcmp(header, "Encryption"))
goto error;
if ((encryption = read_body(src)) == NULL)
goto error;
if (!strcmp(encryption, "aes256-cbc")) {
ciphertype = &ppk_cipher_aes256_cbc;
} else if (!strcmp(encryption, "none")) {
ciphertype = &ppk_cipher_none;
} else {
goto error;
}
/* Read the Comment header line. */
if (!read_header(src, header) || 0 != strcmp(header, "Comment"))
goto error;
if ((comment = read_body(src)) == NULL)
goto error;
memset(¶ms, 0, sizeof(params)); /* in particular, sets
* passes_auto=false */
/* Read the Public-Lines header line and the public blob. */
if (!read_header(src, header) || 0 != strcmp(header, "Public-Lines"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
i = userkey_parse_line_counter(b);
sfree(b);
if (i < 0)
goto error;
public_blob = strbuf_new();
if (!read_blob(src, i, BinarySink_UPCAST(public_blob)))
goto error;
if (fmt_version >= 3 && ciphertype->keylen != 0) {
/* Read Argon2 key derivation parameters. */
if (!read_header(src, header) || 0 != strcmp(header, "Key-Derivation"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
if (!strcmp(b, "Argon2d")) {
params.argon2_flavour = Argon2d;
} else if (!strcmp(b, "Argon2i")) {
params.argon2_flavour = Argon2i;
} else if (!strcmp(b, "Argon2id")) {
params.argon2_flavour = Argon2id;
} else {
sfree(b);
goto error;
}
sfree(b);
if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Memory"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
if (!str_to_uint32_t(b, ¶ms.argon2_mem)) {
sfree(b);
goto error;
}
sfree(b);
if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Passes"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
if (!str_to_uint32_t(b, ¶ms.argon2_passes)) {
sfree(b);
goto error;
}
sfree(b);
if (!read_header(src, header) ||
0 != strcmp(header, "Argon2-Parallelism"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
if (!str_to_uint32_t(b, ¶ms.argon2_parallelism)) {
sfree(b);
goto error;
}
sfree(b);
if (!read_header(src, header) || 0 != strcmp(header, "Argon2-Salt"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
for (size_t i = 0; b[i]; i += 2) {
if (isxdigit((unsigned char)b[i]) && b[i+1] &&
isxdigit((unsigned char)b[i+1])) {
char s[3];
s[0] = b[i];
s[1] = b[i+1];
s[2] = '\0';
put_byte(passphrase_salt, strtoul(s, NULL, 16));
} else {
sfree(b);
goto error;
}
}
sfree(b);
}
/* Read the Private-Lines header line and the Private blob. */
if (!read_header(src, header) || 0 != strcmp(header, "Private-Lines"))
goto error;
if ((b = read_body(src)) == NULL)
goto error;
i = userkey_parse_line_counter(b);
sfree(b);
if (i < 0)
goto error;
private_blob = strbuf_new_nm();
if (!read_blob(src, i, BinarySink_UPCAST(private_blob)))
goto error;
/* Read the Private-MAC or Private-Hash header line. */
if (!read_header(src, header))
goto error;
if (0 == strcmp(header, "Private-MAC")) {
if ((mac = read_body(src)) == NULL)
goto error;
is_mac = true;
} else if (0 == strcmp(header, "Private-Hash") && fmt_version == 1) {
if ((mac = read_body(src)) == NULL)
goto error;
is_mac = false;
} else
goto error;
cipher_mac_keys_blob = strbuf_new();
ssh2_ppk_derive_keys(fmt_version, ciphertype,
ptrlen_from_asciz(passphrase ? passphrase : ""),
cipher_mac_keys_blob, &cipherkey, &cipheriv, &mackey,
ptrlen_from_strbuf(passphrase_salt), ¶ms);
/*
* Decrypt the private blob.
*/
if (private_blob->len % ciphertype->blocklen)
goto error;
if (ciphertype == &ppk_cipher_aes256_cbc) {
aes256_decrypt_pubkey(cipherkey.ptr, cipheriv.ptr,
private_blob->u, private_blob->len);
}
/*
* Verify the MAC.
*/
{
unsigned char binary[32];
char realmac[sizeof(binary) * 2 + 1];
strbuf *macdata;
bool free_macdata;
const ssh2_macalg *mac_alg =
fmt_version <= 2 ? &ssh_hmac_sha1 : &ssh_hmac_sha256;
if (fmt_version == 1) {
/* MAC (or hash) only covers the private blob. */
macdata = private_blob;
free_macdata = false;
} else {
macdata = strbuf_new_nm();
put_stringz(macdata, alg->ssh_id);
put_stringz(macdata, encryption);
put_stringz(macdata, comment);
put_string(macdata, public_blob->s,
public_blob->len);
put_string(macdata, private_blob->s,
private_blob->len);
free_macdata = true;
}
if (is_mac) {
ssh2_mac *mac;
mac = ssh2_mac_new(mac_alg, NULL);
ssh2_mac_setkey(mac, mackey);
ssh2_mac_start(mac);
put_data(mac, macdata->s, macdata->len);
ssh2_mac_genresult(mac, binary);
ssh2_mac_free(mac);
} else {
hash_simple(&ssh_sha1, ptrlen_from_strbuf(macdata), binary);
}
if (free_macdata)
strbuf_free(macdata);
for (i = 0; i < mac_alg->len; i++)
sprintf(realmac + 2 * i, "%02x", binary[i]);
if (strcmp(mac, realmac)) {
/* An incorrect MAC is an unconditional Error if the key is
* unencrypted. Otherwise, it means Wrong Passphrase. */
if (ciphertype->keylen != 0) {
error = "wrong passphrase";
ret = SSH2_WRONG_PASSPHRASE;
} else {
error = "MAC failed";
ret = NULL;
}
goto error;
}
}
/*
* Create and return the key.
*/
ret = snew(ssh2_userkey);
ret->comment = comment;
comment = NULL;
ret->key = ssh_key_new_priv(
alg, ptrlen_from_strbuf(public_blob),
ptrlen_from_strbuf(private_blob));
if (!ret->key) {
sfree(ret);
ret = NULL;
error = "createkey failed";
goto error;
}
error = NULL;
/*
* Error processing.
*/
error:
if (comment)
sfree(comment);
if (encryption)
sfree(encryption);
if (mac)
sfree(mac);
if (public_blob)
strbuf_free(public_blob);
if (private_blob)
strbuf_free(private_blob);
if (cipher_mac_keys_blob)
strbuf_free(cipher_mac_keys_blob);
strbuf_free(passphrase_salt);
if (errorstr)
*errorstr = error;
return ret;