aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Core/Blacklist.cs
blob: 6f25b93c15aaaa95d09931a6ae757f2ef84f0796 (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
// <copyright file="Blacklist.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ Copyright (c) JP Dillingham.
//   │
//   │ This program is free software: you can redistribute it and/or modify
//   │ it under the terms of the GNU Affero General Public License as published
//   │ by the Free Software Foundation, version 3.
//   │
//   │ This program is distributed in the hope that it will be useful,
//   │ but WITHOUT ANY WARRANTY; without even the implied warranty of
//   │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   │ GNU Affero General Public License for more details.
//   │
//   │ You should have received a copy of the GNU Affero General Public License
//   │ along with this program.  If not, see https://www.gnu.org/licenses/.
//   │
//   │ This program is distributed with Additional Terms pursuant to Section 7
//   │ of the AGPLv3.  See the LICENSE file in the root directory of this
//   │ project for the complete terms and conditions.
//   │
//   │ https://slskd.org
//   │
//   ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌
//   │ SPDX-FileCopyrightText: JP Dillingham
//   │ SPDX-License-Identifier: AGPL-3.0-only
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

namespace slskd;

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using NetTools;
using Serilog;

/// <summary>
///     Blacklist file formats.
/// </summary>
public enum BlacklistFormat
{
    /// <summary>
    ///     Automatically detect format based on contents.
    /// </summary>
    AutoDetect,

    /// <summary>
    ///     CIDR format. <see href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing"/>.
    /// </summary>
    /// <example>
    ///     <code>
    ///         1.2.4.0/24
    ///         1.2.8.0/24
    ///         1.9.96.105/32
    ///     </code>
    /// </example>
    CIDR,

    /// <summary>
    ///     P2P format. <see href="https://sourceforge.net/p/peerguardian/wiki/dev-blocklist-format-p2p/"/>.
    /// </summary>
    /// <example>
    ///     <code>
    ///         China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255
    ///         China Internet Information Center (CNNIC):1.2.8.0-1.2.8.255
    ///         Botnet on Telekom Malaysia:1.9.96.105-1.9.96.105
    ///     </code>
    /// </example>
    P2P,

    /// <summary>
    ///     DAT format. <see href="https://sourceforge.net/p/peerguardian/wiki/dev-blocklist-format-dat/"/>.
    /// </summary>
    /// <example>
    ///     <code>
    ///         001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC)
    ///         001.002.008.000 - 001.002.008.255 , 000 , China Internet Information Center (CNNIC)
    ///         001.009.096.105 - 001.009.096.105 , 000 , Botnet on Telekom Malaysia
    ///     </code>
    /// </example>
    DAT,
}

/// <summary>
///     A managed blacklist for CIDRs.
/// </summary>
public class Blacklist
{
    /// <summary>
    ///     Gets the total number of loaded CIDRs.
    /// </summary>
    public long Count => Cache.Sum(kvp => kvp.Value.Length);

    private ILogger Log { get; set; } = Serilog.Log.ForContext<Blacklist>();
    private ConcurrentDictionary<int, (uint First, uint Last)[]> Cache { get; set; } = new();

    /// <summary>
    ///     Examines the contents of the specified <paramref name="filename"/> and attempts to determine the format.
    /// </summary>
    /// <param name="filename">The fully qualified path to the file to examine.</param>
    /// <returns>The detected format.</returns>
    /// <exception cref="IOException">Thrown if the specified filename can't be accessed.</exception>
    /// <exception cref="FormatException">Thrown if the format can't be determined.</exception>
    public static async Task<BlacklistFormat> DetectFormat(string filename)
    {
        using var reader = new StreamReader(filename, options: new FileStreamOptions
        {
            Access = FileAccess.Read,
            Mode = FileMode.Open,
            Share = FileShare.Read,
        });

        string line = default;

        // read the first non-empty, non-commented line from the file
        while ((line = await reader.ReadLineAsync()) != null)
        {
            if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#'))
            {
                continue;
            }

            try
            {
                // CIDR format: 1.2.4.0/24
                if (IPAddressRange.TryParse(line, out _))
                {
                    return BlacklistFormat.CIDR;
                }
            }
            catch
            {
            }

            try
            {
                // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255
                if (IPAddressRange.TryParse(line.Split(':')[1], out _))
                {
                    return BlacklistFormat.P2P;
                }
            }
            catch
            {
            }

            try
            {
                // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC)
                if (IPAddressRange.TryParse(line.Split(",")[0], out _))
                {
                    return BlacklistFormat.DAT;
                }
            }
            catch
            {
            }
        }

        throw new FormatException("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported");
    }

    /// <summary>
    ///     Clears the contents of the Blacklist.
    /// </summary>
    public virtual void Clear() => Cache.Clear();

    /// <summary>
    ///     Loads the contents of the specified <paramref name="filename"/> into the Blacklist.
    /// </summary>
    /// <remarks>
    ///     The existing Blacklist contents are replaced atomically.
    /// </remarks>
    /// <param name="filename">The fully qualified path to the file to load.</param>
    /// <param name="format">The optional blacklist file format.</param>
    /// <returns>The operation context.</returns>
    /// <exception cref="IOException">Thrown if the specified filename can't be accessed.</exception>
    /// <exception cref="FormatException">
    ///     Thrown if any of the lines in the file do not match the specified or auto-detected <paramref name="format"/>.
    /// </exception>
    /// <exception cref="FormatException">
    ///     Thrown if the specified <paramref name="format"/> is <see cref="BlacklistFormat.AutoDetect"/> and the format could not be detected.
    /// </exception>
    public virtual async Task Load(string filename, BlacklistFormat format = BlacklistFormat.AutoDetect)
    {
        if (format == BlacklistFormat.AutoDetect)
        {
            Log.Debug("Attempting to auto-detect blacklist format from contents...");
            format = await DetectFormat(filename); // FormatException if unsuccessful
            Log.Debug("Detected blacklist format {Format}", format);
        }

        var sw = new Stopwatch();
        sw.Start();
        Log.Debug("Loading blacklist");

        using var reader = new StreamReader(filename, options: new FileStreamOptions
        {
            Access = FileAccess.Read,
            Mode = FileMode.Open,
            Share = FileShare.Read,
            BufferSize = 262144, // 256kib, assumes most blacklists will be > 1mb
        });

        var dict = new ConcurrentDictionary<int, List<(uint First, uint Last)>>();
        string line = default;
        int lineNumber = 0;

        while ((line = await reader.ReadLineAsync()) != null)
        {
            lineNumber++;

            if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#'))
            {
                continue;
            }

            IPAddressRange cidr = default;

            /*
                parse CIDR from string using specified or detected format
                note: we should never get this far without format being one of CIDR, P2P, DAT
            */

            try
            {
                // CIDR format: 1.2.4.0/24
                if (format == BlacklistFormat.CIDR)
                {
                    cidr = IPAddressRange.Parse(line);
                }

                // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255
                else if (format == BlacklistFormat.P2P)
                {
                    cidr = IPAddressRange.Parse(line.Split(':').Last());
                }

                // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC)
                else if (format == BlacklistFormat.DAT)
                {
                    // the IPAddressRange library doesn't like leading zeros, so we have to remove them
                    static string TrimLeadingZerosFromEachOctet(string ip)
                        => string.Join('.', ip.Split('.').Select(octet => octet == "000" ? "0" : octet.TrimStart('0')));

                    // 001.002.004.000-001.002.004.255
                    var range = line.Split(",").First().Replace(" ", string.Empty);

                    // [1.2.4.0, 1.2.4.255]
                    var ips = range.Split("-")
                        .Select(TrimLeadingZerosFromEachOctet);

                    cidr = IPAddressRange.Parse(string.Join('-', ips));
                }
            }
            catch (Exception ex)
            {
                throw new FormatException($"Failed to parse {format} blacklist line {lineNumber} '{line}': {ex.Message}");
            }

            // grab the first octet of the first and last addresses in the range
            var first = int.Parse(cidr.Begin.ToString().Split('.')[0]);
            var last = int.Parse(cidr.End.ToString().Split('.')[0]);

            var entry = (ToUint32(cidr.Begin), ToUint32(cidr.End));

            // CIDRs with a mask of /7 and lower span multiple octets, so we must add these CIDRs to the list for each octet
            for (int i = 0; i <= last - first; i++)
            {
                dict.AddOrUpdate(
                    key: first + i, // first octet
                    addValueFactory: (_) => new List<(uint, uint)> { entry }, // if we haven't seen this octet yet, initialize the list
                    updateValueFactory: (_, list) =>
                    {
                        list.Add(entry); // if we've seen it already, append
                        return list;
                    });
            }
        }

        // copy working dictionary to a temporary cache to:
        //   * deduplicate entries
        //   * sort arrays by first IP to enable binary search (future?)
        //   * convert List<> to array to increase access speed
        var tempCache = new ConcurrentDictionary<int, (uint First, uint Last)[]>();

        foreach (var key in dict.Keys)
        {
            tempCache[key] = dict[key]
                .Distinct()
                .OrderBy(x => x.First)
                .ToArray();
        }

        // swap the temporary cache for the "real" cache, enabling a bumpless update
        Cache = tempCache;

        sw.Stop();
        Log.Debug("Blacklist loaded in {Duration}ms", sw.ElapsedMilliseconds);
    }

    /// <summary>
    ///     Returns a value indicating whether the specified <paramref name="ip"/> is contained within the blacklist.
    /// </summary>
    /// <param name="ip">The IP address to check.</param>
    /// <returns>A value indicating whether the specified IP is contained within the blacklist.</returns>
    public virtual bool Contains(IPAddress ip)
    {
        // looks like '::ffff:1.2.3.4'; convert it back to IPv4 so the lookup below works
        if (ip.IsIPv4MappedToIPv6)
        {
            ip = ip.MapToIPv4();
        }

        // only IPv4 ranges are supported
        if (ip.AddressFamily != AddressFamily.InterNetwork)
        {
            return false;
        }

        // grab the first octet
        int first = ip.GetAddressBytes()[0];

        // check to see if *any* CIDRs covering this offset are in the blacklist
        // best case scenario for performance if not, roughly O(1)
        if (!Cache.TryGetValue(first, out (uint, uint)[] cidrs))
        {
            return false;
        }

        // convert the entire IP to a uint
        var ipAsUint32 = ToUint32(ip);

        // check the list for this octet sequentially until the first match
        foreach (var cidr in cidrs)
        {
            if (ipAsUint32 >= cidr.Item1 && ipAsUint32 <= cidr.Item2)
            {
                return true;
            }
        }

        // not in the list
        // worst case scenario for performance, O(n) where n = list length
        return false;
    }

    private uint ToUint32(IPAddress ip)
    {
        byte[] bytes = ip.GetAddressBytes();

        if (BitConverter.IsLittleEndian)
        {
            Array.Reverse(bytes);
        }

        return BitConverter.ToUInt32(bytes, 0);
    }
}