aboutsummaryrefslogtreecommitdiffstats
path: root/driver/allowedips.c
blob: 6e96577fea8bcf18a9e060706a35bc3716ff551d (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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/* SPDX-License-Identifier: GPL-2.0
 *
 * Copyright (C) 2015-2021 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
 */

#include "allowedips.h"
#include "containers.h"
#include "peer.h"
#include "logging.h"

#define STACK_ENTRIES 129

static LOOKASIDE_ALIGN LOOKASIDE_LIST_EX NodeCache;

static VOID
SwapEndian(_Out_writes_bytes_all_(Bits / 8) UINT8 *Dst, _In_reads_bytes_(Bits / 8) CONST UINT8 *Src, _In_ UINT8 Bits)
{
    if (Bits == 32)
    {
        *(UINT32 *)Dst = Be32ToCpu(*(CONST UINT32_BE *)Src);
    }
    else if (Bits == 128)
    {
        ((UINT64 *)Dst)[0] = Be64ToCpu(((CONST UINT64_BE *)Src)[0]);
        ((UINT64 *)Dst)[1] = Be64ToCpu(((CONST UINT64_BE *)Src)[1]);
    }
}

static VOID
CopyAndAssignCidr(
    _Out_ ALLOWEDIPS_NODE *Node,
    _In_reads_bytes_(Bits / 8) CONST UINT8 *Src,
    _In_ UINT8 Cidr,
    _In_ UINT8 Bits)
{
    Node->Cidr = Cidr;
    Node->BitAtA = Cidr / 8U;
#if REG_DWORD == REG_DWORD_LITTLE_ENDIAN
    Node->BitAtA ^= (Bits / 8U - 1U) % 8U;
#endif
    Node->BitAtB = 7U - (Cidr % 8U);
    Node->Bitlen = Bits;
    RtlCopyMemory(Node->Bits, Src, Bits / 8U);
}

static inline UINT8
Choose(_In_ CONST ALLOWEDIPS_NODE *Node, _In_ CONST UINT8 *Key)
{
    return (Key[Node->BitAtA] >> Node->BitAtB) & 1;
}

static VOID
PushRcu(_Inout_ ALLOWEDIPS_NODE *Stack[STACK_ENTRIES], _In_ ALLOWEDIPS_NODE __rcu *P, _In_ ULONG *Len)
{
    /* This lets us use it from mutex-protected or cleanup functions too. */
    _Analysis_assume_rcu_held_;
    if (RcuAccessPointer(P))
    {
        NT_ASSERT(*Len < STACK_ENTRIES);
        Stack[(*Len)++] = RcuDereference(ALLOWEDIPS_NODE, P);
    }
    _Analysis_assume_rcu_not_held_;
}

static RCU_CALLBACK_FN NodeFreeRcu;
_Use_decl_annotations_
static VOID
NodeFreeRcu(RCU_CALLBACK *Rcu)
{
    ExFreeToLookasideListEx(&NodeCache, CONTAINING_RECORD(Rcu, ALLOWEDIPS_NODE, Rcu));
}

static RCU_CALLBACK_FN RootFreeRcu;
#pragma warning(suppress : 6262) /* Using 1044 bytes of stack is still below 1280. */
_Use_decl_annotations_
static VOID
RootFreeRcu(RCU_CALLBACK *Rcu)
{
    ALLOWEDIPS_NODE *Node, *Stack[STACK_ENTRIES] = { CONTAINING_RECORD(Rcu, ALLOWEDIPS_NODE, Rcu) };
    ULONG Len = 1;

    while (Len > 0 && (Node = Stack[--Len]) != NULL)
    {
        PushRcu(Stack, Node->Bit[0], &Len);
        PushRcu(Stack, Node->Bit[1], &Len);
        ExFreeToLookasideListEx(&NodeCache, Node);
    }
}

#pragma warning(suppress : 6262) /* Using 1044 bytes of stack is still below 1280. */
static VOID
RootRemovePeerLists(_In_ ALLOWEDIPS_NODE *Root)
{
    ALLOWEDIPS_NODE *Node, *Stack[STACK_ENTRIES] = { Root };
    ULONG Len = 1;
    while (Len > 0 && (Node = Stack[--Len]) != NULL)
    {
        PushRcu(Stack, Node->Bit[0], &Len);
        PushRcu(Stack, Node->Bit[1], &Len);
        if (RcuAccessPointer(Node->Peer))
            RemoveEntryList(&Node->PeerList);
    }
}

static UINT8
CommonBits(_In_ CONST ALLOWEDIPS_NODE *Node, _In_reads_bytes_(Bits / 8) CONST UINT8 *Key, _In_ UINT8 Bits)
{
    if (Bits == 32)
        return 32 - (UINT8)FindLastSet32(*(CONST UINT32 *)Node->Bits ^ *(CONST UINT32 *)Key);
    else if (Bits == 128)
        return 128 - (UINT8)FindLastSet128(
                         *(CONST UINT64 *)&Node->Bits[0] ^ *(CONST UINT64 *)&Key[0],
                         *(CONST UINT64 *)&Node->Bits[8] ^ *(CONST UINT64 *)&Key[8]);
    return 0;
}

static BOOLEAN
PrefixMatches(_In_ CONST ALLOWEDIPS_NODE *Node, _In_reads_bytes_(Bits / 8) CONST UINT8 *Key, _In_ UINT8 Bits)
{
    /* This could be much faster if it actually just compared the common
     * bits properly, by precomputing a mask bswap(~0 << (32 - cidr)), and
     * the rest, but it turns out that common_bits is already super fast on
     * modern processors, even taking into account the unfortunate bswap.
     * So, we just inline it like this instead.
     */
    return CommonBits(Node, Key, Bits) >= Node->Cidr;
}

_Requires_rcu_held_
_Must_inspect_result_
_Post_maybenull_
static ALLOWEDIPS_NODE *
FindNode(_In_ ALLOWEDIPS_NODE *Trie, _In_ UINT8 Bits, _In_reads_bytes_(Bits / 8) CONST UINT8 *Key)
{
    ALLOWEDIPS_NODE *Node = Trie, *Found = NULL;

    while (Node && PrefixMatches(Node, Key, Bits))
    {
        if (RcuAccessPointer(Node->Peer))
            Found = Node;
        if (Node->Cidr == Bits)
            break;
        Node = RcuDereference(ALLOWEDIPS_NODE, Node->Bit[Choose(Node, Key)]);
    }
    return Found;
}

/* Returns a strong reference to a peer */
_IRQL_requires_max_(DISPATCH_LEVEL)
_Must_inspect_result_
_Post_maybenull_
static WG_PEER *
Lookup(_In_ ALLOWEDIPS_NODE __rcu *Root, _In_ UINT8 Bits, _In_reads_bytes_(Bits / 8) CONST VOID *BeIp)
{
    /* Aligned so it can be passed to FindLastSet/FindLastSet64 */
    __declspec(align(8)) UINT8 Ip[16];
    ALLOWEDIPS_NODE *Node;
    WG_PEER *Peer = NULL;
    KIRQL Irql;

    SwapEndian(Ip, BeIp, Bits);

    Irql = RcuReadLock();
retry:
    Node = FindNode(RcuDereference(ALLOWEDIPS_NODE, Root), Bits, Ip);
    if (Node)
    {
        Peer = PeerGetMaybeZero(RcuDereference(WG_PEER, Node->Peer));
        if (!Peer)
            goto retry;
    }
    RcuReadUnlock(Irql);
    return Peer;
}

_Requires_lock_held_(Lock)
static BOOLEAN
NodePlacement(
    _In_ ALLOWEDIPS_NODE __rcu *Trie,
    _In_reads_bytes_(Bits / 8) CONST UINT8 *Key,
    _In_ UINT8 Cidr,
    _In_ UINT8 Bits,
    _Out_ ALLOWEDIPS_NODE **Rnode,
    _In_ EX_PUSH_LOCK *Lock)
{
    ALLOWEDIPS_NODE *Node = RcuDereferenceProtected(ALLOWEDIPS_NODE, Trie, Lock);
    ALLOWEDIPS_NODE *Parent = NULL;
    BOOLEAN Exact = FALSE;

    while (Node && Node->Cidr <= Cidr && PrefixMatches(Node, Key, Bits))
    {
        Parent = Node;
        if (Parent->Cidr == Cidr)
        {
            Exact = TRUE;
            break;
        }
        Node = RcuDereferenceProtected(ALLOWEDIPS_NODE, Parent->Bit[Choose(Parent, Key)], Lock);
    }
    *Rnode = Parent;
    return Exact;
}

static inline VOID
ConnectNode(_Inout_ ALLOWEDIPS_NODE __rcu **Parent, _In_ UINT8 Bit, _In_ __drv_aliasesMem ALLOWEDIPS_NODE *Node)
{
    Node->ParentBitPacked = (ULONG_PTR)Parent | Bit;
    RcuAssignPointer(*Parent, Node);
}

static inline VOID
ChooseAndConnectNode(_Inout_ ALLOWEDIPS_NODE *Parent, _In_ __drv_aliasesMem ALLOWEDIPS_NODE *Node)
{
    UINT8 Bit = Choose(Parent, Node->Bits);
    ConnectNode(&Parent->Bit[Bit], Bit, Node);
}

_Requires_lock_held_(Lock)
static NTSTATUS
Add(_Inout_ ALLOWEDIPS_NODE __rcu **Trie,
    _In_ UINT8 Bits,
    _In_ CONST UINT8 *Key,
    _In_ UINT8 Cidr,
    _In_ WG_PEER *Peer,
    _In_ EX_PUSH_LOCK *Lock)
{
    ALLOWEDIPS_NODE *Node, *Parent, *Down, *Newnode;

    if (Cidr > Bits || !Peer)
        return STATUS_INVALID_PARAMETER;

    if (!RcuAccessPointer(*Trie))
    {
        Node = ExAllocateFromLookasideListEx(&NodeCache);
        if (!Node)
            return STATUS_INSUFFICIENT_RESOURCES;
        RtlZeroMemory(Node, sizeof(*Node));
        RcuInitPointer(Node->Peer, Peer);
        InsertTailList(&Peer->AllowedIpsList, &Node->PeerList);
        CopyAndAssignCidr(Node, Key, Cidr, Bits);
        ConnectNode(Trie, 2, Node);
        return STATUS_SUCCESS;
    }
    if (NodePlacement(*Trie, Key, Cidr, Bits, &Node, Lock))
    {
        RcuAssignPointer(Node->Peer, Peer);
        RemoveEntryList(&Node->PeerList);
        InsertTailList(&Peer->AllowedIpsList, &Node->PeerList);
        return STATUS_SUCCESS;
    }

    Newnode = ExAllocateFromLookasideListEx(&NodeCache);
    if (!Newnode)
        return STATUS_INSUFFICIENT_RESOURCES;
    RtlZeroMemory(Newnode, sizeof(*Newnode));
    RcuInitPointer(Newnode->Peer, Peer);
    InsertTailList(&Peer->AllowedIpsList, &Newnode->PeerList);
    CopyAndAssignCidr(Newnode, Key, Cidr, Bits);

    if (!Node)
    {
        Down = RcuDereferenceProtected(ALLOWEDIPS_NODE, *Trie, Lock);
    }
    else
    {
        CONST UINT8 Bit = Choose(Node, Key);
        Down = RcuDereferenceProtected(ALLOWEDIPS_NODE, Node->Bit[Bit], Lock);
        if (!Down)
        {
            ConnectNode(&Node->Bit[Bit], Bit, Newnode);
            return STATUS_SUCCESS;
        }
    }
    Cidr = min(Cidr, CommonBits(Down, Key, Bits));
    Parent = Node;

    if (Newnode->Cidr == Cidr)
    {
        ChooseAndConnectNode(Newnode, Down);
        if (!Parent)
            ConnectNode(Trie, 2, Newnode);
        else
            ChooseAndConnectNode(Parent, Newnode);
        return 0;
    }

    Node = ExAllocateFromLookasideListEx(&NodeCache);
    if (!Node)
    {
        RemoveEntryList(&Newnode->PeerList);
        ExFreeToLookasideListEx(&NodeCache, Newnode);
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    RtlZeroMemory(Node, sizeof(*Node));
    InitializeListHead(&Node->PeerList);
    CopyAndAssignCidr(Node, Newnode->Bits, Cidr, Bits);

    ChooseAndConnectNode(Node, Down);
    ChooseAndConnectNode(Node, Newnode);
    if (!Parent)
        ConnectNode(Trie, 2, Node);
    else
        ChooseAndConnectNode(Parent, Node);
    return STATUS_SUCCESS;
}

_Use_decl_annotations_
VOID
AllowedIpsInit(ALLOWEDIPS_TABLE *Table)
{
    Table->Root4 = Table->Root6 = NULL;
    Table->Seq = 1;
}

_Use_decl_annotations_
VOID
AllowedIpsFree(ALLOWEDIPS_TABLE *Table, EX_PUSH_LOCK *Lock)
{
    ALLOWEDIPS_NODE *Old4 = RcuDereferenceProtected(ALLOWEDIPS_NODE, Table->Root4, Lock);
    ALLOWEDIPS_NODE *Old6 = RcuDereferenceProtected(ALLOWEDIPS_NODE, Table->Root6, Lock);

    ++Table->Seq;
    RcuInitPointer(Table->Root4, NULL);
    RcuInitPointer(Table->Root6, NULL);
    if (Old4)
    {
        RootRemovePeerLists(Old4);
        RcuCall(&Old4->Rcu, RootFreeRcu);
    }
    if (Old6)
    {
        RootRemovePeerLists(Old6);
        RcuCall(&Old6->Rcu, RootFreeRcu);
    }
}

_Use_decl_annotations_
NTSTATUS
AllowedIpsInsertV4(ALLOWEDIPS_TABLE *Table, CONST IN_ADDR *Ip, UINT8 Cidr, WG_PEER *Peer, EX_PUSH_LOCK *Lock)
{
    /* Aligned so it can be passed to FindLastSet */
    __declspec(align(4)) UINT8 Key[4];

    ++Table->Seq;
    SwapEndian(Key, (CONST UINT8 *)Ip, 32);
    return Add(&Table->Root4, 32, Key, Cidr, Peer, Lock);
}

_Use_decl_annotations_
NTSTATUS
AllowedIpsInsertV6(ALLOWEDIPS_TABLE *Table, CONST IN6_ADDR *Ip, UINT8 Cidr, WG_PEER *Peer, EX_PUSH_LOCK *Lock)
{
    /* Aligned so it can be passed to FindLastSet64 */
    __declspec(align(8)) UINT8 Key[16];

    ++Table->Seq;
    SwapEndian(Key, (CONST UINT8 *)Ip, 128);
    return Add(&Table->Root6, 128, Key, Cidr, Peer, Lock);
}

_Use_decl_annotations_
VOID
AllowedIpsRemoveByPeer(ALLOWEDIPS_TABLE *Table, WG_PEER *Peer, EX_PUSH_LOCK *Lock)
{
    ALLOWEDIPS_NODE *Node, *Child, **ParentBit, *Parent, *Tmp;
    BOOLEAN FreeParent;

    if (IsListEmpty(&Peer->AllowedIpsList))
        return;
    ++Table->Seq;
    LIST_FOR_EACH_ENTRY_SAFE (Node, Tmp, &Peer->AllowedIpsList, ALLOWEDIPS_NODE, PeerList)
    {
        RemoveEntryList(&Node->PeerList);
        InitializeListHead(&Node->PeerList);
        RcuInitPointer(Node->Peer, NULL);
        if (Node->Bit[0] && Node->Bit[1])
            continue;
        Child = RcuDereferenceProtected(ALLOWEDIPS_NODE, Node->Bit[!RcuAccessPointer(Node->Bit[0])], Lock);
        if (Child)
            Child->ParentBitPacked = Node->ParentBitPacked;
        ParentBit = (ALLOWEDIPS_NODE **)(Node->ParentBitPacked & ~(ULONG_PTR)3);
        *ParentBit = Child;
        Parent =
            (ALLOWEDIPS_NODE *)((UCHAR *)ParentBit - FIELD_OFFSET(ALLOWEDIPS_NODE, Bit[Node->ParentBitPacked & 1]));
        FreeParent = !RcuAccessPointer(Node->Bit[0]) && !RcuAccessPointer(Node->Bit[1]) &&
                     (Node->ParentBitPacked & 3) <= 1 && !RcuAccessPointer(Parent->Peer);
        if (FreeParent)
            Child = RcuDereferenceProtected(ALLOWEDIPS_NODE, Parent->Bit[!(Node->ParentBitPacked & 1)], Lock);
        RcuCall(&Node->Rcu, NodeFreeRcu);
        if (!FreeParent)
            continue;
        if (Child)
            Child->ParentBitPacked = Parent->ParentBitPacked;
        *(ALLOWEDIPS_NODE **)(Parent->ParentBitPacked & ~(ULONG_PTR)3) = Child;
        RcuCall(&Parent->Rcu, NodeFreeRcu);
    }
}

_Use_decl_annotations_
ADDRESS_FAMILY
AllowedIpsReadNode(CONST ALLOWEDIPS_NODE *Node, UINT8 Ip[16], UINT8 *Cidr)
{
    CONST ULONG CidrBytes = DIV_ROUND_UP(Node->Cidr, 8U);
    SwapEndian(Ip, Node->Bits, Node->Bitlen);
    RtlZeroMemory(Ip + CidrBytes, Node->Bitlen / 8U - CidrBytes);
    if (Node->Cidr)
        Ip[CidrBytes - 1U] &= ~0U << (-Node->Cidr % 8U);

    *Cidr = Node->Cidr;
    return Node->Bitlen == 32 ? AF_INET : AF_INET6;
}

/* Returns a strong reference to a peer */
_Use_decl_annotations_
WG_PEER *
AllowedIpsLookupDst(ALLOWEDIPS_TABLE *Table, UINT16_BE Proto, CONST VOID *IpHdr)
{
    if (Proto == Htons(NDIS_ETH_TYPE_IPV4))
        return Lookup(Table->Root4, 32, &((IPV4HDR *)IpHdr)->Daddr);
    else if (Proto == Htons(NDIS_ETH_TYPE_IPV6))
        return Lookup(Table->Root6, 128, &((IPV6HDR *)IpHdr)->Daddr);
    return NULL;
}

/* Returns a strong reference to a peer */
_Use_decl_annotations_
WG_PEER *
AllowedIpsLookupSrc(ALLOWEDIPS_TABLE *Table, UINT16_BE Proto, CONST VOID *IpHdr)
{
    if (Proto == Htons(NDIS_ETH_TYPE_IPV4))
        return Lookup(Table->Root4, 32, &((IPV4HDR *)IpHdr)->Saddr);
    else if (Proto == Htons(NDIS_ETH_TYPE_IPV6))
        return Lookup(Table->Root6, 128, &((IPV6HDR *)IpHdr)->Saddr);
    return NULL;
}

#ifdef ALLOC_PRAGMA
#    pragma alloc_text(INIT, AllowedIpsDriverEntry)
#endif
_Use_decl_annotations_
NTSTATUS
AllowedIpsDriverEntry(VOID)
{
    return ExInitializeLookasideListEx(&NodeCache, NULL, NULL, NonPagedPool, 0, sizeof(ALLOWEDIPS_NODE), MEMORY_TAG, 0);
}

_Use_decl_annotations_
VOID AllowedIpsUnload(VOID)
{
    RcuBarrier();
    ExDeleteLookasideListEx(&NodeCache);
}

#ifdef DBG
#    include "selftest/allowedips.c"
#endif