/work/toxcore/timed_auth.c
Line | Count | Source |
1 | | /* SPDX-License-Identifier: GPL-3.0-or-later |
2 | | * Copyright © 2019-2025 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 | 174k | { |
16 | 174k | const uint64_t t = (mono_time_get(mono_time) / timeout) - (previous ? 1 : 0); |
17 | 174k | memcpy(to_hash, &t, sizeof(t)); |
18 | | |
19 | 174k | if (data != nullptr) { |
20 | 174k | memcpy(to_hash + sizeof(t), data, length); |
21 | 174k | } |
22 | 174k | } |
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 | 62.8k | { |
27 | 62.8k | const uint16_t to_hash_size = sizeof(uint64_t) + length; |
28 | 62.8k | VLA(uint8_t, to_hash, to_hash_size); |
29 | 62.8k | create_timed_auth_to_hash(mono_time, timeout, false, data, length, to_hash); |
30 | 62.8k | crypto_hmac(timed_auth, key, to_hash, to_hash_size); |
31 | 62.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 | 59.0k | { |
36 | 59.0k | const uint16_t to_hash_size = sizeof(uint64_t) + length; |
37 | 59.0k | VLA(uint8_t, to_hash, to_hash_size); |
38 | | |
39 | 163k | for (uint8_t i = 0; i < 2; ++i) { |
40 | 112k | create_timed_auth_to_hash(mono_time, timeout, i != 0, data, length, to_hash); |
41 | | |
42 | 112k | if (crypto_hmac_verify(timed_auth, key, to_hash, to_hash_size)) { |
43 | 7.44k | return true; |
44 | 7.44k | } |
45 | 112k | } |
46 | | |
47 | 51.6k | return false; |
48 | 59.0k | } |