aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Core/Security/SecurityService.cs
blob: 6da8857142bd473cf3796f50d889ae32eec79c77 (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
// <copyright file="SecurityService.cs" company="slskd Team">
//     Copyright (c) slskd Team. All rights reserved.
//
//     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, either version 3 of the License, or
//     (at your option) any later version.
//
//     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/.
// </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 slskd.Authentication;

    public interface ISecurityService
    {
        JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null);
        (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress);
    }

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

        private SymmetricSecurityKey JwtSigningKey { get; }
        private OptionsAtStartup OptionsAtStartup { get; }
        private IOptionsMonitor<Options> OptionsMonitor { get; }

        public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress)
        {
            var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys
                .FirstOrDefault(k => k.Value.Key == key);

            if (record.Key == null)
            {
                throw new NotFoundException($"The provided API key does not match an existing key");
            }

            if (!record.Value.Cidr.Split(',')
                .Select(cidr => IPAddressRange.Parse(cidr))
                .Any(range => range.Contains(callerIpAddress)))
            {
                throw new OutOfRangeException("The remote IP address is not within the range specified for the key");
            }

            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;
        }
    }
}