forked from servalproject/serval-dna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyring.c
2285 lines (2095 loc) · 74 KB
/
keyring.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
/*
Serval DNA keyring
Copyright (C) 2013 Serval Project Inc.
Copyright (C) 2010-2012 Paul Gardner-Stephen
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <stdio.h>
#include <assert.h>
#include "serval.h"
#include "rhizome.h"
#include "conf.h"
#include "constants.h"
#include "nacl.h"
#include "overlay_address.h"
#include "crypto.h"
#include "overlay_interface.h"
#include "overlay_packet.h"
#include "overlay_buffer.h"
#include "keyring.h"
#include "dataformats.h"
#include "str.h"
#include "mem.h"
#include "rotbuf.h"
static void keyring_free_keypair(keypair *kp);
static void keyring_free_context(keyring_context *c);
static void keyring_free_identity(keyring_identity *id);
static int keyring_identity_mac(const keyring_identity *id, unsigned char *pkrsalt, unsigned char *mac);
static int _keyring_open(keyring_file *k, const char *path, const char *mode)
{
if (config.debug.keyring)
DEBUGF("opening %s in \"%s\" mode", alloca_str_toprint(path), mode);
k->file = fopen(path, mode);
if (!k->file) {
if (errno != EPERM && errno != ENOENT)
return WHYF_perror("fopen(%s, \"%s\")", alloca_str_toprint(path), mode);
if (config.debug.keyring)
DEBUGF("cannot open %s in \"%s\" mode", alloca_str_toprint(path), mode);
}
return 0;
}
/*
* Open keyring file, read BAM and create initial context using the stored salt.
*/
keyring_file *keyring_open(const char *path, int writeable)
{
/* Allocate structure */
keyring_file *k = emalloc_zero(sizeof(keyring_file));
if (!k)
return NULL;
/* Open keyring file read-write if we can, else use it read-only, else create it. */
if (writeable && _keyring_open(k, path, "r+") == -1) {
keyring_free(k);
return NULL;
}
if (!k->file && _keyring_open(k, path, "r") == -1) {
keyring_free(k);
return NULL;
}
if (!k->file && writeable && _keyring_open(k, path, "w+") == -1) {
keyring_free(k);
return NULL;
}
if (!k->file) {
WHYF_perror("cannot open or create keyring file %s", alloca_str_toprint(path));
keyring_free(k);
return NULL;
}
if (fseeko(k->file, 0, SEEK_END)) {
WHYF_perror("fseeko(%s, 0, SEEK_END)", alloca_str_toprint(path));
keyring_free(k);
return NULL;
}
k->file_size=ftello(k->file);
if (k->file_size<KEYRING_PAGE_SIZE) {
/* Uninitialised, so write 2KB of zeroes,
followed by 2KB of random bytes as salt. */
if (fseeko(k->file, 0, SEEK_SET)) {
WHYF_perror("fseeko(%s, 0, SEEK_END)", alloca_str_toprint(path));
keyring_free(k);
return NULL;
}
unsigned char buffer[KEYRING_PAGE_SIZE];
bzero(&buffer[0],KEYRING_BAM_BYTES);
if (fwrite(buffer, 2048, 1, k->file)!=1) {
WHYF_perror("fwrite(%p, 2048, 1, %s)", buffer, alloca_str_toprint(path));
WHY("Could not write empty bitmap in fresh keyring file");
keyring_free(k);
return NULL;
}
if (urandombytes(&buffer[0],KEYRING_PAGE_SIZE-KEYRING_BAM_BYTES)) {
WHYF("Could not get random keyring salt to put in fresh keyring file %s", path);
keyring_free(k);
return NULL;
}
if (fwrite(buffer, KEYRING_PAGE_SIZE - KEYRING_BAM_BYTES, 1, k->file) != 1) {
WHYF_perror("fwrite(%p, %lu, 1, %s)", buffer, (long)(KEYRING_PAGE_SIZE - KEYRING_BAM_BYTES), alloca_str_toprint(path));
WHYF("Could not write keyring salt in fresh keyring file");
keyring_free(k);
return NULL;
}
k->file_size=KEYRING_PAGE_SIZE;
}
/* Read BAMs for each slab in the file */
keyring_bam **b=&k->bam;
off_t offset=0;
while(offset<k->file_size) {
/* Read bitmap from slab.
Also, if offset is zero, read the salt */
if (fseeko(k->file,offset,SEEK_SET)) {
WHYF_perror("fseeko(%s, %ld, SEEK_SET)", alloca_str_toprint(path), (long)offset);
WHY("Could not seek to BAM in keyring file");
keyring_free(k);
return NULL;
}
*b = emalloc_zero(sizeof(keyring_bam));
if (!(*b)) {
WHYF("Could not allocate keyring_bam structure for key ring file %s", path);
keyring_free(k);
return NULL;
}
(*b)->file_offset=offset;
/* Read bitmap */
int r=fread((*b)->bitmap, KEYRING_BAM_BYTES, 1, k->file);
if (r!=1) {
WHYF_perror("fread(%p, %ld, 1, %s)", (*b)->bitmap, (long)KEYRING_BAM_BYTES, alloca_str_toprint(path));
WHYF("Could not read BAM from keyring file");
keyring_free(k);
return NULL;
}
/* Read salt if this is the first bitmap block.
We setup a context for this self-supplied key-ring salt.
(other keyring salts may be provided later on, resulting in
multiple contexts being loaded) */
if (!offset) {
k->contexts[0] = emalloc_zero(sizeof(keyring_context));
if (!k->contexts[0]) {
WHYF("Could not allocate keyring_context for keyring file %s", path);
keyring_free(k);
return NULL;
}
// First context is always with null keyring PIN.
k->contexts[0]->KeyRingPin = str_edup("");
k->contexts[0]->KeyRingSaltLen=KEYRING_PAGE_SIZE-KEYRING_BAM_BYTES;
k->contexts[0]->KeyRingSalt = emalloc(k->contexts[0]->KeyRingSaltLen);
if (!k->contexts[0]->KeyRingSalt) {
WHYF("Could not allocate keyring_context->salt for keyring file %s", path);
keyring_free(k);
return NULL;
}
r = fread(k->contexts[0]->KeyRingSalt, k->contexts[0]->KeyRingSaltLen, 1, k->file);
if (r!=1) {
WHYF_perror("fread(%p, %d, 1, %s)", k->contexts[0]->KeyRingSalt, k->contexts[0]->KeyRingSaltLen, alloca_str_toprint(path));
WHYF("Could not read salt from keyring file %s", path);
keyring_free(k);
return NULL;
}
k->context_count=1;
}
/* Skip to next slab, and find next bam pointer. */
offset+=KEYRING_PAGE_SIZE*(KEYRING_BAM_BYTES<<3);
b=&(*b)->next;
}
return k;
}
static void add_subscriber(keyring_identity *id, unsigned keypair)
{
assert(keypair < id->keypair_count);
assert(id->keypairs[keypair]->type == KEYTYPE_CRYPTOBOX);
id->subscriber = find_subscriber(id->keypairs[keypair]->public_key, SID_SIZE, 1);
if (id->subscriber) {
if (id->subscriber->reachable == REACHABLE_NONE){
id->subscriber->reachable = REACHABLE_SELF;
if (!my_subscriber)
my_subscriber = id->subscriber;
}
id->subscriber->identity = id;
}
}
void keyring_free(keyring_file *k)
{
int i;
if (!k) return;
/* Close keyring file handle */
if (k->file) fclose(k->file);
k->file=NULL;
/* Free BAMs (no substructure, so easy) */
keyring_bam *b=k->bam;
while(b) {
keyring_bam *last_bam=b;
b=b->next;
/* Clear out any private data */
bzero(last_bam,sizeof(keyring_bam));
/* release structure */
free(last_bam);
}
/* Free contexts (including subordinate identities and dynamically allocated salt strings).
Don't forget to overwrite any private data. */
for(i=0;i<KEYRING_MAX_CONTEXTS;i++)
if (k->contexts[i]) {
keyring_free_context(k->contexts[i]);
k->contexts[i]=NULL;
}
/* Wipe everything, just to be sure. */
bzero(k,sizeof(keyring_file));
free(k);
return;
}
static void wipestr(char *str)
{
while (*str)
*str++ = ' ';
}
void keyring_release_identity(keyring_file *k, unsigned cn, unsigned id)
{
if (config.debug.keyring)
DEBUGF("Releasing k=%p, cn=%u, id=%u", k, cn, id);
keyring_context *c=k->contexts[cn];
assert(c->identity_count > 0);
c->identity_count--;
keyring_free_identity(c->identities[id]);
if (id!=c->identity_count)
c->identities[id] = c->identities[c->identity_count];
c->identities[c->identity_count]=NULL;
if (c->identity_count==0){
keyring_free_context(c);
assert(k->context_count > 0);
k->context_count --;
if (cn!=k->context_count)
k->contexts[cn] = k->contexts[k->context_count];
k->contexts[k->context_count]=NULL;
}
}
void keyring_release_subscriber(keyring_file *k, const sid_t *sid)
{
unsigned cn=0, in=0, kp=0;
if (keyring_find_sid(k, &cn, &in, &kp, sid)
&& keyring->contexts[cn]->identities[in]->subscriber != my_subscriber)
keyring_release_identity(keyring, cn, in);
}
static void keyring_free_context(keyring_context *c)
{
int i;
if (!c) return;
if (c->KeyRingPin) {
/* Wipe pin from local memory before freeing. */
wipestr(c->KeyRingPin);
free(c->KeyRingPin);
c->KeyRingPin = NULL;
}
if (c->KeyRingSalt) {
bzero(c->KeyRingSalt,c->KeyRingSaltLen);
free(c->KeyRingSalt);
c->KeyRingSalt = NULL;
c->KeyRingSaltLen = 0;
}
/* Wipe out any loaded identities */
for(i=0;i<KEYRING_MAX_IDENTITIES;i++)
if (c->identities[i])
keyring_free_identity(c->identities[i]);
/* Make sure any private data is wiped out */
bzero(c,sizeof(keyring_context));
free(c);
return;
}
void keyring_free_identity(keyring_identity *id)
{
if (id->PKRPin) {
/* Wipe pin from local memory before freeing. */
wipestr(id->PKRPin);
free(id->PKRPin);
id->PKRPin = NULL;
}
int i;
for(i=0;i<PKR_MAX_KEYPAIRS;i++)
if (id->keypairs[i])
keyring_free_keypair(id->keypairs[i]);
if (id->subscriber)
link_stop_routing(id->subscriber);
bzero(id,sizeof(keyring_identity));
free(id);
return;
}
/* Create a new keyring context for the loaded keyring file. Returns the index of the context. We
* don't need to load any identities etc, as that happens when we enter an identity pin. If the pin
* is NULL, it is assumed to be blank. The pin does NOT have to be numeric, and has no practical
* length limitation, as it is used as an input into a hashing function. But for sanity sake, let's
* limit it to 16KB.
*/
int keyring_enter_keyringpin(keyring_file *k, const char *pin)
{
if (config.debug.keyring)
DEBUGF("k=%p pin=%s", k, alloca_str_toprint(pin));
if (!k)
return WHY("k is null");
if (k->context_count >= KEYRING_MAX_CONTEXTS)
return WHY("Too many loaded contexts already");
if (k->context_count < 1)
return WHY("Cannot enter PIN without keyring salt being available");
unsigned cn;
for (cn = 0; cn < k->context_count; ++cn)
if (strcmp(k->contexts[cn]->KeyRingPin, pin) == 0)
return cn;
keyring_context *c = emalloc_zero(sizeof(keyring_context));
if (c == NULL)
return -1;
/* Store pin and copy salt from the zeroeth context */
c->KeyRingSaltLen = k->contexts[0]->KeyRingSaltLen;
if ( ((c->KeyRingPin = str_edup(pin ? pin : "")) == NULL)
|| ((c->KeyRingSalt = emalloc(c->KeyRingSaltLen)) == NULL)
) {
keyring_free_context(c);
return -1;
}
bcopy(k->contexts[0]->KeyRingSalt, c->KeyRingSalt, c->KeyRingSaltLen);
k->contexts[k->context_count] = c;
return k->context_count++;
}
/*
En/Decrypting a block requires use of the first 32 bytes of the block to provide
salt. The next 64 bytes constitute a message authentication code (MAC) that is
used to verify the validity of the block. The verification occurs in a higher
level function, and all we need to know here is that we shouldn't decrypt the
first 96 bytes of the block.
*/
static int keyring_munge_block(
unsigned char *block, int len /* includes the first 96 bytes */,
unsigned char *KeyRingSalt, int KeyRingSaltLen,
const char *KeyRingPin, const char *PKRPin)
{
if (config.debug.keyring)
DEBUGF("KeyRingPin=%s PKRPin=%s", alloca_str_toprint(KeyRingPin), alloca_str_toprint(PKRPin));
int exit_code=1;
unsigned char hashKey[crypto_hash_sha512_BYTES];
unsigned char hashNonce[crypto_hash_sha512_BYTES];
unsigned char work[65536];
if (len<96) return WHY("block too short");
unsigned char *PKRSalt=&block[0];
int PKRSaltLen=32;
#if crypto_stream_xsalsa20_KEYBYTES>crypto_hash_sha512_BYTES
#error crypto primitive key size too long -- hash needs to be expanded
#endif
#if crypto_stream_xsalsa20_NONCEBYTES>crypto_hash_sha512_BYTES
#error crypto primitive nonce size too long -- hash needs to be expanded
#endif
/* Generate key and nonce hashes from the various inputs */
unsigned ofs;
#define APPEND(buf, len) { \
assert(ofs <= sizeof work); \
unsigned __len = (len); \
if (__len > sizeof work - ofs) { \
WHY("Input too long"); \
goto kmb_safeexit; \
} \
bcopy((buf), &work[ofs], __len); \
ofs += __len; \
}
/* Form key as hash of various concatenated inputs.
The ordering and repetition of the inputs is designed to make rainbow tables
infeasible */
ofs=0;
APPEND(PKRSalt,PKRSaltLen);
APPEND(PKRPin,strlen(PKRPin));
APPEND(PKRSalt,PKRSaltLen);
APPEND(KeyRingPin,strlen(KeyRingPin));
crypto_hash_sha512(hashKey,work,ofs);
/* Form the nonce as hash of various other concatenated inputs */
ofs=0;
APPEND(KeyRingPin,strlen(KeyRingPin));
APPEND(KeyRingSalt,KeyRingSaltLen);
APPEND(KeyRingPin,strlen(KeyRingPin));
APPEND(PKRPin,strlen(PKRPin));
crypto_hash_sha512(hashNonce,work,ofs);
/* Now en/de-crypt the remainder of the block.
We do this in-place for convenience, so you should not pass in a mmap()'d
lump. */
crypto_stream_xsalsa20_xor(&block[96],&block[96],len-96, hashNonce,hashKey);
exit_code=0;
kmb_safeexit:
/* Wipe out all sensitive structures before returning */
ofs=0;
bzero(&work[0],65536);
bzero(&hashKey[0],crypto_hash_sha512_BYTES);
bzero(&hashNonce[0],crypto_hash_sha512_BYTES);
return exit_code;
#undef APPEND
}
static const char *keytype_str(unsigned ktype, const char *unknown)
{
switch (ktype) {
case KEYTYPE_CRYPTOBOX: return "CRYPTOBOX";
case KEYTYPE_CRYPTOSIGN: return "CRYPTOSIGN";
case KEYTYPE_RHIZOME: return "RHIZOME";
case KEYTYPE_DID: return "DID";
case KEYTYPE_PUBLIC_TAG: return "PUBLIC_TAG";
default: return unknown;
}
}
struct keytype {
size_t public_key_size;
size_t private_key_size;
size_t packed_size;
void (*creator)(keypair *);
int (*packer)(const keypair *, struct rotbuf *);
int (*unpacker)(keypair *, struct rotbuf *, size_t);
void (*dumper)(const keypair *, XPRINTF, int);
int (*loader)(keypair *, const char *);
};
static void create_cryptobox(keypair *kp)
{
/* Filter out public keys that start with 0x0, as they are reserved for address
abbreviation. */
do {
crypto_box_curve25519xsalsa20poly1305_keypair(kp->public_key, kp->private_key);
} while (kp->public_key[0] < 0x10);
}
/* Compute public key from private key.
*
* Public key calculation as below is taken from section 3 of:
* http://cr.yp.to/highspeed/naclcrypto-20090310.pdf
*
* This can take a while on a mobile phone since it involves a scalarmult operation, so searching
* through all slots for a pin could take a while (perhaps 1 second per pin:slot cominbation). This
* is both good and bad. The other option is to store the public key as well, which would make
* entering a pin faster, but would also make trying an incorrect pin faster, thus simplifying some
* brute-force attacks. We need to make a decision between speed/convenience and security here.
*/
static void _derive_scalarmult_public(unsigned char *public, const unsigned char *private)
{
crypto_scalarmult_curve25519_base(public, private);
}
static void create_cryptosign(keypair *kp)
{
crypto_sign_edwards25519sha512batch_keypair(kp->public_key, kp->private_key);
}
static void create_rhizome(keypair *kp)
{
urandombytes(kp->private_key, kp->private_key_len);
}
static int pack_private_only(const keypair *kp, struct rotbuf *rb)
{
rotbuf_putbuf(rb, kp->private_key, kp->private_key_len);
return 0;
}
static int pack_public_only(const keypair *kp, struct rotbuf *rb)
{
rotbuf_putbuf(rb, kp->public_key, kp->public_key_len);
return 0;
}
static int pack_private_public(const keypair *kp, struct rotbuf *rb)
{
rotbuf_putbuf(rb, kp->private_key, kp->private_key_len);
rotbuf_putbuf(rb, kp->public_key, kp->public_key_len);
return 0;
}
static void dump_private_public(const keypair *kp, XPRINTF xpf, int include_secret)
{
if (kp->public_key_len)
xprintf(xpf, " pub=%s", alloca_tohex(kp->public_key, kp->public_key_len));
if (include_secret && kp->private_key_len)
xprintf(xpf, " sec=%s", alloca_tohex(kp->private_key, kp->private_key_len));
}
static int _load_decode_hex(const char **hex, unsigned char **buf, size_t *len)
{
const char *end = NULL;
size_t hexlen = strn_fromhex(NULL, -1, *hex, &end);
if (hexlen == 0 || end == NULL || (*end != ' ' && *end != '\0'))
return WHY("malformed hex value");
if (*len == 0) {
assert(*buf == NULL);
*len = hexlen;
if ((*buf = emalloc_zero(*len)) == NULL)
return -1;
}
else if (hexlen != *len)
return WHYF("invalid hex value, incorrect length (expecting %zu bytes, got %zu)", *len, hexlen);
strn_fromhex(*buf, *len, *hex, hex);
assert(*hex == end);
return 0;
}
static int load_private_public(keypair *kp, const char *text)
{
assert(kp->public_key_len != 0);
assert(kp->public_key != NULL);
assert(kp->private_key_len != 0);
assert(kp->private_key != NULL);
const char *t = text;
int got_pub = 0;
int got_sec = 0;
while (*t) {
while (isspace(*t))
++t;
if (str_startswith(t, "pub=", &t)) {
if (_load_decode_hex(&t, &kp->public_key, &kp->public_key_len) == -1)
WHY("cannot decode pub= field");
else
got_pub = 1;
}
else if (str_startswith(t, "sec=", &t)) {
if (_load_decode_hex(&t, &kp->private_key, &kp->private_key_len) == -1)
WHY("cannot decode sec= field");
else
got_sec = 1;
}
else if (*t)
return WHYF("unsupported dump field: %s", t);
}
if (!got_sec)
return WHY("missing sec= field");
if (!got_pub)
return WHY("missing pub= field");
return 0;
}
static int load_private(keypair *kp, const char *text)
{
assert(kp->private_key_len != 0);
assert(kp->private_key != NULL);
const char *t = text;
int got_sec = 0;
while (*t) {
while (isspace(*t))
++t;
if (str_startswith(t, "sec=", &t)) {
if (_load_decode_hex(&t, &kp->private_key, &kp->private_key_len) == -1)
WHY("cannot decode sec= field");
else
got_sec = 1;
} else if (str_startswith(t, "pub=", &t)) {
WARN("skipping pub= field");
while (*t && !isspace(*t))
++t;
}
else if (*t)
return WHYF("unsupported dump field: %s", t);
}
if (!got_sec)
return WHY("missing sec= field");
return 0;
}
static int load_cryptobox(keypair *kp, const char *text)
{
if (load_private(kp, text) == -1)
return -1;
_derive_scalarmult_public(kp->public_key, kp->private_key);
return 0;
}
static int load_private_only(keypair *kp, const char *text)
{
assert(kp->public_key_len == 0);
assert(kp->public_key == NULL);
return load_private(kp, text);
}
static int load_unknown(keypair *kp, const char *text)
{
assert(kp->private_key_len == 0);
assert(kp->private_key == NULL);
assert(kp->public_key_len == 0);
assert(kp->public_key == NULL);
const char *t = text;
while (*t) {
while (isspace(*t))
++t;
if (str_startswith(t, "pub=", &t)) {
if (_load_decode_hex(&t, &kp->public_key, &kp->public_key_len) == -1)
WHY("cannot decode pub= field");
}
else if (str_startswith(t, "sec=", &t)) {
if (_load_decode_hex(&t, &kp->private_key, &kp->private_key_len) == -1)
WHY("cannot decode sec= field");
}
else if (*t)
return WHYF("unsupported dump field: %s", t);
}
return 0;
}
static int unpack_private_public(keypair *kp, struct rotbuf *rb, size_t key_length)
{
assert(key_length == kp->private_key_len + kp->public_key_len);
rotbuf_getbuf(rb, kp->private_key, kp->private_key_len);
rotbuf_getbuf(rb, kp->public_key, kp->public_key_len);
return 0;
}
static int unpack_private_only(keypair *kp, struct rotbuf *rb, size_t key_length)
{
if (!kp->private_key){
kp->private_key_len = key_length;
if ((kp->private_key = emalloc(kp->private_key_len))==NULL)
return -1;
}
rotbuf_getbuf(rb, kp->private_key, kp->private_key_len);
return 0;
}
static int unpack_public_only(keypair *kp, struct rotbuf *rb, size_t key_length)
{
if (!kp->public_key){
kp->public_key_len = key_length;
if ((kp->public_key = emalloc(kp->public_key_len))==NULL)
return -1;
}
rotbuf_getbuf(rb, kp->public_key, kp->public_key_len);
return 0;
}
static int unpack_cryptobox(keypair *kp, struct rotbuf *rb, size_t key_length)
{
assert(key_length == kp->private_key_len);
rotbuf_getbuf(rb, kp->private_key, kp->private_key_len);
if (!rb->wrap)
_derive_scalarmult_public(kp->public_key, kp->private_key);
return 0;
}
static int pack_did_name(const keypair *kp, struct rotbuf *rb)
{
// Ensure name is nul terminated.
if (strnchr((const char *)kp->public_key, kp->public_key_len, '\0') == NULL)
return WHY("missing nul terminator");
return pack_private_public(kp, rb);
}
static int unpack_did_name(keypair *kp, struct rotbuf *rb, size_t key_length)
{
if (unpack_private_public(kp, rb, key_length) == -1)
return -1;
// Fail if name is not nul terminated.
return strnchr((const char *)kp->public_key, kp->public_key_len, '\0') == NULL ? -1 : 0;
}
static void dump_did_name(const keypair *kp, XPRINTF xpf, int UNUSED(include_secret))
{
xprintf(xpf, " DID=%s", alloca_str_toprint_quoted((const char *)kp->private_key, "\"\""));
xprintf(xpf, " Name=%s", alloca_str_toprint_quoted((const char *)kp->public_key, "\"\""));
}
static int load_did_name(keypair *kp, const char *text)
{
assert(kp->public_key != NULL);
assert(kp->private_key != NULL);
const char *t = text;
int got_did = 0;
int got_name = 0;
while (*t) {
while (isspace(*t))
++t;
if (str_startswith(t, "DID=\"", &t)) {
if (got_did)
return WHY("duplicate DID");
const char *e = NULL;
bzero(kp->private_key, kp->private_key_len);
strn_fromprint(kp->private_key, kp->private_key_len, t, 0, '"', &e);
if (*e != '"')
return WHY("malformed DID quoted string");
t = e + 1;
got_did = 1;
} else if (str_startswith(t, "Name=\"", &t)) {
if (got_name)
return WHY("duplicate Name");
const char *e = NULL;
bzero(kp->public_key, kp->public_key_len);
strn_fromprint(kp->public_key, kp->public_key_len, t, 0, '"', &e);
if (*e != '"')
return WHY("malformed Name quoted string");
t = e + 1;
got_name = 1;
}
else if (*t)
return WHYF("unsupported dump content: %s", t);
}
if (!got_did)
return WHY("missing DID");
if (!got_name)
return WHY("missing Name");
return 0;
}
/* This is where all the supported key types are declared. In order to preserve backward
* compatibility (reading keyring files from older versions of Serval DNA), DO NOT ERASE OR RE-USE
* ANY KEY TYPE ENTRIES FROM THIS ARRAY. If a key type is no longer used, it must be permanently
* deprecated, ie, recognised and simply skipped. The packer and unpacker functions can be changed
* to NULL.
*/
const struct keytype keytypes[] = {
[KEYTYPE_CRYPTOBOX] = {
/* Only the private key is stored, and the public key (SID) is derived from the private key
* when the keyring is read.
*/
.private_key_size = crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES,
.public_key_size = crypto_box_curve25519xsalsa20poly1305_PUBLICKEYBYTES,
.packed_size = crypto_box_curve25519xsalsa20poly1305_SECRETKEYBYTES,
.creator = create_cryptobox,
.packer = pack_private_only,
.unpacker = unpack_cryptobox,
.dumper = dump_private_public,
.loader = load_cryptobox
},
[KEYTYPE_CRYPTOSIGN] = {
/* The NaCl API does not expose any method to derive a cryptosign public key from its private
* key, although there must be an internal NaCl function to do so. Subverting the NaCl API to
* invoke that function risks incompatibility with future releases of NaCl, so instead the
* public key is stored redundantly in the keyring.
*/
.private_key_size = crypto_sign_edwards25519sha512batch_SECRETKEYBYTES,
.public_key_size = crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES,
.packed_size = crypto_sign_edwards25519sha512batch_SECRETKEYBYTES + crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES,
.creator = create_cryptosign,
.packer = pack_private_public,
.unpacker = unpack_private_public,
.dumper = dump_private_public,
.loader = load_private_public
},
[KEYTYPE_RHIZOME] = {
/* The Rhizome Secret (a large, unguessable number) is stored in the private key field, and
* the public key field is not used.
*/
.private_key_size = 32,
.public_key_size = 0,
.packed_size = 32,
.creator = create_rhizome,
.packer = pack_private_only,
.unpacker = unpack_private_only,
.dumper = dump_private_public,
.loader = load_private_only
},
[KEYTYPE_DID] = {
/* The DID is stored in unpacked form in the private key field, and the name in nul-terminated
* ASCII form in the public key field.
*/
.private_key_size = 32,
.public_key_size = 64,
.packed_size = 32 + 64,
.creator = NULL, // not included in a newly created identity
.packer = pack_did_name,
.unpacker = unpack_did_name,
.dumper = dump_did_name,
.loader = load_did_name
},
[KEYTYPE_PUBLIC_TAG] = {
.private_key_size = 0,
.public_key_size = 0, // size is derived from the stored key length
.packed_size = 0,
.creator = NULL, // not included in a newly created identity
.packer = pack_public_only,
.unpacker = unpack_public_only,
.dumper = dump_private_public,
.loader = load_unknown
}
// ADD MORE KEY TYPES HERE
};
static void keyring_free_keypair(keypair *kp)
{
if (kp->private_key) {
bzero(kp->private_key, kp->private_key_len);
free(kp->private_key);
}
if (kp->public_key) {
bzero(kp->public_key, kp->public_key_len);
free(kp->public_key);
}
bzero(kp, sizeof(keypair));
free(kp);
}
static keypair *keyring_alloc_keypair(unsigned ktype, size_t len)
{
assert(ktype != 0);
keypair *kp = emalloc_zero(sizeof(keypair));
if (!kp)
return NULL;
kp->type = ktype;
if (ktype < NELS(keytypes)) {
kp->private_key_len = keytypes[ktype].private_key_size;
kp->public_key_len = keytypes[ktype].public_key_size;
} else {
kp->private_key_len = len;
kp->public_key_len = 0;
}
if ( (kp->private_key_len && (kp->private_key = emalloc(kp->private_key_len)) == NULL)
|| (kp->public_key_len && (kp->public_key = emalloc(kp->public_key_len)) == NULL)
) {
keyring_free_keypair(kp);
return NULL;
}
return kp;
}
static int keyring_pack_identity(const keyring_identity *id, unsigned char packed[KEYRING_PAGE_SIZE])
{
/* Convert an identity to a KEYRING_PAGE_SIZE bytes long block that consists of 32 bytes of random
* salt, a 64 byte (512 bit) message authentication code (MAC) and the list of key pairs. */
if (urandombytes(packed, PKR_SALT_BYTES) == -1)
return WHY("Could not generate salt");
/* Calculate MAC */
if (keyring_identity_mac(id, packed /* pkr salt */, packed + PKR_SALT_BYTES /* write mac in after salt */) == -1)
return -1;
/* There was a known plain-text opportunity here: byte 96 must be 0x01, and some other bytes are
* likely deducible, e.g., the location of the trailing 0x00 byte can probably be guessed with
* confidence. Payload rotation will frustrate this attack.
*/
uint16_t rotation;
if (urandombytes((unsigned char *)&rotation, sizeof rotation) == -1)
return WHY("urandombytes() failed to generate random rotation");
#ifdef NO_ROTATION
rotation=0;
#endif
// The two bytes immediately following the MAC describe the rotation offset.
packed[PKR_SALT_BYTES + PKR_MAC_BYTES] = rotation >> 8;
packed[PKR_SALT_BYTES + PKR_MAC_BYTES + 1] = rotation & 0xff;
/* Pack the key pairs into the rest of the slot as a rotated buffer. */
struct rotbuf rbuf;
rotbuf_init(&rbuf,
packed + PKR_SALT_BYTES + PKR_MAC_BYTES + 2,
KEYRING_PAGE_SIZE - (PKR_SALT_BYTES + PKR_MAC_BYTES + 2),
rotation);
unsigned kp;
for (kp = 0; kp < id->keypair_count && !rbuf.wrap; ++kp) {
unsigned ktype = id->keypairs[kp]->type;
const char *kts = keytype_str(ktype, "unknown");
int (*packer)(const keypair *, struct rotbuf *) = NULL;
size_t keypair_len=0;
const struct keytype *kt = &keytypes[ktype];
if (ktype == 0x00)
FATALF("ktype=0 in keypair kp=%u", kp);
if (ktype < NELS(keytypes)) {
packer = kt->packer;
keypair_len = kt->packed_size;
if (keypair_len==0){
keypair_len = id->keypairs[kp]->private_key_len + id->keypairs[kp]->public_key_len;
}
} else {
packer = pack_private_only;
keypair_len = id->keypairs[kp]->private_key_len;
}
if (packer == NULL) {
WARNF("no packer function for key type 0x%02x(%s), omitted from keyring file", ktype, kts);
} else {
if (config.debug.keyring)
DEBUGF("pack key type = 0x%02x(%s)", ktype, kts);
// First byte is the key type code.
rotbuf_putc(&rbuf, ktype);
// The next two bytes are the key pair length, for forward compatibility: so older software can
// skip over key pairs with an unrecognised type. The original four first key types do not
// store the length, for the sake of backward compatibility with legacy keyring files. Their
// entry lengths are hard-coded.
switch (ktype) {
case KEYTYPE_CRYPTOBOX:
case KEYTYPE_CRYPTOSIGN:
case KEYTYPE_RHIZOME:
case KEYTYPE_DID:
break;
default:
rotbuf_putc(&rbuf, (keypair_len >> 8) & 0xff);
rotbuf_putc(&rbuf, keypair_len & 0xff);
break;
}
// The remaining bytes is the key pair in whatever format it uses.
struct rotbuf rbstart = rbuf;
if (packer(id->keypairs[kp], &rbuf) != 0)
break;
// Ensure the correct number of bytes were written.
unsigned packed = rotbuf_delta(&rbstart, &rbuf);
if (packed != keypair_len) {
WHYF("key type 0x%02x(%s) packed wrong length (packed %u, expecting %u)", ktype, kts, packed, (int)keypair_len);
goto scram;
}
}
}
// Final byte is a zero key type code.
rotbuf_putc(&rbuf, 0x00);
if (rbuf.wrap > 1) {
WHY("slot overrun");
goto scram;
}
if (kp < id->keypair_count) {
WHY("error filling slot");
goto scram;
}
/* Randomfill the remaining part of the slot to frustrate any known-plain-text attack on the
* keyring.
*/
{
unsigned char *buf;
size_t len;
while (rotbuf_next_chunk(&rbuf, &buf, &len))
if (urandombytes(buf, len))
return WHY("urandombytes() failed to back-fill packed identity block");
}
return 0;
scram:
/* Randomfill the entire slot to erase any secret keys that may have found their way into it, to
* avoid leaking sensitive information out through a possibly re-used memory buffer.
*/
if (urandombytes(packed, KEYRING_PAGE_SIZE) == -1)
WHY("urandombytes() failed to in-fill packed identity block");
return -1;
}
static int cmp_keypair(const keypair *a, const keypair *b)
{
int c = a->type < b->type ? -1 : a->type > b->type ? 1 : 0;
if (c == 0 && a->public_key_len) {
assert(a->public_key != NULL);
assert(b->public_key != NULL);
size_t len = a->public_key_len;
if (len > b->public_key_len)
len = b->public_key_len;
c = memcmp(a->public_key, b->public_key, len);
if (c==0 && a->public_key_len!=b->public_key_len)
c = a->public_key_len - b->public_key_len;
}
if (c == 0 && a->private_key_len) {
assert(a->private_key != NULL);
assert(b->private_key != NULL);
size_t len = a->private_key_len;
if (len > b->private_key_len)
len = b->private_key_len;
c = memcmp(a->private_key, b->private_key, len);
if (c==0 && a->private_key_len!=b->private_key_len)
c = a->private_key_len - b->private_key_len;
}
return c;
}
/* Ensure that regardless of the order in the keyring file or loaded dump, keypairs are always
* stored in memory in ascending order of (key type, public key, private key).
*/
static int keyring_identity_add_keypair(keyring_identity *id, keypair *kp)
{
assert(id->keypair_count < PKR_MAX_KEYPAIRS);
assert(kp != NULL);
int c = 1;
unsigned i = 0;
for (i = 0; i < id->keypair_count && (c = cmp_keypair(id->keypairs[i], kp)) < 0; ++i)
if (i)
assert(cmp_keypair(id->keypairs[i - 1], id->keypairs[i]) < 0);
if (c == 0)