aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Core/Security/SecurityService.cs
blob: 790f58068a601240a67b0647983e46eb2ebca7ee (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
// <copyright file="SecurityService.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>

using Microsoft.Extensions.Options;

namespace slskd;

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using NetTools;
using Serilog;
using slskd.Authentication;

public class SecurityService
{
    public SecurityService(
        SymmetricSecurityKey jwtSigningKey,
        OptionsAtStartup optionsAtStartup,
        IOptionsMonitor<Options> optionsMonitor)
    {
        JwtSigningKey = jwtSigningKey;
        OptionsAtStartup = optionsAtStartup;
        OptionsMonitor = optionsMonitor;

        // parse the configured string into an instance of ApiKeyOptions and assign it to
        // PrimaryApiKey, if a string is provided.
        // this is kind of expensive in terms of allocations, so do it once at instantiation
        // and mark the option with [RequiresRestart]
        var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey;

        if (!string.IsNullOrWhiteSpace(adminApiKeyString))
        {
            if (!adminApiKeyString.Contains(';'))
            {
                PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions
                {
                    Key = adminApiKeyString,
                };
            }

            var tuples = adminApiKeyString.Split(';');

            string key = null;
            string role = null;
            string cidr = null;

            foreach (var tuple in tuples)
            {
                if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase))
                {
                    role = tuple.Split('=').LastOrDefault();
                }
                else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
                {
                    cidr = tuple.Split('=').LastOrDefault();
                }
                else
                {
                    key = tuple;
                }
            }

            if (!string.IsNullOrEmpty(key))
            {
                PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions
                {
                    Key = key,
                    Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role,
                    Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr,
                };
            }
        }
    }

    private ILogger Log { get; } = Serilog.Log.ForContext<SecurityService>();
    private SymmetricSecurityKey JwtSigningKey { get; }
    private OptionsAtStartup OptionsAtStartup { get; }
    private IOptionsMonitor<Options> OptionsMonitor { get; }
    private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions PrimaryApiKey { get; } = null;

    public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress)
    {
        var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable();

        if (PrimaryApiKey is not null)
        {
            keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey));
        }

        var record = keys.FirstOrDefault(k => k.Value.Key == key);

        if (record.Key == null)
        {
            throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}");
        }

        // looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4
        if (callerIpAddress.IsIPv4MappedToIPv6)
        {
            callerIpAddress = callerIpAddress.MapToIPv4();
        }

        if (!record.Value.Cidr.Split(',')
            .Select(cidr => IPAddressRange.Parse(cidr))
            .Any(range => range.Contains(callerIpAddress)))
        {
            throw new OutOfRangeException($"IP address {callerIpAddress} not included in CIDR range(s) for API key {record.Key}; allowed: {record.Value.Cidr}");
        }

        return (record.Key, record.Value.Role.ToEnum<Role>());
    }

    public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null)
    {
        var issuedUtc = DateTime.UtcNow;
        var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl);

        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.Name, username),
            new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.Role, role.ToString()),
            new Claim("name", username),
            new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()),
        };

        var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: Program.AppName,
            claims: claims,
            notBefore: issuedUtc,
            expires: expiresUtc,
            signingCredentials: credentials);

        return token;
    }
}