Coverage Report

Created: 2026-10-24 08:16

/work/toxcore/shared_key_cache.c
Line
Count
Source (jump to first uncovered line)
1
/* SPDX-License-Identifier: GPL-3.0-or-later
2
 * Copyright © 2022-2026 The TokTok team.
3
 */
4
5
#include "shared_key_cache.h"
6
7
#include <stdint.h>
8
#include <string.h>     // memcpy(...)
9
10
#include "attributes.h"
11
#include "ccompat.h"
12
#include "crypto_core.h"
13
#include "logger.h"
14
#include "mem.h"
15
#include "mono_time.h"
16
17
typedef struct Shared_Key {
18
    uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE];
19
    uint8_t shared_key[CRYPTO_SHARED_KEY_SIZE];
20
    uint64_t time_last_requested;
21
} Shared_Key;
22
23
struct Shared_Key_Cache {
24
    Shared_Key *_Nonnull keys;
25
    const uint8_t *_Nonnull self_secret_key;
26
    uint64_t timeout; /** After this time (in seconds), a key is erased on the next housekeeping cycle */
27
    const Mono_Time *_Nonnull mono_time;
28
    const Memory *_Nonnull mem;
29
    const Logger *_Nonnull log;
30
    uint8_t keys_per_slot;
31
};
32
33
static bool shared_key_is_empty(const Logger *_Nonnull log, const Shared_Key *_Nonnull k)
34
1.98M
{
35
1.98M
    LOGGER_ASSERT(log, k != nullptr, "shared key must not be NULL");
36
    /*
37
     * Since time can never be 0, we use that to determine if a key slot is empty.
38
     * Additionally this allows us to use crypto_memzero and leave the slot in a valid state.
39
     */
40
1.98M
    return k->time_last_requested == 0;
41
1.98M
}
42
43
static void shared_key_set_empty(const Logger *_Nonnull log, Shared_Key *_Nonnull k)
44
8.80k
{
45
8.80k
    crypto_memzero(k, sizeof(Shared_Key));
46
8.80k
    LOGGER_ASSERT(log, shared_key_is_empty(log, k), "shared key must be empty after clearing it");
47
8.80k
}
48
49
Shared_Key_Cache *shared_key_cache_new(const Logger *log, const Mono_Time *mono_time, const Memory *mem, const uint8_t *self_secret_key, uint64_t timeout, uint8_t keys_per_slot)
50
13.7k
{
51
13.7k
    if (mono_time == nullptr || self_secret_key == nullptr || timeout == 0 || keys_per_slot == 0) {
52
0
        return nullptr;
53
0
    }
54
55
    // Time must not be zero, since we use that as special value for empty slots
56
13.7k
    if (mono_time_get(mono_time) == 0) {
57
        // Fail loudly in debug environments
58
0
        LOGGER_FATAL(log, "time must not be zero (mono_time not initialised?)");
59
0
        return nullptr;
60
0
    }
61
62
13.7k
    Shared_Key_Cache *res = (Shared_Key_Cache *)mem_alloc(mem, sizeof(Shared_Key_Cache));
63
13.7k
    if (res == nullptr) {
64
30
        return nullptr;
65
30
    }
66
67
13.6k
    res->self_secret_key = self_secret_key;
68
13.6k
    res->mono_time = mono_time;
69
13.6k
    res->mem = mem;
70
13.6k
    res->log = log;
71
13.6k
    res->keys_per_slot = keys_per_slot;
72
73
    // We take one byte from the public key for each bucket and store keys_per_slot elements there
74
13.6k
    const size_t cache_size = 256 * keys_per_slot;
75
13.6k
    Shared_Key *keys = (Shared_Key *)mem_valloc(mem, cache_size, sizeof(Shared_Key));
76
77
13.6k
    if (keys == nullptr) {
78
27
        mem_delete(mem, res);
79
27
        return nullptr;
80
27
    }
81
82
13.6k
    crypto_memlock(keys, cache_size * sizeof(Shared_Key));
83
84
13.6k
    res->keys = keys;
85
86
13.6k
    return res;
87
13.6k
}
88
89
void shared_key_cache_free(Shared_Key_Cache *cache)
90
13.6k
{
91
13.6k
    if (cache == nullptr) {
92
115
        return;
93
115
    }
94
95
13.5k
    const size_t cache_size = 256 * cache->keys_per_slot;
96
    // Don't leave key material in memory
97
13.5k
    crypto_memzero(cache->keys, cache_size * sizeof(Shared_Key));
98
13.5k
    crypto_memunlock(cache->keys, cache_size * sizeof(Shared_Key));
99
13.5k
    mem_delete(cache->mem, cache->keys);
100
13.5k
    mem_delete(cache->mem, cache);
101
13.5k
}
102
103
/* NOTE: On each lookup housekeeping is performed to evict keys that did timeout. */
104
const uint8_t *shared_key_cache_lookup(Shared_Key_Cache *cache, const uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE])
105
364k
{
106
    // caching the time is not necessary, but calls to mono_time_get(...) are not free
107
364k
    const uint64_t cur_time = mono_time_get(cache->mono_time);
108
    // We can't use the first and last bytes because they are masked in curve25519. Selected 8 for good alignment.
109
364k
    const uint8_t bucket_idx = public_key[8];
110
364k
    Shared_Key *bucket_start = &cache->keys[bucket_idx * cache->keys_per_slot];
111
112
364k
    const uint8_t *found = nullptr;
113
114
    // Perform lookup
115
560k
    for (size_t i = 0; i < cache->keys_per_slot; ++i) {
116
515k
        if (shared_key_is_empty(cache->log, &bucket_start[i])) {
117
174k
            continue;
118
174k
        }
119
120
340k
        if (pk_equal(public_key, bucket_start[i].public_key)) {
121
319k
            found = bucket_start[i].shared_key;
122
319k
            bucket_start[i].time_last_requested = cur_time;
123
319k
            break;
124
319k
        }
125
340k
    }
126
127
    // Perform housekeeping for this bucket
128
1.82M
    for (size_t i = 0; i < cache->keys_per_slot; ++i) {
129
1.45M
        if (shared_key_is_empty(cache->log, &bucket_start[i])) {
130
1.11M
            continue;
131
1.11M
        }
132
133
347k
        const bool timed_out = (bucket_start[i].time_last_requested + cache->timeout) < cur_time;
134
347k
        if (timed_out) {
135
8.80k
            shared_key_set_empty(cache->log, &bucket_start[i]);
136
8.80k
        }
137
347k
    }
138
139
364k
    if (found == nullptr) {
140
        // Insert into cache
141
142
45.5k
        uint64_t oldest_timestamp = UINT64_MAX;
143
45.5k
        size_t oldest_index = 0;
144
145
        /*
146
         *  Find least recently used entry, unused entries are prioritised,
147
         *  because their time_last_requested field is zeroed.
148
         */
149
227k
        for (size_t i = 0; i < cache->keys_per_slot; ++i) {
150
182k
            if (bucket_start[i].time_last_requested < oldest_timestamp) {
151
50.3k
                oldest_timestamp = bucket_start[i].time_last_requested;
152
50.3k
                oldest_index = i;
153
50.3k
            }
154
182k
        }
155
156
        // Compute the shared key for the cache
157
45.5k
        if (encrypt_precompute(public_key, cache->self_secret_key, bucket_start[oldest_index].shared_key) != 0) {
158
            // Don't put anything in the cache on error
159
0
            return nullptr;
160
0
        }
161
162
        // update cache entry
163
45.5k
        memcpy(bucket_start[oldest_index].public_key, public_key, CRYPTO_PUBLIC_KEY_SIZE);
164
45.5k
        bucket_start[oldest_index].time_last_requested = cur_time;
165
45.5k
        found = bucket_start[oldest_index].shared_key;
166
45.5k
    }
167
168
364k
    return found;
169
364k
}