/work/toxcore/timed_auth.c
Line | Count | Source |
1 | | /* SPDX-License-Identifier: GPL-3.0-or-later |
2 | | * Copyright © 2019-2021 The TokTok team. |
3 | | */ |
4 | | #include "timed_auth.h" |
5 | | |
6 | | #include <string.h> |
7 | | |
8 | | #include "ccompat.h" |
9 | | #include "crypto_core.h" |
10 | | #include "mono_time.h" |
11 | | |
12 | | non_null(1,6) nullable(4) |
13 | | static void create_timed_auth_to_hash(const Mono_Time *mono_time, uint16_t timeout, bool previous, const uint8_t *data, |
14 | | uint16_t length, uint8_t *to_hash) |
15 | 184k | { |
16 | 184k | const uint64_t t = (mono_time_get(mono_time) / timeout) - (previous ? 1 : 0); |
17 | 184k | memcpy(to_hash, &t, sizeof(t)); |
18 | | |
19 | 184k | if (data != nullptr) { |
20 | 184k | memcpy(to_hash + sizeof(t), data, length); |
21 | 184k | } |
22 | 184k | } |
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 | 66.6k | { |
27 | 66.6k | const uint16_t to_hash_size = sizeof(uint64_t) + length; |
28 | 66.6k | VLA(uint8_t, to_hash, to_hash_size); |
29 | 66.6k | create_timed_auth_to_hash(mono_time, timeout, false, data, length, to_hash); |
30 | 66.6k | crypto_hmac(timed_auth, key, to_hash, to_hash_size); |
31 | 66.6k | } |
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 | 62.5k | { |
36 | 62.5k | const uint16_t to_hash_size = sizeof(uint64_t) + length; |
37 | 62.5k | VLA(uint8_t, to_hash, to_hash_size); |
38 | | |
39 | 172k | for (uint8_t i = 0; i < 2; ++i) { |
40 | 117k | create_timed_auth_to_hash(mono_time, timeout, i != 0, data, length, to_hash); |
41 | | |
42 | 117k | if (crypto_hmac_verify(timed_auth, key, to_hash, to_hash_size)) { |
43 | 7.89k | return true; |
44 | 7.89k | } |
45 | 117k | } |
46 | | |
47 | 54.6k | return false; |
48 | 62.5k | } |