aboutsummaryrefslogtreecommitdiffstats
path: root/driver/peerlookup.c
blob: 812060f90318edd2228944d8e433bcf3e9d2ba17 (plain) (blame)
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
/* SPDX-License-Identifier: GPL-2.0
 *
 * Copyright (C) 2015-2021 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
 */

#include "containers.h"
#include "noise.h"
#include "peer.h"
#include "peerlookup.h"

_Post_notnull_
static HLIST_HEAD *
PubkeyBucket(_In_ PUBKEY_HASHTABLE *Table, _In_ CONST UINT8 Pubkey[NOISE_PUBLIC_KEY_LEN])
{
    /* siphash gives us a secure 64bit number based on a random key. Since
     * the bits are uniformly distributed, we can then mask off to get the
     * bits we need.
     */
    CONST UINT64 Hash = Siphash(Pubkey, NOISE_PUBLIC_KEY_LEN, &Table->Key);

    return &Table->Hashtable[Hash & (HASH_SIZE(Table->Hashtable) - 1)];
}

_Use_decl_annotations_
PUBKEY_HASHTABLE *PubkeyHashtableAlloc(VOID)
{
    PUBKEY_HASHTABLE *Table = MemAllocate(sizeof(*Table));
    if (!Table)
        return NULL;

    CryptoRandom(&Table->Key, sizeof(Table->Key));
    HashInit(Table->Hashtable);
    MuInitializePushLock(&Table->Lock);
    return Table;
}

_Use_decl_annotations_
VOID
PubkeyHashtableAdd(PUBKEY_HASHTABLE *Table, WG_PEER *Peer)
{
    MuAcquirePushLockExclusive(&Table->Lock);
    HlistAddHeadRcu(&Peer->PubkeyHash, PubkeyBucket(Table, Peer->Handshake.RemoteStatic));
    MuReleasePushLockExclusive(&Table->Lock);
}

_Use_decl_annotations_
VOID
PubkeyHashtableRemove(PUBKEY_HASHTABLE *Table, WG_PEER *Peer)
{
    MuAcquirePushLockExclusive(&Table->Lock);
    HlistDelInitRcu(&Peer->PubkeyHash);
    MuReleasePushLockExclusive(&Table->Lock);
}

_Use_decl_annotations_
WG_PEER *
PubkeyHashtableLookup(PUBKEY_HASHTABLE *Table, CONST UINT8 Pubkey[NOISE_PUBLIC_KEY_LEN])
{
    WG_PEER *IterPeer, *Peer = NULL;
    KIRQL Irql;

    Irql = RcuReadLock();
    HLIST_FOR_EACH_ENTRY_RCU (IterPeer, PubkeyBucket(Table, Pubkey), WG_PEER, PubkeyHash)
    {
        if (RtlEqualMemory(Pubkey, IterPeer->Handshake.RemoteStatic, NOISE_PUBLIC_KEY_LEN))
        {
            Peer = IterPeer;
            break;
        }
    }
    Peer = PeerGetMaybeZero(Peer);
    RcuReadUnlock(Irql);
    return Peer;
}

_Post_notnull_
static HLIST_HEAD *
IndexBucket(_In_ INDEX_HASHTABLE *Table, _In_ CONST UINT32_LE Index)
{
    /* Since the indices are random and thus all bits are uniformly
     * distributed, we can find its bucket simply by masking.
     */
    return &Table->Hashtable[(UINT32)Index & (HASH_SIZE(Table->Hashtable) - 1)];
}

_Use_decl_annotations_
INDEX_HASHTABLE *IndexHashtableAlloc(VOID)
{
    INDEX_HASHTABLE *Table = MemAllocate(sizeof(*Table));
    if (!Table)
        return NULL;

    HashInit(Table->Hashtable);
    KeInitializeSpinLock(&Table->Lock);
    return Table;
}

/* At the moment, we limit ourselves to 2^20 total peers, which generally might
 * amount to 2^20*3 items in this hashtable. The algorithm below works by
 * picking a random number and testing it. We can see that these limits mean we
 * usually succeed pretty quickly:
 *
 * >>> def calculation(tries, size):
 * ...     return (size / 2**32)**(tries - 1) *  (1 - (size / 2**32))
 * ...
 * >>> calculation(1, 2**20 * 3)
 * 0.999267578125
 * >>> calculation(2, 2**20 * 3)
 * 0.0007318854331970215
 * >>> calculation(3, 2**20 * 3)
 * 5.360489012673497e-07
 * >>> calculation(4, 2**20 * 3)
 * 3.9261394135792216e-10
 *
 * At the moment, we don't do any masking, so this algorithm isn't exactly
 * constant time in either the random guessing or in the hash list lookup. We
 * could require a minimum of 3 tries, which would successfully mask the
 * guessing. this would not, however, help with the growing hash lengths, which
 * is another thing to consider moving forward.
 */

