Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
samr7
GitHub Repository: samr7/vanitygen
Path: blob/master/util.c
239 views
1
/*
2
* Vanitygen, vanity bitcoin address generator
3
* Copyright (C) 2011 <[email protected]>
4
*
5
* Vanitygen is free software: you can redistribute it and/or modify
6
* it under the terms of the GNU Affero General Public License as published by
7
* the Free Software Foundation, either version 3 of the License, or
8
* any later version.
9
*
10
* Vanitygen is distributed in the hope that it will be useful,
11
* but WITHOUT ANY WARRANTY; without even the implied warranty of
12
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
* GNU Affero General Public License for more details.
14
*
15
* You should have received a copy of the GNU Affero General Public License
16
* along with Vanitygen. If not, see <http://www.gnu.org/licenses/>.
17
*/
18
19
#if defined(_WIN32)
20
#define _USE_MATH_DEFINES
21
#endif /* defined(_WIN32) */
22
23
#include <stdio.h>
24
#include <stdlib.h>
25
#include <string.h>
26
#include <assert.h>
27
#include <math.h>
28
29
#include <openssl/bn.h>
30
#include <openssl/sha.h>
31
#include <openssl/ripemd.h>
32
#include <openssl/hmac.h>
33
#include <openssl/evp.h>
34
#include <openssl/rand.h>
35
#include <openssl/x509.h>
36
#include <openssl/pem.h>
37
#include <openssl/pkcs12.h>
38
39
#include "pattern.h"
40
#include "util.h"
41
42
const char *vg_b58_alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
43
44
const signed char vg_b58_reverse_map[256] = {
45
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
46
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
47
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
48
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
49
-1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
50
22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
51
-1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
52
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, -1, -1, -1, -1, -1,
53
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
54
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
55
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
56
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
57
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
58
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
59
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
60
};
61
62
void
63
fdumphex(FILE *fp, const unsigned char *src, size_t len)
64
{
65
size_t i;
66
for (i = 0; i < len; i++) {
67
fprintf(fp, "%02x", src[i]);
68
}
69
printf("\n");
70
}
71
72
void
73
fdumpbn(FILE *fp, const BIGNUM *bn)
74
{
75
char *buf;
76
buf = BN_bn2hex(bn);
77
fprintf(fp, "%s\n", buf ? buf : "0");
78
if (buf)
79
OPENSSL_free(buf);
80
}
81
82
void
83
dumphex(const unsigned char *src, size_t len)
84
{
85
fdumphex(stdout, src, len);
86
}
87
88
void
89
dumpbn(const BIGNUM *bn)
90
{
91
fdumpbn(stdout, bn);
92
}
93
94
/*
95
* Key format encode/decode
96
*/
97
98
void
99
vg_b58_encode_check(void *buf, size_t len, char *result)
100
{
101
unsigned char hash1[32];
102
unsigned char hash2[32];
103
104
int d, p;
105
106
BN_CTX *bnctx;
107
BIGNUM *bn, *bndiv, *bntmp;
108
BIGNUM bna, bnb, bnbase, bnrem;
109
unsigned char *binres;
110
int brlen, zpfx;
111
112
bnctx = BN_CTX_new();
113
BN_init(&bna);
114
BN_init(&bnb);
115
BN_init(&bnbase);
116
BN_init(&bnrem);
117
BN_set_word(&bnbase, 58);
118
119
bn = &bna;
120
bndiv = &bnb;
121
122
brlen = (2 * len) + 4;
123
binres = (unsigned char*) malloc(brlen);
124
memcpy(binres, buf, len);
125
126
SHA256(binres, len, hash1);
127
SHA256(hash1, sizeof(hash1), hash2);
128
memcpy(&binres[len], hash2, 4);
129
130
BN_bin2bn(binres, len + 4, bn);
131
132
for (zpfx = 0; zpfx < (len + 4) && binres[zpfx] == 0; zpfx++);
133
134
p = brlen;
135
while (!BN_is_zero(bn)) {
136
BN_div(bndiv, &bnrem, bn, &bnbase, bnctx);
137
bntmp = bn;
138
bn = bndiv;
139
bndiv = bntmp;
140
d = BN_get_word(&bnrem);
141
binres[--p] = vg_b58_alphabet[d];
142
}
143
144
while (zpfx--) {
145
binres[--p] = vg_b58_alphabet[0];
146
}
147
148
memcpy(result, &binres[p], brlen - p);
149
result[brlen - p] = '\0';
150
151
free(binres);
152
BN_clear_free(&bna);
153
BN_clear_free(&bnb);
154
BN_clear_free(&bnbase);
155
BN_clear_free(&bnrem);
156
BN_CTX_free(bnctx);
157
}
158
159
#define skip_char(c) \
160
(((c) == '\r') || ((c) == '\n') || ((c) == ' ') || ((c) == '\t'))
161
162
int
163
vg_b58_decode_check(const char *input, void *buf, size_t len)
164
{
165
int i, l, c;
166
unsigned char *xbuf = NULL;
167
BIGNUM bn, bnw, bnbase;
168
BN_CTX *bnctx;
169
unsigned char hash1[32], hash2[32];
170
int zpfx;
171
int res = 0;
172
173
BN_init(&bn);
174
BN_init(&bnw);
175
BN_init(&bnbase);
176
BN_set_word(&bnbase, 58);
177
bnctx = BN_CTX_new();
178
179
/* Build a bignum from the encoded value */
180
l = strlen(input);
181
for (i = 0; i < l; i++) {
182
if (skip_char(input[i]))
183
continue;
184
c = vg_b58_reverse_map[(int)input[i]];
185
if (c < 0)
186
goto out;
187
BN_clear(&bnw);
188
BN_set_word(&bnw, c);
189
BN_mul(&bn, &bn, &bnbase, bnctx);
190
BN_add(&bn, &bn, &bnw);
191
}
192
193
/* Copy the bignum to a byte buffer */
194
for (i = 0, zpfx = 0; input[i]; i++) {
195
if (skip_char(input[i]))
196
continue;
197
if (input[i] != vg_b58_alphabet[0])
198
break;
199
zpfx++;
200
}
201
c = BN_num_bytes(&bn);
202
l = zpfx + c;
203
if (l < 5)
204
goto out;
205
xbuf = (unsigned char *) malloc(l);
206
if (!xbuf)
207
goto out;
208
if (zpfx)
209
memset(xbuf, 0, zpfx);
210
if (c)
211
BN_bn2bin(&bn, xbuf + zpfx);
212
213
/* Check the hash code */
214
l -= 4;
215
SHA256(xbuf, l, hash1);
216
SHA256(hash1, sizeof(hash1), hash2);
217
if (memcmp(hash2, xbuf + l, 4))
218
goto out;
219
220
/* Buffer verified */
221
if (len) {
222
if (len > l)
223
len = l;
224
memcpy(buf, xbuf, len);
225
}
226
res = l;
227
228
out:
229
if (xbuf)
230
free(xbuf);
231
BN_clear_free(&bn);
232
BN_clear_free(&bnw);
233
BN_clear_free(&bnbase);
234
BN_CTX_free(bnctx);
235
return res;
236
}
237
238
void
239
vg_encode_address(const EC_POINT *ppoint, const EC_GROUP *pgroup,
240
int addrtype, char *result)
241
{
242
unsigned char eckey_buf[128], *pend;
243
unsigned char binres[21] = {0,};
244
unsigned char hash1[32];
245
246
pend = eckey_buf;
247
248
EC_POINT_point2oct(pgroup,
249
ppoint,
250
POINT_CONVERSION_UNCOMPRESSED,
251
eckey_buf,
252
sizeof(eckey_buf),
253
NULL);
254
pend = eckey_buf + 0x41;
255
binres[0] = addrtype;
256
SHA256(eckey_buf, pend - eckey_buf, hash1);
257
RIPEMD160(hash1, sizeof(hash1), &binres[1]);
258
259
vg_b58_encode_check(binres, sizeof(binres), result);
260
}
261
262
void
263
vg_encode_script_address(const EC_POINT *ppoint, const EC_GROUP *pgroup,
264
int addrtype, char *result)
265
{
266
unsigned char script_buf[69];
267
unsigned char *eckey_buf = script_buf + 2;
268
unsigned char binres[21] = {0,};
269
unsigned char hash1[32];
270
271
script_buf[ 0] = 0x51; // OP_1
272
script_buf[ 1] = 0x41; // pubkey length
273
// gap for pubkey
274
script_buf[67] = 0x51; // OP_1
275
script_buf[68] = 0xae; // OP_CHECKMULTISIG
276
277
EC_POINT_point2oct(pgroup,
278
ppoint,
279
POINT_CONVERSION_UNCOMPRESSED,
280
eckey_buf,
281
65,
282
NULL);
283
binres[0] = addrtype;
284
SHA256(script_buf, 69, hash1);
285
RIPEMD160(hash1, sizeof(hash1), &binres[1]);
286
287
vg_b58_encode_check(binres, sizeof(binres), result);
288
}
289
290
void
291
vg_encode_privkey(const EC_KEY *pkey, int addrtype, char *result)
292
{
293
unsigned char eckey_buf[128];
294
const BIGNUM *bn;
295
int nbytes;
296
297
bn = EC_KEY_get0_private_key(pkey);
298
299
eckey_buf[0] = addrtype;
300
nbytes = BN_num_bytes(bn);
301
assert(nbytes <= 32);
302
if (nbytes < 32)
303
memset(eckey_buf + 1, 0, 32 - nbytes);
304
BN_bn2bin(bn, &eckey_buf[33 - nbytes]);
305
306
vg_b58_encode_check(eckey_buf, 33, result);
307
}
308
309
int
310
vg_set_privkey(const BIGNUM *bnpriv, EC_KEY *pkey)
311
{
312
const EC_GROUP *pgroup;
313
EC_POINT *ppnt;
314
int res;
315
316
pgroup = EC_KEY_get0_group(pkey);
317
ppnt = EC_POINT_new(pgroup);
318
319
res = (ppnt &&
320
EC_KEY_set_private_key(pkey, bnpriv) &&
321
EC_POINT_mul(pgroup, ppnt, bnpriv, NULL, NULL, NULL) &&
322
EC_KEY_set_public_key(pkey, ppnt));
323
324
if (ppnt)
325
EC_POINT_free(ppnt);
326
327
if (!res)
328
return 0;
329
330
assert(EC_KEY_check_key(pkey));
331
return 1;
332
}
333
334
int
335
vg_decode_privkey(const char *b58encoded, EC_KEY *pkey, int *addrtype)
336
{
337
BIGNUM bnpriv;
338
unsigned char ecpriv[48];
339
int res;
340
341
res = vg_b58_decode_check(b58encoded, ecpriv, sizeof(ecpriv));
342
if (res != 33)
343
return 0;
344
345
BN_init(&bnpriv);
346
BN_bin2bn(ecpriv + 1, res - 1, &bnpriv);
347
res = vg_set_privkey(&bnpriv, pkey);
348
BN_clear_free(&bnpriv);
349
*addrtype = ecpriv[0];
350
return 1;
351
}
352
353
#if OPENSSL_VERSION_NUMBER < 0x10000000L
354
/* The generic PBKDF2 function first appeared in OpenSSL 1.0 */
355
/* ====================================================================
356
* Copyright (c) 1999-2006 The OpenSSL Project. All rights reserved.
357
*
358
* Redistribution and use in source and binary forms, with or without
359
* modification, are permitted provided that the following conditions
360
* are met:
361
*
362
* 1. Redistributions of source code must retain the above copyright
363
* notice, this list of conditions and the following disclaimer.
364
*
365
* 2. Redistributions in binary form must reproduce the above copyright
366
* notice, this list of conditions and the following disclaimer in
367
* the documentation and/or other materials provided with the
368
* distribution.
369
*
370
* 3. All advertising materials mentioning features or use of this
371
* software must display the following acknowledgment:
372
* "This product includes software developed by the OpenSSL Project
373
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
374
*
375
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
376
* endorse or promote products derived from this software without
377
* prior written permission. For written permission, please contact
378
* [email protected].
379
*
380
* 5. Products derived from this software may not be called "OpenSSL"
381
* nor may "OpenSSL" appear in their names without prior written
382
* permission of the OpenSSL Project.
383
*
384
* 6. Redistributions of any form whatsoever must retain the following
385
* acknowledgment:
386
* "This product includes software developed by the OpenSSL Project
387
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
388
*
389
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
390
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
391
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
392
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
393
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
394
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
395
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
396
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
397
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
398
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
399
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
400
* OF THE POSSIBILITY OF SUCH DAMAGE.
401
* ====================================================================
402
*
403
* This product includes cryptographic software written by Eric Young
404
* ([email protected]). This product includes software written by Tim
405
* Hudson ([email protected]).
406
*
407
*/
408
int
409
PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
410
const unsigned char *salt, int saltlen, int iter,
411
const EVP_MD *digest,
412
int keylen, unsigned char *out)
413
{
414
unsigned char digtmp[EVP_MAX_MD_SIZE], *p, itmp[4];
415
int cplen, j, k, tkeylen, mdlen;
416
unsigned long i = 1;
417
HMAC_CTX hctx;
418
419
mdlen = EVP_MD_size(digest);
420
if (mdlen < 0)
421
return 0;
422
423
HMAC_CTX_init(&hctx);
424
p = out;
425
tkeylen = keylen;
426
if(!pass)
427
passlen = 0;
428
else if(passlen == -1)
429
passlen = strlen(pass);
430
while(tkeylen)
431
{
432
if(tkeylen > mdlen)
433
cplen = mdlen;
434
else
435
cplen = tkeylen;
436
/* We are unlikely to ever use more than 256 blocks (5120 bits!)
437
* but just in case...
438
*/
439
itmp[0] = (unsigned char)((i >> 24) & 0xff);
440
itmp[1] = (unsigned char)((i >> 16) & 0xff);
441
itmp[2] = (unsigned char)((i >> 8) & 0xff);
442
itmp[3] = (unsigned char)(i & 0xff);
443
HMAC_Init_ex(&hctx, pass, passlen, digest, NULL);
444
HMAC_Update(&hctx, salt, saltlen);
445
HMAC_Update(&hctx, itmp, 4);
446
HMAC_Final(&hctx, digtmp, NULL);
447
memcpy(p, digtmp, cplen);
448
for(j = 1; j < iter; j++)
449
{
450
HMAC(digest, pass, passlen,
451
digtmp, mdlen, digtmp, NULL);
452
for(k = 0; k < cplen; k++)
453
p[k] ^= digtmp[k];
454
}
455
tkeylen-= cplen;
456
i++;
457
p+= cplen;
458
}
459
HMAC_CTX_cleanup(&hctx);
460
return 1;
461
}
462
#endif /* OPENSSL_VERSION_NUMBER < 0x10000000L */
463
464
465
typedef struct {
466
int mode;
467
int iterations;
468
const EVP_MD *(*pbkdf_hash_getter)(void);
469
const EVP_CIPHER *(*cipher_getter)(void);
470
} vg_protkey_parameters_t;
471
472
static const vg_protkey_parameters_t protkey_parameters[] = {
473
{ 0, 4096, EVP_sha256, EVP_aes_256_cbc },
474
{ 0, 0, NULL, NULL },
475
{ 0, 0, NULL, NULL },
476
{ 0, 0, NULL, NULL },
477
{ 0, 0, NULL, NULL },
478
{ 0, 0, NULL, NULL },
479
{ 0, 0, NULL, NULL },
480
{ 0, 0, NULL, NULL },
481
{ 0, 0, NULL, NULL },
482
{ 0, 0, NULL, NULL },
483
{ 0, 0, NULL, NULL },
484
{ 0, 0, NULL, NULL },
485
{ 0, 0, NULL, NULL },
486
{ 0, 0, NULL, NULL },
487
{ 0, 0, NULL, NULL },
488
{ 0, 0, NULL, NULL },
489
{ 1, 4096, EVP_sha256, EVP_aes_256_cbc },
490
};
491
492
static int
493
vg_protect_crypt(int parameter_group,
494
unsigned char *data_in, int data_in_len,
495
unsigned char *data_out,
496
const char *pass, int enc)
497
{
498
EVP_CIPHER_CTX *ctx = NULL;
499
unsigned char *salt;
500
unsigned char keymaterial[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH +
501
EVP_MAX_MD_SIZE];
502
unsigned char hmac[EVP_MAX_MD_SIZE];
503
int hmac_len = 0, hmac_keylen = 0;
504
int salt_len;
505
int plaintext_len = 32;
506
int ciphertext_len;
507
int pkcs7_padding = 1;
508
const vg_protkey_parameters_t *params;
509
const EVP_CIPHER *cipher;
510
const EVP_MD *pbkdf_digest;
511
const EVP_MD *hmac_digest;
512
unsigned int hlen;
513
int opos, olen, oincr, nbytes;
514
int ipos;
515
int ret = 0;
516
517
ctx = EVP_CIPHER_CTX_new();
518
if (!ctx)
519
goto out;
520
521
if (parameter_group < 0) {
522
if (enc)
523
parameter_group = 0;
524
else
525
parameter_group = data_in[0];
526
} else {
527
if (!enc && (parameter_group != data_in[0]))
528
goto out;
529
}
530
531
if (parameter_group > (sizeof(protkey_parameters) /
532
sizeof(protkey_parameters[0])))
533
goto out;
534
params = &protkey_parameters[parameter_group];
535
536
if (!params->iterations || !params->pbkdf_hash_getter)
537
goto out;
538
539
pbkdf_digest = params->pbkdf_hash_getter();
540
cipher = params->cipher_getter();
541
542
if (params->mode == 0) {
543
/* Brief encoding */
544
salt_len = 4;
545
hmac_len = 8;
546
hmac_keylen = 16;
547
ciphertext_len = ((plaintext_len + cipher->block_size - 1) /
548
cipher->block_size) * cipher->block_size;
549
pkcs7_padding = 0;
550
hmac_digest = EVP_sha256();
551
} else {
552
/* PKCS-compliant encoding */
553
salt_len = 8;
554
ciphertext_len = ((plaintext_len + cipher->block_size) /
555
cipher->block_size) * cipher->block_size;
556
hmac_digest = NULL;
557
}
558
559
if (!enc && (data_in_len != (1 + ciphertext_len + hmac_len + salt_len)))
560
goto out;
561
562
if (!pass || !data_out) {
563
/* Format check mode */
564
ret = plaintext_len;
565
goto out;
566
}
567
568
if (!enc) {
569
salt = data_in + 1 + ciphertext_len + hmac_len;
570
} else if (salt_len) {
571
salt = data_out + 1 + ciphertext_len + hmac_len;
572
RAND_bytes(salt, salt_len);
573
} else {
574
salt = NULL;
575
}
576
577
PKCS5_PBKDF2_HMAC((const char *) pass, strlen(pass) + 1,
578
salt, salt_len,
579
params->iterations,
580
pbkdf_digest,
581
cipher->key_len + cipher->iv_len + hmac_keylen,
582
keymaterial);
583
584
if (!EVP_CipherInit(ctx, cipher,
585
keymaterial,
586
keymaterial + cipher->key_len,
587
enc)) {
588
fprintf(stderr, "ERROR: could not configure cipher\n");
589
goto out;
590
}
591
592
if (!pkcs7_padding)
593
EVP_CIPHER_CTX_set_padding(ctx, 0);
594
595
if (!enc) {
596
opos = 0;
597
olen = plaintext_len;
598
nbytes = ciphertext_len;
599
ipos = 1;
600
} else {
601
data_out[0] = parameter_group;
602
opos = 1;
603
olen = 1 + ciphertext_len + hmac_len + salt_len - opos;
604
nbytes = plaintext_len;
605
ipos = 0;
606
}
607
608
oincr = olen;
609
if (!EVP_CipherUpdate(ctx, data_out + opos, &oincr,
610
data_in + ipos, nbytes))
611
goto invalid_pass;
612
opos += oincr;
613
olen -= oincr;
614
oincr = olen;
615
if (!EVP_CipherFinal(ctx, data_out + opos, &oincr))
616
goto invalid_pass;
617
opos += oincr;
618
619
if (hmac_len) {
620
hlen = sizeof(hmac);
621
HMAC(hmac_digest,
622
keymaterial + cipher->key_len + cipher->iv_len,
623
hmac_keylen,
624
enc ? data_in : data_out, plaintext_len,
625
hmac, &hlen);
626
if (enc) {
627
memcpy(data_out + 1 + ciphertext_len, hmac, hmac_len);
628
} else if (memcmp(hmac,
629
data_in + 1 + ciphertext_len,
630
hmac_len))
631
goto invalid_pass;
632
}
633
634
if (enc) {
635
if (opos != (1 + ciphertext_len)) {
636
fprintf(stderr, "ERROR: plaintext size mismatch\n");
637
goto out;
638
}
639
opos += hmac_len + salt_len;
640
} else if (opos != plaintext_len) {
641
fprintf(stderr, "ERROR: plaintext size mismatch\n");
642
goto out;
643
}
644
645
ret = opos;
646
647
if (0) {
648
invalid_pass:
649
fprintf(stderr, "ERROR: Invalid password\n");
650
}
651
652
out:
653
OPENSSL_cleanse(hmac, sizeof(hmac));
654
OPENSSL_cleanse(keymaterial, sizeof(keymaterial));
655
if (ctx)
656
EVP_CIPHER_CTX_free(ctx);
657
return ret;
658
}
659
660
int
661
vg_protect_encode_privkey(char *out,
662
const EC_KEY *pkey, int keytype,
663
int parameter_group,
664
const char *pass)
665
{
666
unsigned char ecpriv[64];
667
unsigned char ecenc[128];
668
const BIGNUM *privkey;
669
int nbytes;
670
int restype;
671
672
restype = (keytype & 1) ? 79 : 32;
673
674
privkey = EC_KEY_get0_private_key(pkey);
675
nbytes = BN_num_bytes(privkey);
676
if (nbytes < 32)
677
memset(ecpriv, 0, 32 - nbytes);
678
BN_bn2bin(privkey, ecpriv + 32 - nbytes);
679
680
nbytes = vg_protect_crypt(parameter_group,
681
ecpriv, 32,
682
&ecenc[1], pass, 1);
683
if (nbytes <= 0)
684
return 0;
685
686
OPENSSL_cleanse(ecpriv, sizeof(ecpriv));
687
688
ecenc[0] = restype;
689
vg_b58_encode_check(ecenc, nbytes + 1, out);
690
nbytes = strlen(out);
691
return nbytes;
692
}
693
694
695
int
696
vg_protect_decode_privkey(EC_KEY *pkey, int *keytype,
697
const char *encoded, const char *pass)
698
{
699
unsigned char ecpriv[64];
700
unsigned char ecenc[128];
701
BIGNUM bn;
702
int restype;
703
int res;
704
705
res = vg_b58_decode_check(encoded, ecenc, sizeof(ecenc));
706
707
if ((res < 2) || (res > sizeof(ecenc)))
708
return 0;
709
710
switch (ecenc[0]) {
711
case 32: restype = 128; break;
712
case 79: restype = 239; break;
713
default:
714
return 0;
715
}
716
717
if (!vg_protect_crypt(-1,
718
ecenc + 1, res - 1,
719
pkey ? ecpriv : NULL,
720
pass, 0))
721
return 0;
722
723
res = 1;
724
if (pkey) {
725
BN_init(&bn);
726
BN_bin2bn(ecpriv, 32, &bn);
727
res = vg_set_privkey(&bn, pkey);
728
BN_clear_free(&bn);
729
OPENSSL_cleanse(ecpriv, sizeof(ecpriv));
730
}
731
732
*keytype = restype;
733
return res;
734
}
735
736
/*
737
* Besides the bitcoin-adapted formats, we also support PKCS#8.
738
*/
739
int
740
vg_pkcs8_encode_privkey(char *out, int outlen,
741
const EC_KEY *pkey, const char *pass)
742
{
743
EC_KEY *pkey_copy = NULL;
744
EVP_PKEY *evp_key = NULL;
745
PKCS8_PRIV_KEY_INFO *pkcs8 = NULL;
746
X509_SIG *pkcs8_enc = NULL;
747
BUF_MEM *memptr;
748
BIO *bio = NULL;
749
int res = 0;
750
751
pkey_copy = EC_KEY_dup(pkey);
752
if (!pkey_copy)
753
goto out;
754
evp_key = EVP_PKEY_new();
755
if (!evp_key || !EVP_PKEY_set1_EC_KEY(evp_key, pkey_copy))
756
goto out;
757
pkcs8 = EVP_PKEY2PKCS8(evp_key);
758
if (!pkcs8)
759
goto out;
760
761
bio = BIO_new(BIO_s_mem());
762
if (!bio)
763
goto out;
764
765
if (!pass) {
766
res = PEM_write_bio_PKCS8_PRIV_KEY_INFO(bio, pkcs8);
767
768
} else {
769
pkcs8_enc = PKCS8_encrypt(-1,
770
EVP_aes_256_cbc(),
771
pass, strlen(pass),
772
NULL, 0,
773
4096,
774
pkcs8);
775
if (!pkcs8_enc)
776
goto out;
777
res = PEM_write_bio_PKCS8(bio, pkcs8_enc);
778
}
779
780
BIO_get_mem_ptr(bio, &memptr);
781
res = memptr->length;
782
if (res < outlen) {
783
memcpy(out, memptr->data, res);
784
out[res] = '\0';
785
} else {
786
memcpy(out, memptr->data, outlen - 1);
787
out[outlen-1] = '\0';
788
}
789
790
out:
791
if (bio)
792
BIO_free(bio);
793
if (pkey_copy)
794
EC_KEY_free(pkey_copy);
795
if (evp_key)
796
EVP_PKEY_free(evp_key);
797
if (pkcs8)
798
PKCS8_PRIV_KEY_INFO_free(pkcs8);
799
if (pkcs8_enc)
800
X509_SIG_free(pkcs8_enc);
801
return res;
802
}
803
804
int
805
vg_pkcs8_decode_privkey(EC_KEY *pkey, const char *pem_in, const char *pass)
806
{
807
EC_KEY *pkey_in = NULL;
808
EC_KEY *test_key = NULL;
809
EVP_PKEY *evp_key = NULL;
810
PKCS8_PRIV_KEY_INFO *pkcs8 = NULL;
811
X509_SIG *pkcs8_enc = NULL;
812
BIO *bio = NULL;
813
int res = 0;
814
815
bio = BIO_new_mem_buf((char *)pem_in, strlen(pem_in));
816
if (!bio)
817
goto out;
818
819
pkcs8_enc = PEM_read_bio_PKCS8(bio, NULL, NULL, NULL);
820
if (pkcs8_enc) {
821
if (!pass)
822
return -1;
823
pkcs8 = PKCS8_decrypt(pkcs8_enc, pass, strlen(pass));
824
825
} else {
826
(void) BIO_reset(bio);
827
pkcs8 = PEM_read_bio_PKCS8_PRIV_KEY_INFO(bio, NULL, NULL, NULL);
828
}
829
830
if (!pkcs8)
831
goto out;
832
evp_key = EVP_PKCS82PKEY(pkcs8);
833
if (!evp_key)
834
goto out;
835
pkey_in = EVP_PKEY_get1_EC_KEY(evp_key);
836
if (!pkey_in)
837
goto out;
838
839
/* Expect a specific curve */
840
test_key = EC_KEY_new_by_curve_name(NID_secp256k1);
841
if (!test_key ||
842
EC_GROUP_cmp(EC_KEY_get0_group(pkey_in),
843
EC_KEY_get0_group(test_key),
844
NULL))
845
goto out;
846
847
if (!EC_KEY_copy(pkey, pkey_in))
848
goto out;
849
850
res = 1;
851
852
out:
853
if (bio)
854
BIO_free(bio);
855
if (test_key)
856
EC_KEY_free(pkey_in);
857
if (evp_key)
858
EVP_PKEY_free(evp_key);
859
if (pkcs8)
860
PKCS8_PRIV_KEY_INFO_free(pkcs8);
861
if (pkcs8_enc)
862
X509_SIG_free(pkcs8_enc);
863
return res;
864
}
865
866
867
int
868
vg_decode_privkey_any(EC_KEY *pkey, int *addrtype, const char *input,
869
const char *pass)
870
{
871
int res;
872
873
if (vg_decode_privkey(input, pkey, addrtype))
874
return 1;
875
if (vg_protect_decode_privkey(pkey, addrtype, input, NULL)) {
876
if (!pass)
877
return -1;
878
return vg_protect_decode_privkey(pkey, addrtype, input, pass);
879
}
880
res = vg_pkcs8_decode_privkey(pkey, input, pass);
881
if (res > 0) {
882
/* Assume main network address */
883
*addrtype = 128;
884
}
885
return res;
886
}
887
888
889
int
890
vg_read_password(char *buf, size_t size)
891
{
892
return !EVP_read_pw_string(buf, size, "Enter new password:", 1);
893
}
894
895
896
/*
897
* Password complexity checker
898
* Heavily inspired by, but a simplification of "How Secure Is My Password?",
899
* http://howsecureismypassword.net/
900
*/
901
static unsigned char ascii_class[] = {
902
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
903
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
904
5, 4, 5, 4, 4, 4, 4, 5, 4, 4, 4, 4, 5, 4, 5, 5,
905
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 4, 5, 5,
906
4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
907
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 5, 5, 5, 4, 4,
908
5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
909
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 0,
910
};
911
912
int
913
vg_check_password_complexity(const char *pass, int verbose)
914
{
915
int i, len;
916
int classes[6] = { 0, };
917
const char *crackunit = "seconds";
918
int char_complexity = 0;
919
double crackops, cracktime;
920
int weak;
921
922
/*
923
* This number reflects a resourceful attacker with
924
* USD >$20K in 2011 hardware
925
*/
926
const int rate = 250000000;
927
928
/* Consider the password weak if it can be cracked in <1 year */
929
const int weak_threshold = (60*60*24*365);
930
931
len = strlen(pass);
932
for (i = 0; i < len; i++) {
933
if (pass[i] > sizeof(ascii_class))
934
/* FIXME: skip the rest of the UTF8 char */
935
classes[5]++;
936
else if (!ascii_class[(int)pass[i]])
937
continue;
938
else
939
classes[(int)ascii_class[(int)pass[i]] - 1]++;
940
}
941
942
if (classes[0])
943
char_complexity += 26;
944
if (classes[1])
945
char_complexity += 26;
946
if (classes[2])
947
char_complexity += 10;
948
if (classes[3])
949
char_complexity += 14;
950
if (classes[4])
951
char_complexity += 19;
952
if (classes[5])
953
char_complexity += 32; /* oversimplified */
954
955
/* This assumes brute-force and oversimplifies the problem */
956
crackops = pow((double)char_complexity, (double)len);
957
cracktime = (crackops * (1 - (1/M_E))) / rate;
958
weak = (cracktime < weak_threshold);
959
960
if (cracktime > 60.0) {
961
cracktime /= 60.0;
962
crackunit = "minutes";
963
if (cracktime > 60.0) {
964
cracktime /= 60.0;
965
crackunit = "hours";
966
if (cracktime > 24.0) {
967
cracktime /= 24;
968
crackunit = "days";
969
if (cracktime > 365.0) {
970
cracktime /= 365.0;
971
crackunit = "years";
972
}
973
}
974
}
975
}
976
977
/* Complain by default about weak passwords */
978
if ((weak && (verbose > 0)) || (verbose > 1)) {
979
if (cracktime < 1.0) {
980
fprintf(stderr,
981
"Estimated password crack time: >1 %s\n",
982
crackunit);
983
} else if (cracktime < 1000000) {
984
fprintf(stderr,
985
"Estimated password crack time: %.1f %s\n",
986
cracktime, crackunit);
987
} else {
988
fprintf(stderr,
989
"Estimated password crack time: %e %s\n",
990
cracktime, crackunit);
991
}
992
if (!classes[0] && !classes[1] && classes[2] &&
993
!classes[3] && !classes[4] && !classes[5]) {
994
fprintf(stderr,
995
"WARNING: Password contains only numbers\n");
996
}
997
else if (!classes[2] && !classes[3] && !classes[4] &&
998
!classes[5]) {
999
if (!classes[0] || !classes[1]) {
1000
fprintf(stderr,
1001
"WARNING: Password contains "
1002
"only %scase letters\n",
1003
classes[0] ? "lower" : "upper");
1004
} else {
1005
fprintf(stderr,
1006
"WARNING: Password contains "
1007
"only letters\n");
1008
}
1009
}
1010
}
1011
1012
return !weak;
1013
}
1014
1015
1016
/*
1017
* Pattern file reader
1018
* Absolutely disgusting, unable to free the pattern list when it's done
1019
*/
1020
1021
int
1022
vg_read_file(FILE *fp, char ***result, int *rescount)
1023
{
1024
int ret = 1;
1025
1026
char **patterns;
1027
char *buf = NULL, *obuf, *pat;
1028
const int blksize = 16*1024;
1029
int nalloc = 16;
1030
int npatterns = 0;
1031
int count, pos;
1032
1033
patterns = (char**) malloc(sizeof(char*) * nalloc);
1034
count = 0;
1035
pos = 0;
1036
1037
while (1) {
1038
obuf = buf;
1039
buf = (char *) malloc(blksize);
1040
if (!buf) {
1041
ret = 0;
1042
break;
1043
}
1044
if (pos < count) {
1045
memcpy(buf, &obuf[pos], count - pos);
1046
}
1047
pos = count - pos;
1048
count = fread(&buf[pos], 1, blksize - pos, fp);
1049
if (count < 0) {
1050
fprintf(stderr,
1051
"Error reading file: %s\n", strerror(errno));
1052
ret = 0;
1053
}
1054
if (count <= 0)
1055
break;
1056
count += pos;
1057
pat = buf;
1058
1059
while (pos < count) {
1060
if ((buf[pos] == '\r') || (buf[pos] == '\n')) {
1061
buf[pos] = '\0';
1062
if (pat) {
1063
if (npatterns == nalloc) {
1064
nalloc *= 2;
1065
patterns = (char**)
1066
realloc(patterns,
1067
sizeof(char*) *
1068
nalloc);
1069
}
1070
patterns[npatterns] = pat;
1071
npatterns++;
1072
pat = NULL;
1073
}
1074
}
1075
else if (!pat) {
1076
pat = &buf[pos];
1077
}
1078
pos++;
1079
}
1080
1081
pos = pat ? (pat - buf) : count;
1082
}
1083
1084
*result = patterns;
1085
*rescount = npatterns;
1086
1087
return ret;
1088
}
1089
1090