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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
|
/* Copyright (c) 2016-2017, The Tor Project, Inc. */
/* See LICENSE for licensing information */
/**
* \file hs_common.c
* \brief Contains code shared between different HS protocol version as well
* as useful data structures and accessors used by other subsystems.
* The rendcommon.c should only contains code relating to the v2
* protocol.
**/
#define HS_COMMON_PRIVATE
#include "or.h"
#include "config.h"
#include "networkstatus.h"
#include "nodelist.h"
#include "hs_cache.h"
#include "hs_common.h"
#include "hs_service.h"
#include "rendcommon.h"
#include "rendservice.h"
#include "router.h"
#include "shared_random.h"
#include "shared_random_state.h"
/* Ed25519 Basepoint value. Taken from section 5 of
* https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03 */
static const char *str_ed25519_basepoint =
"(15112221349535400772501151409588531511"
"454012693041857206046113283949847762202, "
"463168356949264781694283940034751631413"
"07993866256225615783033603165251855960)";
#ifdef HAVE_SYS_UN_H
/** Given <b>ports</b>, a smarlist containing rend_service_port_config_t,
* add the given <b>p</b>, a AF_UNIX port to the list. Return 0 on success
* else return -ENOSYS if AF_UNIX is not supported (see function in the
* #else statement below). */
static int
add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
{
tor_assert(ports);
tor_assert(p);
tor_assert(p->is_unix_addr);
smartlist_add(ports, p);
return 0;
}
/** Given <b>conn</b> set it to use the given port <b>p</b> values. Return 0
* on success else return -ENOSYS if AF_UNIX is not supported (see function
* in the #else statement below). */
static int
set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
{
tor_assert(conn);
tor_assert(p);
tor_assert(p->is_unix_addr);
conn->base_.socket_family = AF_UNIX;
tor_addr_make_unspec(&conn->base_.addr);
conn->base_.port = 1;
conn->base_.address = tor_strdup(p->unix_addr);
return 0;
}
#else /* defined(HAVE_SYS_UN_H) */
static int
set_unix_port(edge_connection_t *conn, rend_service_port_config_t *p)
{
(void) conn;
(void) p;
return -ENOSYS;
}
static int
add_unix_port(smartlist_t *ports, rend_service_port_config_t *p)
{
(void) ports;
(void) p;
return -ENOSYS;
}
#endif /* HAVE_SYS_UN_H */
/* Helper function: The key is a digest that we compare to a node_t object
* current hsdir_index. */
static int
compare_digest_to_current_hsdir_index(const void *_key, const void **_member)
{
const char *key = _key;
const node_t *node = *_member;
return tor_memcmp(key, node->hsdir_index->current, DIGEST256_LEN);
}
/* Helper function: The key is a digest that we compare to a node_t object
* next hsdir_index. */
static int
compare_digest_to_next_hsdir_index(const void *_key, const void **_member)
{
const char *key = _key;
const node_t *node = *_member;
return tor_memcmp(key, node->hsdir_index->next, DIGEST256_LEN);
}
/* Helper function: Compare two node_t objects current hsdir_index. */
static int
compare_node_current_hsdir_index(const void **a, const void **b)
{
const node_t *node1= *a;
const node_t *node2 = *b;
return tor_memcmp(node1->hsdir_index->current,
node2->hsdir_index->current,
DIGEST256_LEN);
}
/* Helper function: Compare two node_t objects next hsdir_index. */
static int
compare_node_next_hsdir_index(const void **a, const void **b)
{
const node_t *node1= *a;
const node_t *node2 = *b;
return tor_memcmp(node1->hsdir_index->next,
node2->hsdir_index->next,
DIGEST256_LEN);
}
/* Allocate and return a string containing the path to filename in directory.
* This function will never return NULL. The caller must free this path. */
char *
hs_path_from_filename(const char *directory, const char *filename)
{
char *file_path = NULL;
tor_assert(directory);
tor_assert(filename);
tor_asprintf(&file_path, "%s%s%s", directory, PATH_SEPARATOR, filename);
return file_path;
}
/* Make sure that the directory for <b>service</b> is private, using the config
* <b>username</b>.
* If <b>create</b> is true:
* - if the directory exists, change permissions if needed,
* - if the directory does not exist, create it with the correct permissions.
* If <b>create</b> is false:
* - if the directory exists, check permissions,
* - if the directory does not exist, check if we think we can create it.
* Return 0 on success, -1 on failure. */
int
hs_check_service_private_dir(const char *username, const char *path,
unsigned int dir_group_readable,
unsigned int create)
{
cpd_check_t check_opts = CPD_NONE;
tor_assert(path);
if (create) {
check_opts |= CPD_CREATE;
} else {
check_opts |= CPD_CHECK_MODE_ONLY;
check_opts |= CPD_CHECK;
}
if (dir_group_readable) {
check_opts |= CPD_GROUP_READ;
}
/* Check/create directory */
if (check_private_dir(path, check_opts, username) < 0) {
return -1;
}
return 0;
}
/** Get the default HS time period length in minutes from the consensus. */
STATIC uint64_t
get_time_period_length(void)
{
/* If we are on a test network, make the time period smaller than normal so
that we actually see it rotate. Specifically, make it the same length as
an SRV protocol run. */
if (get_options()->TestingTorNetwork) {
unsigned run_duration = sr_state_get_protocol_run_duration();
/* An SRV run should take more than a minute (it's 24 rounds) */
tor_assert_nonfatal(run_duration > 60);
/* Turn it from seconds to minutes before returning: */
return sr_state_get_protocol_run_duration() / 60;
}
int32_t time_period_length = networkstatus_get_param(NULL, "hsdir-interval",
HS_TIME_PERIOD_LENGTH_DEFAULT,
HS_TIME_PERIOD_LENGTH_MIN,
HS_TIME_PERIOD_LENGTH_MAX);
/* Make sure it's a positive value. */
tor_assert(time_period_length >= 0);
/* uint64_t will always be able to contain a int32_t */
return (uint64_t) time_period_length;
}
/** Get the HS time period number at time <b>now</b> */
uint64_t
hs_get_time_period_num(time_t now)
{
uint64_t time_period_num;
/* Start by calculating minutes since the epoch */
uint64_t time_period_length = get_time_period_length();
uint64_t minutes_since_epoch = now / 60;
/* Apply the rotation offset as specified by prop224 (section
* [TIME-PERIODS]), so that new time periods synchronize nicely with SRV
* publication */
unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
time_period_rotation_offset /= 60; /* go from seconds to minutes */
tor_assert(minutes_since_epoch > time_period_rotation_offset);
minutes_since_epoch -= time_period_rotation_offset;
/* Calculate the time period */
time_period_num = minutes_since_epoch / time_period_length;
return time_period_num;
}
/** Get the number of the _upcoming_ HS time period, given that the current
* time is <b>now</b>. */
uint64_t
hs_get_next_time_period_num(time_t now)
{
return hs_get_time_period_num(now) + 1;
}
/* Return the start time of the upcoming time period based on <b>now</b>. */
time_t
hs_get_start_time_of_next_time_period(time_t now)
{
uint64_t time_period_length = get_time_period_length();
/* Get start time of next time period */
uint64_t next_time_period_num = hs_get_next_time_period_num(now);
uint64_t start_of_next_tp_in_mins = next_time_period_num *time_period_length;
/* Apply rotation offset as specified by prop224 section [TIME-PERIODS] */
unsigned int time_period_rotation_offset = sr_state_get_phase_duration();
return start_of_next_tp_in_mins * 60 + time_period_rotation_offset;
}
/* Create a new rend_data_t for a specific given <b>version</b>.
* Return a pointer to the newly allocated data structure. */
static rend_data_t *
rend_data_alloc(uint32_t version)
{
rend_data_t *rend_data = NULL;
switch (version) {
case HS_VERSION_TWO:
{
rend_data_v2_t *v2 = tor_malloc_zero(sizeof(*v2));
v2->base_.version = HS_VERSION_TWO;
v2->base_.hsdirs_fp = smartlist_new();
rend_data = &v2->base_;
break;
}
default:
tor_assert(0);
break;
}
return rend_data;
}
/** Free all storage associated with <b>data</b> */
void
rend_data_free(rend_data_t *data)
{
if (!data) {
return;
}
/* By using our allocation function, this should always be set. */
tor_assert(data->hsdirs_fp);
/* Cleanup the HSDir identity digest. */
SMARTLIST_FOREACH(data->hsdirs_fp, char *, d, tor_free(d));
smartlist_free(data->hsdirs_fp);
/* Depending on the version, cleanup. */
switch (data->version) {
case HS_VERSION_TWO:
{
rend_data_v2_t *v2_data = TO_REND_DATA_V2(data);
tor_free(v2_data);
break;
}
default:
tor_assert(0);
}
}
/* Allocate and return a deep copy of <b>data</b>. */
rend_data_t *
rend_data_dup(const rend_data_t *data)
{
rend_data_t *data_dup = NULL;
smartlist_t *hsdirs_fp = smartlist_new();
tor_assert(data);
tor_assert(data->hsdirs_fp);
SMARTLIST_FOREACH(data->hsdirs_fp, char *, fp,
smartlist_add(hsdirs_fp, tor_memdup(fp, DIGEST_LEN)));
switch (data->version) {
case HS_VERSION_TWO:
{
rend_data_v2_t *v2_data = tor_memdup(TO_REND_DATA_V2(data),
sizeof(*v2_data));
data_dup = &v2_data->base_;
data_dup->hsdirs_fp = hsdirs_fp;
break;
}
default:
tor_assert(0);
break;
}
return data_dup;
}
/* Compute the descriptor ID for each HS descriptor replica and save them. A
* valid onion address must be present in the <b>rend_data</b>.
*
* Return 0 on success else -1. */
static int
compute_desc_id(rend_data_t *rend_data)
{
int ret = 0;
unsigned replica;
time_t now = time(NULL);
tor_assert(rend_data);
switch (rend_data->version) {
case HS_VERSION_TWO:
{
rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
/* Compute descriptor ID for each replicas. */
for (replica = 0; replica < ARRAY_LENGTH(v2_data->descriptor_id);
replica++) {
ret = rend_compute_v2_desc_id(v2_data->descriptor_id[replica],
v2_data->onion_address,
v2_data->descriptor_cookie,
now, replica);
if (ret < 0) {
goto end;
}
}
break;
}
default:
tor_assert(0);
}
end:
return ret;
}
/* Allocate and initialize a rend_data_t object for a service using the
* provided arguments. All arguments are optional (can be NULL), except from
* <b>onion_address</b> which MUST be set. The <b>pk_digest</b> is the hash of
* the service private key. The <b>cookie</b> is the rendezvous cookie and
* <b>auth_type</b> is which authentiation this service is configured with.
*
* Return a valid rend_data_t pointer. This only returns a version 2 object of
* rend_data_t. */
rend_data_t *
rend_data_service_create(const char *onion_address, const char *pk_digest,
const uint8_t *cookie, rend_auth_type_t auth_type)
{
/* Create a rend_data_t object for version 2. */
rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
/* We need at least one else the call is wrong. */
tor_assert(onion_address != NULL);
if (pk_digest) {
memcpy(v2->rend_pk_digest, pk_digest, sizeof(v2->rend_pk_digest));
}
if (cookie) {
memcpy(rend_data->rend_cookie, cookie, sizeof(rend_data->rend_cookie));
}
strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
v2->auth_type = auth_type;
return rend_data;
}
/* Allocate and initialize a rend_data_t object for a client request using the
* given arguments. Either an onion address or a descriptor ID is needed. Both
* can be given but in this case only the onion address will be used to make
* the descriptor fetch. The <b>cookie</b> is the rendezvous cookie and
* <b>auth_type</b> is which authentiation the service is configured with.
*
* Return a valid rend_data_t pointer or NULL on error meaning the
* descriptor IDs couldn't be computed from the given data. */
rend_data_t *
rend_data_client_create(const char *onion_address, const char *desc_id,
const char *cookie, rend_auth_type_t auth_type)
{
/* Create a rend_data_t object for version 2. */
rend_data_t *rend_data = rend_data_alloc(HS_VERSION_TWO);
rend_data_v2_t *v2= TO_REND_DATA_V2(rend_data);
/* We need at least one else the call is wrong. */
tor_assert(onion_address != NULL || desc_id != NULL);
if (cookie) {
memcpy(v2->descriptor_cookie, cookie, sizeof(v2->descriptor_cookie));
}
if (desc_id) {
memcpy(v2->desc_id_fetch, desc_id, sizeof(v2->desc_id_fetch));
}
if (onion_address) {
strlcpy(v2->onion_address, onion_address, sizeof(v2->onion_address));
if (compute_desc_id(rend_data) < 0) {
goto error;
}
}
v2->auth_type = auth_type;
return rend_data;
error:
rend_data_free(rend_data);
return NULL;
}
/* Return the onion address from the rend data. Depending on the version,
* the size of the address can vary but it's always NUL terminated. */
const char *
rend_data_get_address(const rend_data_t *rend_data)
{
tor_assert(rend_data);
switch (rend_data->version) {
case HS_VERSION_TWO:
return TO_REND_DATA_V2(rend_data)->onion_address;
default:
/* We should always have a supported version. */
tor_assert(0);
}
}
/* Return the descriptor ID for a specific replica number from the rend
* data. The returned data is a binary digest and depending on the version its
* size can vary. The size of the descriptor ID is put in <b>len_out</b> if
* non NULL. */
const char *
rend_data_get_desc_id(const rend_data_t *rend_data, uint8_t replica,
size_t *len_out)
{
tor_assert(rend_data);
switch (rend_data->version) {
case HS_VERSION_TWO:
tor_assert(replica < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS);
if (len_out) {
*len_out = DIGEST_LEN;
}
return TO_REND_DATA_V2(rend_data)->descriptor_id[replica];
default:
/* We should always have a supported version. */
tor_assert(0);
}
}
/* Return the public key digest using the given <b>rend_data</b>. The size of
* the digest is put in <b>len_out</b> (if set) which can differ depending on
* the version. */
const uint8_t *
rend_data_get_pk_digest(const rend_data_t *rend_data, size_t *len_out)
{
tor_assert(rend_data);
switch (rend_data->version) {
case HS_VERSION_TWO:
{
const rend_data_v2_t *v2_data = TO_REND_DATA_V2(rend_data);
if (len_out) {
*len_out = sizeof(v2_data->rend_pk_digest);
}
return (const uint8_t *) v2_data->rend_pk_digest;
}
default:
/* We should always have a supported version. */
tor_assert(0);
}
}
/* Using the given time period number, compute the disaster shared random
* value and put it in srv_out. It MUST be at least DIGEST256_LEN bytes. */
static void
get_disaster_srv(uint64_t time_period_num, uint8_t *srv_out)
{
crypto_digest_t *digest;
tor_assert(srv_out);
digest = crypto_digest256_new(DIGEST_SHA3_256);
/* Start setting up payload:
* H("shared-random-disaster" | INT_8(period_length) | INT_8(period_num)) */
crypto_digest_add_bytes(digest, HS_SRV_DISASTER_PREFIX,
HS_SRV_DISASTER_PREFIX_LEN);
/* Setup INT_8(period_length) | INT_8(period_num) */
{
uint64_t time_period_length = get_time_period_length();
char period_stuff[sizeof(uint64_t)*2];
size_t offset = 0;
set_uint64(period_stuff, tor_htonll(time_period_num));
offset += sizeof(uint64_t);
set_uint64(period_stuff+offset, tor_htonll(time_period_length));
offset += sizeof(uint64_t);
tor_assert(offset == sizeof(period_stuff));
crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
}
crypto_digest_get_digest(digest, (char *) srv_out, DIGEST256_LEN);
crypto_digest_free(digest);
}
/* When creating a blinded key, we need a parameter which construction is as
* follow: H(pubkey | [secret] | ed25519-basepoint | nonce).
*
* The nonce has a pre-defined format which uses the time period number
* period_num and the start of the period in second start_time_period.
*
* The secret of size secret_len is optional meaning that it can be NULL and
* thus will be ignored for the param construction.
*
* The result is put in param_out. */
static void
build_blinded_key_param(const ed25519_public_key_t *pubkey,
const uint8_t *secret, size_t secret_len,
uint64_t period_num, uint64_t period_length,
uint8_t *param_out)
{
size_t offset = 0;
uint8_t nonce[HS_KEYBLIND_NONCE_LEN];
crypto_digest_t *digest;
tor_assert(pubkey);
tor_assert(param_out);
/* Create the nonce N. The construction is as follow:
* N = "key-blind" || INT_8(period_num) || INT_8(period_length) */
memcpy(nonce, HS_KEYBLIND_NONCE_PREFIX, HS_KEYBLIND_NONCE_PREFIX_LEN);
offset += HS_KEYBLIND_NONCE_PREFIX_LEN;
set_uint64(nonce + offset, tor_htonll(period_num));
offset += sizeof(uint64_t);
set_uint64(nonce + offset, tor_htonll(period_length));
offset += sizeof(uint64_t);
tor_assert(offset == HS_KEYBLIND_NONCE_LEN);
/* Generate the parameter h and the construction is as follow:
* h = H(pubkey | [secret] | ed25519-basepoint | nonce) */
digest = crypto_digest256_new(DIGEST_SHA3_256);
crypto_digest_add_bytes(digest, (char *) pubkey, ED25519_PUBKEY_LEN);
/* Optional secret. */
if (secret) {
crypto_digest_add_bytes(digest, (char *) secret, secret_len);
}
crypto_digest_add_bytes(digest, str_ed25519_basepoint,
strlen(str_ed25519_basepoint));
crypto_digest_add_bytes(digest, (char *) nonce, sizeof(nonce));
/* Extract digest and put it in the param. */
crypto_digest_get_digest(digest, (char *) param_out, DIGEST256_LEN);
crypto_digest_free(digest);
memwipe(nonce, 0, sizeof(nonce));
}
/* Using an ed25519 public key and version to build the checksum of an
* address. Put in checksum_out. Format is:
* SHA3-256(".onion checksum" || PUBKEY || VERSION)
*
* checksum_out must be large enough to receive 32 bytes (DIGEST256_LEN). */
static void
build_hs_checksum(const ed25519_public_key_t *key, uint8_t version,
uint8_t *checksum_out)
{
size_t offset = 0;
char data[HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN];
/* Build checksum data. */
memcpy(data, HS_SERVICE_ADDR_CHECKSUM_PREFIX,
HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN);
offset += HS_SERVICE_ADDR_CHECKSUM_PREFIX_LEN;
memcpy(data + offset, key->pubkey, ED25519_PUBKEY_LEN);
offset += ED25519_PUBKEY_LEN;
set_uint8(data + offset, version);
offset += sizeof(version);
tor_assert(offset == HS_SERVICE_ADDR_CHECKSUM_INPUT_LEN);
/* Hash the data payload to create the checksum. */
crypto_digest256((char *) checksum_out, data, sizeof(data),
DIGEST_SHA3_256);
}
/* Using an ed25519 public key, checksum and version to build the binary
* representation of a service address. Put in addr_out. Format is:
* addr_out = PUBKEY || CHECKSUM || VERSION
*
* addr_out must be large enough to receive HS_SERVICE_ADDR_LEN bytes. */
static void
build_hs_address(const ed25519_public_key_t *key, const uint8_t *checksum,
uint8_t version, char *addr_out)
{
size_t offset = 0;
tor_assert(key);
tor_assert(checksum);
memcpy(addr_out, key->pubkey, ED25519_PUBKEY_LEN);
offset += ED25519_PUBKEY_LEN;
memcpy(addr_out + offset, checksum, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
set_uint8(addr_out + offset, version);
offset += sizeof(uint8_t);
tor_assert(offset == HS_SERVICE_ADDR_LEN);
}
/* Helper for hs_parse_address(): Using a binary representation of a service
* address, parse its content into the key_out, checksum_out and version_out.
* Any out variable can be NULL in case the caller would want only one field.
* checksum_out MUST at least be 2 bytes long. address must be at least
* HS_SERVICE_ADDR_LEN bytes but doesn't need to be NUL terminated. */
static void
hs_parse_address_impl(const char *address, ed25519_public_key_t *key_out,
uint8_t *checksum_out, uint8_t *version_out)
{
size_t offset = 0;
tor_assert(address);
if (key_out) {
/* First is the key. */
memcpy(key_out->pubkey, address, ED25519_PUBKEY_LEN);
}
offset += ED25519_PUBKEY_LEN;
if (checksum_out) {
/* Followed by a 2 bytes checksum. */
memcpy(checksum_out, address + offset, HS_SERVICE_ADDR_CHECKSUM_LEN_USED);
}
offset += HS_SERVICE_ADDR_CHECKSUM_LEN_USED;
if (version_out) {
/* Finally, version value is 1 byte. */
*version_out = get_uint8(address + offset);
}
offset += sizeof(uint8_t);
/* Extra safety. */
tor_assert(offset == HS_SERVICE_ADDR_LEN);
}
/* Using the given identity public key and a blinded public key, compute the
* subcredential and put it in subcred_out. This can't fail. */
void
hs_get_subcredential(const ed25519_public_key_t *identity_pk,
const ed25519_public_key_t *blinded_pk,
uint8_t *subcred_out)
{
uint8_t credential[DIGEST256_LEN];
crypto_digest_t *digest;
tor_assert(identity_pk);
tor_assert(blinded_pk);
tor_assert(subcred_out);
/* First, build the credential. Construction is as follow:
* credential = H("credential" | public-identity-key) */
digest = crypto_digest256_new(DIGEST_SHA3_256);
crypto_digest_add_bytes(digest, HS_CREDENTIAL_PREFIX,
HS_CREDENTIAL_PREFIX_LEN);
crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
ED25519_PUBKEY_LEN);
crypto_digest_get_digest(digest, (char *) credential, DIGEST256_LEN);
crypto_digest_free(digest);
/* Now, compute the subcredential. Construction is as follow:
* subcredential = H("subcredential" | credential | blinded-public-key). */
digest = crypto_digest256_new(DIGEST_SHA3_256);
crypto_digest_add_bytes(digest, HS_SUBCREDENTIAL_PREFIX,
HS_SUBCREDENTIAL_PREFIX_LEN);
crypto_digest_add_bytes(digest, (const char *) credential,
sizeof(credential));
crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
ED25519_PUBKEY_LEN);
crypto_digest_get_digest(digest, (char *) subcred_out, DIGEST256_LEN);
crypto_digest_free(digest);
memwipe(credential, 0, sizeof(credential));
}
/* From the given list of hidden service ports, find the matching one from the
* given edge connection conn and set the connection address from the service
* port object. Return 0 on success or -1 if none. */
int
hs_set_conn_addr_port(const smartlist_t *ports, edge_connection_t *conn)
{
rend_service_port_config_t *chosen_port;
unsigned int warn_once = 0;
smartlist_t *matching_ports;
tor_assert(ports);
tor_assert(conn);
matching_ports = smartlist_new();
SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
if (TO_CONN(conn)->port != p->virtual_port) {
continue;
}
if (!(p->is_unix_addr)) {
smartlist_add(matching_ports, p);
} else {
if (add_unix_port(matching_ports, p)) {
if (!warn_once) {
/* Unix port not supported so warn only once. */
log_warn(LD_REND, "Saw AF_UNIX virtual port mapping for port %d "
"which is unsupported on this platform. "
"Ignoring it.",
TO_CONN(conn)->port);
}
warn_once++;
}
}
} SMARTLIST_FOREACH_END(p);
chosen_port = smartlist_choose(matching_ports);
smartlist_free(matching_ports);
if (chosen_port) {
if (!(chosen_port->is_unix_addr)) {
/* Get a non-AF_UNIX connection ready for connection_exit_connect() */
tor_addr_copy(&TO_CONN(conn)->addr, &chosen_port->real_addr);
TO_CONN(conn)->port = chosen_port->real_port;
} else {
if (set_unix_port(conn, chosen_port)) {
/* Simply impossible to end up here else we were able to add a Unix
* port without AF_UNIX support... ? */
tor_assert(0);
}
}
}
return (chosen_port) ? 0 : -1;
}
/* Using a base32 representation of a service address, parse its content into
* the key_out, checksum_out and version_out. Any out variable can be NULL in
* case the caller would want only one field. checksum_out MUST at least be 2
* bytes long.
*
* Return 0 if parsing went well; return -1 in case of error. */
int
hs_parse_address(const char *address, ed25519_public_key_t *key_out,
uint8_t *checksum_out, uint8_t *version_out)
{
char decoded[HS_SERVICE_ADDR_LEN];
tor_assert(address);
/* Obvious length check. */
if (strlen(address) != HS_SERVICE_ADDR_LEN_BASE32) {
log_warn(LD_REND, "Service address %s has an invalid length. "
"Expected %lu but got %lu.",
escaped_safe_str(address),
(unsigned long) HS_SERVICE_ADDR_LEN_BASE32,
(unsigned long) strlen(address));
goto invalid;
}
/* Decode address so we can extract needed fields. */
if (base32_decode(decoded, sizeof(decoded), address, strlen(address)) < 0) {
log_warn(LD_REND, "Service address %s can't be decoded.",
escaped_safe_str(address));
goto invalid;
}
/* Parse the decoded address into the fields we need. */
hs_parse_address_impl(decoded, key_out, checksum_out, version_out);
return 0;
invalid:
return -1;
}
/* Validate a given onion address. The length, the base32 decoding and
* checksum are validated. Return 1 if valid else 0. */
int
hs_address_is_valid(const char *address)
{
uint8_t version;
uint8_t checksum[HS_SERVICE_ADDR_CHECKSUM_LEN_USED];
uint8_t target_checksum[DIGEST256_LEN];
ed25519_public_key_t key;
/* Parse the decoded address into the fields we need. */
if (hs_parse_address(address, &key, checksum, &version) < 0) {
goto invalid;
}
/* Get the checksum it's suppose to be and compare it with what we have
* encoded in the address. */
build_hs_checksum(&key, version, target_checksum);
if (tor_memcmp(checksum, target_checksum, sizeof(checksum))) {
log_warn(LD_REND, "Service address %s invalid checksum.",
escaped_safe_str(address));
goto invalid;
}
/* Valid address. */
return 1;
invalid:
return 0;
}
/* Build a service address using an ed25519 public key and a given version.
* The returned address is base32 encoded and put in addr_out. The caller MUST
* make sure the addr_out is at least HS_SERVICE_ADDR_LEN_BASE32 + 1 long.
*
* Format is as follow:
* base32(PUBKEY || CHECKSUM || VERSION)
* CHECKSUM = H(".onion checksum" || PUBKEY || VERSION)
* */
void
hs_build_address(const ed25519_public_key_t *key, uint8_t version,
char *addr_out)
{
uint8_t checksum[DIGEST256_LEN];
char address[HS_SERVICE_ADDR_LEN];
tor_assert(key);
tor_assert(addr_out);
/* Get the checksum of the address. */
build_hs_checksum(key, version, checksum);
/* Get the binary address representation. */
build_hs_address(key, checksum, version, address);
/* Encode the address. addr_out will be NUL terminated after this. */
base32_encode(addr_out, HS_SERVICE_ADDR_LEN_BASE32 + 1, address,
sizeof(address));
/* Validate what we just built. */
tor_assert(hs_address_is_valid(addr_out));
}
/* Return a newly allocated copy of lspec. */
link_specifier_t *
hs_link_specifier_dup(const link_specifier_t *lspec)
{
link_specifier_t *dup = link_specifier_new();
memcpy(dup, lspec, sizeof(*dup));
/* The unrecognized field is a dynamic array so make sure to copy its
* content and not the pointer. */
link_specifier_setlen_un_unrecognized(
dup, link_specifier_getlen_un_unrecognized(lspec));
if (link_specifier_getlen_un_unrecognized(dup)) {
memcpy(link_specifier_getarray_un_unrecognized(dup),
link_specifier_getconstarray_un_unrecognized(lspec),
link_specifier_getlen_un_unrecognized(dup));
}
return dup;
}
/* From a given ed25519 public key pk and an optional secret, compute a
* blinded public key and put it in blinded_pk_out. This is only useful to
* the client side because the client only has access to the identity public
* key of the service. */
void
hs_build_blinded_pubkey(const ed25519_public_key_t *pk,
const uint8_t *secret, size_t secret_len,
uint64_t time_period_num,
ed25519_public_key_t *blinded_pk_out)
{
/* Our blinding key API requires a 32 bytes parameter. */
uint8_t param[DIGEST256_LEN];
tor_assert(pk);
tor_assert(blinded_pk_out);
tor_assert(!tor_mem_is_zero((char *) pk, ED25519_PUBKEY_LEN));
build_blinded_key_param(pk, secret, secret_len,
time_period_num, get_time_period_length(), param);
ed25519_public_blind(blinded_pk_out, pk, param);
memwipe(param, 0, sizeof(param));
}
/* From a given ed25519 keypair kp and an optional secret, compute a blinded
* keypair for the current time period and put it in blinded_kp_out. This is
* only useful by the service side because the client doesn't have access to
* the identity secret key. */
void
hs_build_blinded_keypair(const ed25519_keypair_t *kp,
const uint8_t *secret, size_t secret_len,
uint64_t time_period_num,
ed25519_keypair_t *blinded_kp_out)
{
/* Our blinding key API requires a 32 bytes parameter. */
uint8_t param[DIGEST256_LEN];
tor_assert(kp);
tor_assert(blinded_kp_out);
/* Extra safety. A zeroed key is bad. */
tor_assert(!tor_mem_is_zero((char *) &kp->pubkey, ED25519_PUBKEY_LEN));
tor_assert(!tor_mem_is_zero((char *) &kp->seckey, ED25519_SECKEY_LEN));
build_blinded_key_param(&kp->pubkey, secret, secret_len,
time_period_num, get_time_period_length(), param);
ed25519_keypair_blind(blinded_kp_out, kp, param);
memwipe(param, 0, sizeof(param));
}
/* Return true if overlap mode is active given the date in consensus. If
* consensus is NULL, then we use the latest live consensus we can find. */
MOCK_IMPL(int,
hs_overlap_mode_is_active, (const networkstatus_t *consensus, time_t now))
{
time_t valid_after;
time_t srv_start_time, tp_start_time;
if (!consensus) {
consensus = networkstatus_get_live_consensus(now);
if (!consensus) {
return 0;
}
}
/* We consider to be in overlap mode when we are in the period of time
* between a fresh SRV and the beginning of the new time period (in the
* normal network this is between 00:00 (inclusive) and 12:00 UTC
* (exclusive)) */
valid_after = consensus->valid_after;
srv_start_time =sr_state_get_start_time_of_current_protocol_run(valid_after);
tp_start_time = hs_get_start_time_of_next_time_period(srv_start_time);
if (valid_after >= srv_start_time && valid_after < tp_start_time) {
return 1;
}
return 0;
}
/* Return 1 if any virtual port in ports needs a circuit with good uptime.
* Else return 0. */
int
hs_service_requires_uptime_circ(const smartlist_t *ports)
{
tor_assert(ports);
SMARTLIST_FOREACH_BEGIN(ports, rend_service_port_config_t *, p) {
if (smartlist_contains_int_as_string(get_options()->LongLivedPorts,
p->virtual_port)) {
return 1;
}
} SMARTLIST_FOREACH_END(p);
return 0;
}
/* Build hs_index which is used to find the responsible hsdirs. This index
* value is used to select the responsible HSDir where their hsdir_index is
* closest to this value.
* SHA3-256("store-at-idx" | blinded_public_key |
* INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) )
*
* hs_index_out must be large enough to receive DIGEST256_LEN bytes. */
void
hs_build_hs_index(uint64_t replica, const ed25519_public_key_t *blinded_pk,
uint64_t period_num, uint8_t *hs_index_out)
{
crypto_digest_t *digest;
tor_assert(blinded_pk);
tor_assert(hs_index_out);
/* Build hs_index. See construction at top of function comment. */
digest = crypto_digest256_new(DIGEST_SHA3_256);
crypto_digest_add_bytes(digest, HS_INDEX_PREFIX, HS_INDEX_PREFIX_LEN);
crypto_digest_add_bytes(digest, (const char *) blinded_pk->pubkey,
ED25519_PUBKEY_LEN);
/* Now setup INT_8(replicanum) | INT_8(period_length) | INT_8(period_num) */
{
uint64_t period_length = get_time_period_length();
char buf[sizeof(uint64_t)*3];
size_t offset = 0;
set_uint64(buf, tor_htonll(replica));
offset += sizeof(uint64_t);
set_uint64(buf, tor_htonll(period_length));
offset += sizeof(uint64_t);
set_uint64(buf, tor_htonll(period_num));
offset += sizeof(uint64_t);
tor_assert(offset == sizeof(buf));
crypto_digest_add_bytes(digest, buf, sizeof(buf));
}
crypto_digest_get_digest(digest, (char *) hs_index_out, DIGEST256_LEN);
crypto_digest_free(digest);
}
/* Build hsdir_index which is used to find the responsible hsdirs. This is the
* index value that is compare to the hs_index when selecting an HSDir.
* SHA3-256("node-idx" | node_identity |
* shared_random_value | INT_8(period_length) | INT_8(period_num) )
*
* hsdir_index_out must be large enough to receive DIGEST256_LEN bytes. */
void
hs_build_hsdir_index(const ed25519_public_key_t *identity_pk,
const uint8_t *srv_value, uint64_t period_num,
uint8_t *hsdir_index_out)
{
crypto_digest_t *digest;
tor_assert(identity_pk);
tor_assert(srv_value);
tor_assert(hsdir_index_out);
/* Build hsdir_index. See construction at top of function comment. */
digest = crypto_digest256_new(DIGEST_SHA3_256);
crypto_digest_add_bytes(digest, HSDIR_INDEX_PREFIX, HSDIR_INDEX_PREFIX_LEN);
crypto_digest_add_bytes(digest, (const char *) identity_pk->pubkey,
ED25519_PUBKEY_LEN);
crypto_digest_add_bytes(digest, (const char *) srv_value, DIGEST256_LEN);
{
uint64_t time_period_length = get_time_period_length();
char period_stuff[sizeof(uint64_t)*2];
size_t offset = 0;
set_uint64(period_stuff, tor_htonll(period_num));
offset += sizeof(uint64_t);
set_uint64(period_stuff+offset, tor_htonll(time_period_length));
offset += sizeof(uint64_t);
tor_assert(offset == sizeof(period_stuff));
crypto_digest_add_bytes(digest, period_stuff, sizeof(period_stuff));
}
crypto_digest_get_digest(digest, (char *) hsdir_index_out, DIGEST256_LEN);
crypto_digest_free(digest);
}
/* Return a newly allocated buffer containing the current shared random value
* or if not present, a disaster value is computed using the given time period
* number. This function can't fail. */
uint8_t *
hs_get_current_srv(uint64_t time_period_num)
{
uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
const sr_srv_t *current_srv = sr_get_current();
if (current_srv) {
memcpy(sr_value, current_srv->value, sizeof(current_srv->value));
} else {
/* Disaster mode. */
get_disaster_srv(time_period_num, sr_value);
}
return sr_value;
}
/* Return a newly allocated buffer containing the previous shared random
* value or if not present, a disaster value is computed using the given time
* period number. This function can't fail. */
uint8_t *
hs_get_previous_srv(uint64_t time_period_num)
{
uint8_t *sr_value = tor_malloc_zero(DIGEST256_LEN);
const sr_srv_t *previous_srv = sr_get_previous();
if (previous_srv) {
memcpy(sr_value, previous_srv->value, sizeof(previous_srv->value));
} else {
/* Disaster mode. */
get_disaster_srv(time_period_num, sr_value);
}
return sr_value;
}
/* Return the number of replicas defined by a consensus parameter or the
* default value. */
int32_t
hs_get_hsdir_n_replicas(void)
{
/* The [1,16] range is a specification requirement. */
return networkstatus_get_param(NULL, "hsdir_n_replicas",
HS_DEFAULT_HSDIR_N_REPLICAS, 1, 16);
}
/* Return the spread fetch value defined by a consensus parameter or the
* default value. */
int32_t
hs_get_hsdir_spread_fetch(void)
{
/* The [1,128] range is a specification requirement. */
return networkstatus_get_param(NULL, "hsdir_spread_fetch",
HS_DEFAULT_HSDIR_SPREAD_FETCH, 1, 128);
}
/* Return the spread store value defined by a consensus parameter or the
* default value. */
int32_t
hs_get_hsdir_spread_store(void)
{
/* The [1,128] range is a specification requirement. */
return networkstatus_get_param(NULL, "hsdir_spread_store",
HS_DEFAULT_HSDIR_SPREAD_STORE, 1, 128);
}
/* For a given blinded key and time period number, get the responsible HSDir
* and put their routerstatus_t object in the responsible_dirs list. If
* is_next_period is true, the next hsdir_index of the node_t is used. If
* is_client is true, the spread fetch consensus parameter is used else the
* spread store is used which is only for upload. This function can't fail but
* it is possible that the responsible_dirs list contains fewer nodes than
* expected.
*
* This function goes over the latest consensus routerstatus list and sorts it
* by their node_t hsdir_index then does a binary search to find the closest
* node. All of this makes it a bit CPU intensive so use it wisely. */
void
hs_get_responsible_hsdirs(const ed25519_public_key_t *blinded_pk,
uint64_t time_period_num, int is_next_period,
int is_client, smartlist_t *responsible_dirs)
{
smartlist_t *sorted_nodes;
/* The compare function used for the smartlist bsearch. We have two
* different depending on is_next_period. */
int (*cmp_fct)(const void *, const void **);
tor_assert(blinded_pk);
tor_assert(responsible_dirs);
sorted_nodes = smartlist_new();
/* Add every node_t that support HSDir v3 for which we do have a valid
* hsdir_index already computed for them for this consensus. */
{
networkstatus_t *c = networkstatus_get_latest_consensus();
if (!c || smartlist_len(c->routerstatus_list) == 0) {
log_warn(LD_REND, "No valid consensus so we can't get the responsible "
"hidden service directories.");
goto done;
}
SMARTLIST_FOREACH_BEGIN(c->routerstatus_list, const routerstatus_t *, rs) {
/* Even though this node_t object won't be modified and should be const,
* we can't add const object in a smartlist_t. */
node_t *n = node_get_mutable_by_id(rs->identity_digest);
tor_assert(n);
if (node_supports_v3_hsdir(n) && rs->is_hs_dir) {
if (BUG(n->hsdir_index == NULL)) {
continue;
}
smartlist_add(sorted_nodes, n);
}
} SMARTLIST_FOREACH_END(rs);
}
if (smartlist_len(sorted_nodes) == 0) {
log_warn(LD_REND, "No nodes found to be HSDir or supporting v3.");
goto done;
}
/* First thing we have to do is sort all node_t by hsdir_index. The
* is_next_period tells us if we want the current or the next one. Set the
* bsearch compare function also while we are at it. */
if (is_next_period) {
smartlist_sort(sorted_nodes, compare_node_next_hsdir_index);
cmp_fct = compare_digest_to_next_hsdir_index;
} else {
smartlist_sort(sorted_nodes, compare_node_current_hsdir_index);
cmp_fct = compare_digest_to_current_hsdir_index;
}
/* For all replicas, we'll select a set of HSDirs using the consensus
* parameters and the sorted list. The replica starting at value 1 is
* defined by the specification. */
for (int replica = 1; replica <= hs_get_hsdir_n_replicas(); replica++) {
int idx, start, found, n_added = 0;
uint8_t hs_index[DIGEST256_LEN] = {0};
/* Number of node to add to the responsible dirs list depends on if we are
* trying to fetch or store. A client always fetches. */
int n_to_add = (is_client) ? hs_get_hsdir_spread_fetch() :
hs_get_hsdir_spread_store();
/* Get the index that we should use to select the node. */
hs_build_hs_index(replica, blinded_pk, time_period_num, hs_index);
/* The compare function pointer has been set correctly earlier. */
start = idx = smartlist_bsearch_idx(sorted_nodes, hs_index, cmp_fct,
&found);
/* Getting the length of the list if no member is greater than the key we
* are looking for so start at the first element. */
if (idx == smartlist_len(sorted_nodes)) {
start = idx = 0;
}
while (n_added < n_to_add) {
const node_t *node = smartlist_get(sorted_nodes, idx);
/* If the node has already been selected which is possible between
* replicas, the specification says to skip over. */
if (!smartlist_contains(responsible_dirs, node->rs)) {
smartlist_add(responsible_dirs, node->rs);
++n_added;
}
if (++idx == smartlist_len(sorted_nodes)) {
/* Wrap if we've reached the end of the list. */
idx = 0;
}
if (idx == start) {
/* We've gone over the whole list, stop and avoid infinite loop. */
break;
}
}
}
done:
smartlist_free(sorted_nodes);
}
/* Initialize the entire HS subsytem. This is called in tor_init() before any
* torrc options are loaded. Only for >= v3. */
void
hs_init(void)
{
hs_circuitmap_init();
hs_service_init();
hs_cache_init();
}
/* Release and cleanup all memory of the HS subsystem (all version). This is
* called by tor_free_all(). */
void
hs_free_all(void)
{
hs_circuitmap_free_all();
hs_service_free_all();
hs_cache_free_all();
}
|