_Use_decl_annotations_
UINT32_LE
IndexHashtableInsert(INDEX_HASHTABLE *Table, INDEX_HASHTABLE_ENTRY *Entry)
{
    INDEX_HASHTABLE_ENTRY *ExistingEntry;
    KIRQL Irql;

    KeAcquireSpinLock(&Table->Lock, &Irql);
    HlistDelInitRcu(&Entry->IndexHash);
    KeReleaseSpinLock(&Table->Lock, Irql);

    Irql = RcuReadLock();

searchUnusedSlot:
    /* First we try to find an unused slot, randomly, while unlocked. */
    CryptoRandom(&Entry->Index, sizeof(Entry->Index));
    HLIST_FOR_EACH_ENTRY_RCU (ExistingEntry, IndexBucket(Table, Entry->Index), INDEX_HASHTABLE_ENTRY, IndexHash)
    {
        if (ExistingEntry->Index == Entry->Index)
            /* If it's already in use, we continue searching. */
            goto searchUnusedSlot;
    }

    /* Once we've found an unused slot, we lock it, and then double-check
     * that nobody else stole it from us.
     */
    KeAcquireSpinLockAtDpcLevel(&Table->Lock);
    HLIST_FOR_EACH_ENTRY_RCU (ExistingEntry, IndexBucket(Table, Entry->Index), INDEX_HASHTABLE_ENTRY, IndexHash)
    {
        if (ExistingEntry->Index == Entry->Index)
        {
            KeReleaseSpinLockFromDpcLevel(&Table->Lock);
            /* If it was stolen, we start over. */
            goto searchUnusedSlot;
        }
    }
    /* Otherwise, we know we have it exclusively (since we're locked),
     * so we insert.
     */
    HlistAddHeadRcu(&Entry->IndexHash, IndexBucket(Table, Entry->Index));
    KeReleaseSpinLockFromDpcLevel(&Table->Lock);

    RcuReadUnlock(Irql);

    return Entry->Index;
}

_Use_decl_annotations_
BOOLEAN
IndexHashtableReplace(INDEX_HASHTABLE *Table, INDEX_HASHTABLE_ENTRY *Old, INDEX_HASHTABLE_ENTRY *New)
{
    BOOLEAN Ret;
    KIRQL Irql;

    KeAcquireSpinLock(&Table->Lock, &Irql);
    Ret = !HlistUnhashed(&Old->IndexHash);
    if (!Ret)
        goto out;

    New->Index = Old->Index;
    HlistReplaceRcu(&Old->IndexHash, &New->IndexHash);

    /* Calling init here NULLs out IndexHash, and in fact after this
     * function returns, it's theoretically possible for this to get
     * reinserted elsewhere. That means the RCU lookup below might either
     * terminate early or jump between buckets, in which case the packet
     * simply gets dropped, which isn't terrible.
     */
    HlistInit(&Old->IndexHash);
out:
    KeReleaseSpinLock(&Table->Lock, Irql);
    return Ret;
}

_Use_decl_annotations_
VOID
IndexHashtableRemove(INDEX_HASHTABLE *Table, INDEX_HASHTABLE_ENTRY *Entry)
{
    KIRQL Irql;

    KeAcquireSpinLock(&Table->Lock, &Irql);
    HlistDelInitRcu(&Entry->IndexHash);
    KeReleaseSpinLock(&Table->Lock, Irql);
}

/* Returns a strong reference to a entry->peer */
_Use_decl_annotations_
INDEX_HASHTABLE_ENTRY *
IndexHashtableLookup(INDEX_HASHTABLE *Table, CONST INDEX_HASHTABLE_TYPE TypeMask, CONST UINT32_LE Index, WG_PEER **Peer)
{
    INDEX_HASHTABLE_ENTRY *IterEntry, *Entry = NULL;
    KIRQL Irql;

    Irql = RcuReadLock();
    HLIST_FOR_EACH_ENTRY_RCU (IterEntry, IndexBucket(Table, Index), INDEX_HASHTABLE_ENTRY, IndexHash)
    {
        if (IterEntry->Index == Index)
        {
            if (IterEntry->Type & TypeMask)
                Entry = IterEntry;
            break;
        }
    }
    if (Entry)
    {
        Entry->Peer = PeerGetMaybeZero(Entry->Peer);
        if (Entry->Peer)
            *Peer = Entry->Peer;
        else
            Entry = NULL;
    }
    RcuReadUnlock(Irql);
    return Entry;
}