| | | 1 | | using System; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Globalization; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Security.Cryptography; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using MediaBrowser.Common.Extensions; |
| | | 8 | | using MediaBrowser.Controller.Authentication; |
| | | 9 | | using MediaBrowser.Controller.Configuration; |
| | | 10 | | using MediaBrowser.Controller.Net; |
| | | 11 | | using MediaBrowser.Controller.QuickConnect; |
| | | 12 | | using MediaBrowser.Controller.Session; |
| | | 13 | | using MediaBrowser.Model.QuickConnect; |
| | | 14 | | using Microsoft.Extensions.Logging; |
| | | 15 | | |
| | | 16 | | namespace Emby.Server.Implementations.QuickConnect |
| | | 17 | | { |
| | | 18 | | /// <summary> |
| | | 19 | | /// Quick connect implementation. |
| | | 20 | | /// </summary> |
| | | 21 | | public class QuickConnectManager : IQuickConnect |
| | | 22 | | { |
| | | 23 | | /// <summary> |
| | | 24 | | /// The length of user facing codes. |
| | | 25 | | /// </summary> |
| | | 26 | | private const int CodeLength = 6; |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// The time (in minutes) that the quick connect token is valid. |
| | | 30 | | /// </summary> |
| | | 31 | | private const int Timeout = 10; |
| | | 32 | | |
| | 29 | 33 | | private readonly ConcurrentDictionary<string, QuickConnectResult> _currentRequests = new(); |
| | 29 | 34 | | private readonly ConcurrentDictionary<string, (DateTime Timestamp, AuthenticationResult AuthenticationResult)> _ |
| | | 35 | | |
| | | 36 | | private readonly IServerConfigurationManager _config; |
| | | 37 | | private readonly ILogger<QuickConnectManager> _logger; |
| | | 38 | | private readonly ISessionManager _sessionManager; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Initializes a new instance of the <see cref="QuickConnectManager"/> class. |
| | | 42 | | /// Should only be called at server startup when a singleton is created. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <param name="config">Configuration.</param> |
| | | 45 | | /// <param name="logger">Logger.</param> |
| | | 46 | | /// <param name="sessionManager">Session Manager.</param> |
| | | 47 | | public QuickConnectManager( |
| | | 48 | | IServerConfigurationManager config, |
| | | 49 | | ILogger<QuickConnectManager> logger, |
| | | 50 | | ISessionManager sessionManager) |
| | | 51 | | { |
| | 29 | 52 | | _config = config; |
| | 29 | 53 | | _logger = logger; |
| | 29 | 54 | | _sessionManager = sessionManager; |
| | 29 | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <inheritdoc /> |
| | 12 | 58 | | public bool IsEnabled => _config.Configuration.QuickConnectAvailable; |
| | | 59 | | |
| | | 60 | | /// <summary> |
| | | 61 | | /// Assert that quick connect is currently active and throws an exception if it is not. |
| | | 62 | | /// </summary> |
| | | 63 | | private void AssertActive() |
| | | 64 | | { |
| | 10 | 65 | | if (!IsEnabled) |
| | | 66 | | { |
| | 4 | 67 | | throw new AuthenticationException("Quick connect is not active on this server"); |
| | | 68 | | } |
| | 6 | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <inheritdoc/> |
| | | 72 | | public QuickConnectResult TryConnect(AuthorizationInfo authorizationInfo) |
| | | 73 | | { |
| | 7 | 74 | | ArgumentException.ThrowIfNullOrEmpty(authorizationInfo.DeviceId); |
| | 6 | 75 | | ArgumentException.ThrowIfNullOrEmpty(authorizationInfo.Device); |
| | 5 | 76 | | ArgumentException.ThrowIfNullOrEmpty(authorizationInfo.Client); |
| | 4 | 77 | | ArgumentException.ThrowIfNullOrEmpty(authorizationInfo.Version); |
| | | 78 | | |
| | 3 | 79 | | AssertActive(); |
| | 2 | 80 | | ExpireRequests(); |
| | | 81 | | |
| | 2 | 82 | | var secret = GenerateSecureRandom(); |
| | 2 | 83 | | var code = GenerateCode(); |
| | 2 | 84 | | var result = new QuickConnectResult( |
| | 2 | 85 | | secret, |
| | 2 | 86 | | code, |
| | 2 | 87 | | DateTime.UtcNow, |
| | 2 | 88 | | authorizationInfo.DeviceId, |
| | 2 | 89 | | authorizationInfo.Device, |
| | 2 | 90 | | authorizationInfo.Client, |
| | 2 | 91 | | authorizationInfo.Version); |
| | | 92 | | |
| | 2 | 93 | | _currentRequests[code] = result; |
| | 2 | 94 | | return result; |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | /// <inheritdoc/> |
| | | 98 | | public QuickConnectResult CheckRequestStatus(string secret) |
| | | 99 | | { |
| | 3 | 100 | | AssertActive(); |
| | 2 | 101 | | ExpireRequests(); |
| | | 102 | | |
| | 2 | 103 | | string code = _currentRequests.Where(x => x.Value.Secret == secret).Select(x => x.Value.Code).DefaultIfEmpty |
| | | 104 | | |
| | 2 | 105 | | if (!_currentRequests.TryGetValue(code, out QuickConnectResult? result)) |
| | | 106 | | { |
| | 1 | 107 | | throw new ResourceNotFoundException("Unable to find request with provided secret"); |
| | | 108 | | } |
| | | 109 | | |
| | 1 | 110 | | return result; |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Generates a short code to display to the user to uniquely identify this request. |
| | | 115 | | /// </summary> |
| | | 116 | | /// <returns>A short, unique alphanumeric string.</returns> |
| | | 117 | | private string GenerateCode() |
| | | 118 | | { |
| | 2 | 119 | | Span<byte> raw = stackalloc byte[4]; |
| | | 120 | | |
| | 2 | 121 | | int min = (int)Math.Pow(10, CodeLength - 1); |
| | 2 | 122 | | int max = (int)Math.Pow(10, CodeLength); |
| | | 123 | | |
| | 2 | 124 | | uint scale = uint.MaxValue; |
| | 4 | 125 | | while (scale == uint.MaxValue) |
| | | 126 | | { |
| | 2 | 127 | | RandomNumberGenerator.Fill(raw); |
| | 2 | 128 | | scale = BitConverter.ToUInt32(raw); |
| | | 129 | | } |
| | | 130 | | |
| | 2 | 131 | | int code = (int)(min + ((max - min) * (scale / (double)uint.MaxValue))); |
| | 2 | 132 | | return code.ToString(CultureInfo.InvariantCulture); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | /// <inheritdoc/> |
| | | 136 | | public async Task<bool> AuthorizeRequest(Guid userId, string code) |
| | | 137 | | { |
| | | 138 | | AssertActive(); |
| | | 139 | | ExpireRequests(); |
| | | 140 | | |
| | | 141 | | if (!_currentRequests.TryGetValue(code, out QuickConnectResult? result)) |
| | | 142 | | { |
| | | 143 | | throw new ResourceNotFoundException("Unable to find request"); |
| | | 144 | | } |
| | | 145 | | |
| | | 146 | | if (result.Authenticated) |
| | | 147 | | { |
| | | 148 | | throw new InvalidOperationException("Request is already authorized"); |
| | | 149 | | } |
| | | 150 | | |
| | | 151 | | // Change the time on the request so it expires one minute into the future. It can't expire immediately as o |
| | | 152 | | result.DateAdded = DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)); |
| | | 153 | | |
| | | 154 | | var authenticationResult = await _sessionManager.AuthenticateDirect(new AuthenticationRequest |
| | | 155 | | { |
| | | 156 | | UserId = userId, |
| | | 157 | | DeviceId = result.DeviceId, |
| | | 158 | | DeviceName = result.DeviceName, |
| | | 159 | | App = result.AppName, |
| | | 160 | | AppVersion = result.AppVersion |
| | | 161 | | }).ConfigureAwait(false); |
| | | 162 | | |
| | | 163 | | _authorizedSecrets[result.Secret] = (DateTime.UtcNow, authenticationResult); |
| | | 164 | | result.Authenticated = true; |
| | | 165 | | _currentRequests[code] = result; |
| | | 166 | | |
| | | 167 | | _logger.LogDebug("Authorizing device with code {Code} to login as user {UserId}", code, userId); |
| | | 168 | | |
| | | 169 | | return true; |
| | | 170 | | } |
| | | 171 | | |
| | | 172 | | /// <inheritdoc/> |
| | | 173 | | public AuthenticationResult GetAuthorizedRequest(string secret) |
| | | 174 | | { |
| | 2 | 175 | | AssertActive(); |
| | 1 | 176 | | ExpireRequests(); |
| | | 177 | | |
| | 1 | 178 | | if (!_authorizedSecrets.TryGetValue(secret, out var result)) |
| | | 179 | | { |
| | 1 | 180 | | throw new ResourceNotFoundException("Unable to find request"); |
| | | 181 | | } |
| | | 182 | | |
| | 0 | 183 | | return result.AuthenticationResult; |
| | | 184 | | } |
| | | 185 | | |
| | | 186 | | private string GenerateSecureRandom(int length = 32) |
| | | 187 | | { |
| | 2 | 188 | | Span<byte> bytes = stackalloc byte[length]; |
| | 2 | 189 | | RandomNumberGenerator.Fill(bytes); |
| | | 190 | | |
| | 2 | 191 | | return Convert.ToHexString(bytes); |
| | | 192 | | } |
| | | 193 | | |
| | | 194 | | /// <summary> |
| | | 195 | | /// Expire quick connect requests that are over the time limit. If <paramref name="expireAll"/> is true, all req |
| | | 196 | | /// </summary> |
| | | 197 | | /// <param name="expireAll">If true, all requests will be expired.</param> |
| | | 198 | | private void ExpireRequests(bool expireAll = false) |
| | | 199 | | { |
| | | 200 | | // All requests before this timestamp have expired |
| | 6 | 201 | | var minTime = DateTime.UtcNow.AddMinutes(-Timeout); |
| | | 202 | | |
| | | 203 | | // Expire stale connection requests |
| | 16 | 204 | | foreach (var (_, currentRequest) in _currentRequests) |
| | | 205 | | { |
| | 2 | 206 | | if (expireAll || currentRequest.DateAdded < minTime) |
| | | 207 | | { |
| | 0 | 208 | | var code = currentRequest.Code; |
| | 0 | 209 | | _logger.LogDebug("Removing expired request {Code}", code); |
| | | 210 | | |
| | 0 | 211 | | if (!_currentRequests.TryRemove(code, out _)) |
| | | 212 | | { |
| | 0 | 213 | | _logger.LogWarning("Request {Code} already expired", code); |
| | | 214 | | } |
| | | 215 | | } |
| | | 216 | | } |
| | | 217 | | |
| | 12 | 218 | | foreach (var (secret, (timestamp, _)) in _authorizedSecrets) |
| | | 219 | | { |
| | 0 | 220 | | if (expireAll || timestamp < minTime) |
| | | 221 | | { |
| | 0 | 222 | | _logger.LogDebug("Removing expired secret {Secret}", secret); |
| | 0 | 223 | | if (!_authorizedSecrets.TryRemove(secret, out _)) |
| | | 224 | | { |
| | 0 | 225 | | _logger.LogWarning("Secret {Secret} already expired", secret); |
| | | 226 | | } |
| | | 227 | | } |
| | | 228 | | } |
| | 6 | 229 | | } |
| | | 230 | | } |
| | | 231 | | } |