Coverage Report

Created: 2026-10-24 08:16

/work/toxcore/timed_auth.c
Line
Count
Source
1
/* SPDX-License-Identifier: GPL-3.0-or-later
2
 * Copyright © 2019-2026 The TokTok team.
3
 */
4
#include "timed_auth.h"
5
6
#include <string.h>
7
8
#include "attributes.h"
9
#include "ccompat.h"
10
#include "crypto_core.h"
11
#include "mono_time.h"
12
13
static void create_timed_auth_to_hash(const Mono_Time *_Nonnull mono_time, uint16_t timeout, bool previous, const uint8_t *_Nullable data,
14
                                      uint16_t length, uint8_t *_Nonnull to_hash)
15
103k
{
16
103k
    const uint64_t t = (mono_time_get(mono_time) / timeout) - (previous ? 1 : 0);
17
103k
    memcpy(to_hash, &t, sizeof(t));
18
19
103k
    if (data != nullptr) {
20
103k
        memcpy(to_hash + sizeof(t), data, length);
21
103k
    }
22
103k
}
23
24
void generate_timed_auth(const Mono_Time *mono_time, uint16_t timeout, const uint8_t *key,
25
                         const uint8_t *data, uint16_t length, uint8_t *timed_auth)
26
39.8k
{
27
39.8k
    const uint16_t to_hash_size = sizeof(uint64_t) + length;
28
39.8k
    VLA(uint8_t, to_hash, to_hash_size);
29
39.8k
    create_timed_auth_to_hash(mono_time, timeout, false, data, length, to_hash);
30
39.8k
    crypto_hmac(timed_auth, key, to_hash, to_hash_size);
31
39.8k
}
32
33
bool check_timed_auth(const Mono_Time *mono_time, uint16_t timeout, const uint8_t *key, const uint8_t *data,
34
                      uint16_t length, const uint8_t *timed_auth)
35
34.3k
{
36
34.3k
    const uint16_t to_hash_size = sizeof(uint64_t) + length;
37
34.3k
    VLA(uint8_t, to_hash, to_hash_size);
38
39
93.3k
    for (uint8_t i = 0; i < 2; ++i) {
40
63.8k
        create_timed_auth_to_hash(mono_time, timeout, i != 0, data, length, to_hash);
41
42
63.8k
        if (crypto_hmac_verify(timed_auth, key, to_hash, to_hash_size)) {
43
4.89k
            return true;
44
4.89k
        }
45
63.8k
    }
46
47
29.4k
    return false;
48
34.3k
}