jellyfin/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs

286 lines
9.7 KiB
C#
Raw Normal View History

2020-04-15 19:28:42 +00:00
using System;
2020-06-09 20:18:26 +00:00
using System.Collections.Concurrent;
2020-04-15 19:28:42 +00:00
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
2020-08-17 21:36:45 +00:00
using MediaBrowser.Common;
using MediaBrowser.Common.Extensions;
2020-04-15 19:28:42 +00:00
using MediaBrowser.Controller;
2020-08-17 21:36:45 +00:00
using MediaBrowser.Controller.Authentication;
using MediaBrowser.Controller.Configuration;
2020-04-15 19:28:42 +00:00
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.QuickConnect;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.QuickConnect;
using Microsoft.Extensions.Logging;
namespace Emby.Server.Implementations.QuickConnect
{
/// <summary>
/// Quick connect implementation.
/// </summary>
2020-06-09 23:40:35 +00:00
public class QuickConnectManager : IQuickConnect, IDisposable
2020-04-15 19:28:42 +00:00
{
private readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
2020-06-09 20:18:26 +00:00
private readonly ConcurrentDictionary<string, QuickConnectResult> _currentRequests = new ConcurrentDictionary<string, QuickConnectResult>();
2020-04-15 19:28:42 +00:00
private readonly IServerConfigurationManager _config;
private readonly ILogger<QuickConnectManager> _logger;
private readonly IAuthenticationRepository _authenticationRepository;
private readonly IAuthorizationContext _authContext;
private readonly IServerApplicationHost _appHost;
2020-04-15 19:28:42 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="QuickConnectManager"/> class.
/// Should only be called at server startup when a singleton is created.
/// </summary>
/// <param name="config">Configuration.</param>
2020-04-24 23:51:19 +00:00
/// <param name="logger">Logger.</param>
2020-04-15 19:28:42 +00:00
/// <param name="appHost">Application host.</param>
/// <param name="authContext">Authentication context.</param>
/// <param name="authenticationRepository">Authentication repository.</param>
public QuickConnectManager(
IServerConfigurationManager config,
2020-04-24 23:51:19 +00:00
ILogger<QuickConnectManager> logger,
2020-04-15 19:28:42 +00:00
IServerApplicationHost appHost,
IAuthorizationContext authContext,
2020-06-09 20:18:26 +00:00
IAuthenticationRepository authenticationRepository)
2020-04-15 19:28:42 +00:00
{
_config = config;
2020-04-24 23:51:19 +00:00
_logger = logger;
2020-04-15 19:28:42 +00:00
_appHost = appHost;
_authContext = authContext;
_authenticationRepository = authenticationRepository;
ReloadConfiguration();
}
2020-04-15 19:28:42 +00:00
/// <inheritdoc/>
public int CodeLength { get; set; } = 6;
/// <inheritdoc/>
2020-08-17 21:36:45 +00:00
public string TokenName { get; set; } = "QuickConnect";
2020-04-15 19:28:42 +00:00
/// <inheritdoc/>
public QuickConnectState State { get; private set; } = QuickConnectState.Unavailable;
/// <inheritdoc/>
public int Timeout { get; set; } = 5;
private DateTime DateActivated { get; set; }
2020-04-15 19:28:42 +00:00
/// <inheritdoc/>
public void AssertActive()
{
if (State != QuickConnectState.Active)
{
2020-06-18 06:58:58 +00:00
throw new ArgumentException("Quick connect is not active on this server");
2020-04-15 19:28:42 +00:00
}
}
/// <inheritdoc/>
2020-06-18 06:58:58 +00:00
public void Activate()
{
2020-08-17 21:36:45 +00:00
DateActivated = DateTime.UtcNow;
2020-07-27 04:13:14 +00:00
SetState(QuickConnectState.Active);
}
2020-04-15 19:28:42 +00:00
/// <inheritdoc/>
2020-07-27 04:13:14 +00:00
public void SetState(QuickConnectState newState)
2020-04-15 19:28:42 +00:00
{
2020-07-27 04:13:14 +00:00
_logger.LogDebug("Changed quick connect state from {State} to {newState}", State, newState);
2020-04-15 19:28:42 +00:00
2020-06-09 20:18:26 +00:00
ExpireRequests(true);
State = newState;
_config.Configuration.QuickConnectAvailable = newState == QuickConnectState.Available || newState == QuickConnectState.Active;
_config.SaveConfiguration();
_logger.LogDebug("Configuration saved");
2020-04-15 19:28:42 +00:00
}
/// <inheritdoc/>
2020-08-17 21:36:45 +00:00
public QuickConnectResult TryConnect()
2020-04-15 19:28:42 +00:00
{
2020-04-24 04:44:15 +00:00
ExpireRequests();
2020-04-15 19:28:42 +00:00
if (State != QuickConnectState.Active)
{
2020-07-27 04:13:14 +00:00
_logger.LogDebug("Refusing quick connect initiation request, current state is {State}", State);
throw new AuthenticationException("Quick connect is not active on this server");
2020-04-15 19:28:42 +00:00
}
var code = GenerateCode();
2020-04-15 19:28:42 +00:00
var result = new QuickConnectResult()
{
Secret = GenerateSecureRandom(),
2020-08-17 21:36:45 +00:00
DateAdded = DateTime.UtcNow,
Code = code
2020-04-15 19:28:42 +00:00
};
_currentRequests[code] = result;
2020-04-15 19:28:42 +00:00
return result;
}
/// <inheritdoc/>
public QuickConnectResult CheckRequestStatus(string secret)
{
ExpireRequests();
AssertActive();
2020-04-15 19:28:42 +00:00
string code = _currentRequests.Where(x => x.Value.Secret == secret).Select(x => x.Value.Code).DefaultIfEmpty(string.Empty).First();
2020-04-15 19:28:42 +00:00
if (!_currentRequests.TryGetValue(code, out QuickConnectResult result))
2020-04-15 19:28:42 +00:00
{
throw new ResourceNotFoundException("Unable to find request with provided secret");
2020-04-15 19:28:42 +00:00
}
2020-06-09 20:18:26 +00:00
return result;
2020-04-15 19:28:42 +00:00
}
/// <inheritdoc/>
public string GenerateCode()
{
2020-07-26 23:14:35 +00:00
Span<byte> raw = stackalloc byte[4];
2020-04-15 19:28:42 +00:00
int min = (int)Math.Pow(10, CodeLength - 1);
int max = (int)Math.Pow(10, CodeLength);
uint scale = uint.MaxValue;
while (scale == uint.MaxValue)
{
_rng.GetBytes(raw);
2020-07-26 23:14:35 +00:00
scale = BitConverter.ToUInt32(raw);
2020-04-15 19:28:42 +00:00
}
int code = (int)(min + ((max - min) * (scale / (double)uint.MaxValue)));
2020-04-15 19:28:42 +00:00
return code.ToString(CultureInfo.InvariantCulture);
}
/// <inheritdoc/>
2020-08-17 21:36:45 +00:00
public bool AuthorizeRequest(Guid userId, string code)
2020-04-15 19:28:42 +00:00
{
ExpireRequests();
2020-04-15 19:28:42 +00:00
AssertActive();
if (!_currentRequests.TryGetValue(code, out QuickConnectResult result))
2020-04-15 19:28:42 +00:00
{
throw new ResourceNotFoundException("Unable to find request");
2020-04-15 19:28:42 +00:00
}
if (result.Authenticated)
{
throw new InvalidOperationException("Request is already authorized");
}
result.Authentication = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
// Change the time on the request so it expires one minute into the future. It can't expire immediately as otherwise some clients wouldn't ever see that they have been authenticated.
2020-08-17 21:36:45 +00:00
var added = result.DateAdded ?? DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(Timeout));
result.DateAdded = added.Subtract(TimeSpan.FromMinutes(Timeout - 1));
2020-04-15 19:28:42 +00:00
_authenticationRepository.Create(new AuthenticationInfo
{
2020-08-17 21:36:45 +00:00
AppName = TokenName,
2020-04-15 19:28:42 +00:00
AccessToken = result.Authentication,
DateCreated = DateTime.UtcNow,
DeviceId = _appHost.SystemId,
DeviceName = _appHost.FriendlyName,
AppVersion = _appHost.ApplicationVersionString,
2020-08-17 21:36:45 +00:00
UserId = userId
2020-04-15 19:28:42 +00:00
});
2020-08-17 21:36:45 +00:00
_logger.LogDebug("Authorizing device with code {Code} to login as user {userId}", code, userId);
2020-04-15 19:28:42 +00:00
return true;
}
/// <inheritdoc/>
public int DeleteAllDevices(Guid user)
{
var raw = _authenticationRepository.Get(new AuthenticationInfoQuery()
{
DeviceId = _appHost.SystemId,
UserId = user
});
2020-08-26 20:24:24 +00:00
var tokens = raw.Items.Where(x => x.AppName.StartsWith(TokenName, StringComparison.Ordinal));
2020-04-15 19:28:42 +00:00
2020-07-27 04:13:14 +00:00
var removed = 0;
2020-04-15 19:28:42 +00:00
foreach (var token in tokens)
{
_authenticationRepository.Delete(token);
2020-07-27 04:13:14 +00:00
_logger.LogDebug("Deleted token {AccessToken}", token.AccessToken);
removed++;
2020-04-15 19:28:42 +00:00
}
2020-07-27 04:13:14 +00:00
return removed;
2020-04-15 19:28:42 +00:00
}
2020-06-09 20:18:26 +00:00
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
2020-04-15 19:28:42 +00:00
/// <summary>
/// Dispose.
/// </summary>
/// <param name="disposing">Dispose unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_rng?.Dispose();
}
}
2020-06-09 20:18:26 +00:00
2020-04-15 19:28:42 +00:00
private string GenerateSecureRandom(int length = 32)
{
2020-07-26 23:14:35 +00:00
Span<byte> bytes = stackalloc byte[length];
2020-04-15 19:28:42 +00:00
_rng.GetBytes(bytes);
return Hex.Encode(bytes);
2020-04-15 19:28:42 +00:00
}
2020-06-18 06:58:58 +00:00
/// <inheritdoc/>
public void ExpireRequests(bool expireAll = false)
2020-04-15 19:28:42 +00:00
{
2020-06-08 20:48:18 +00:00
// Check if quick connect should be deactivated
2020-08-17 21:36:45 +00:00
if (State == QuickConnectState.Active && DateTime.UtcNow > DateActivated.AddMinutes(Timeout) && !expireAll)
{
_logger.LogDebug("Quick connect time expired, deactivating");
2020-07-27 04:13:14 +00:00
SetState(QuickConnectState.Available);
2020-04-24 04:44:15 +00:00
expireAll = true;
}
2020-06-08 20:48:18 +00:00
// Expire stale connection requests
2020-07-26 23:14:35 +00:00
var code = string.Empty;
2020-04-15 19:28:42 +00:00
var values = _currentRequests.Values.ToList();
2020-06-09 20:18:26 +00:00
for (int i = 0; i < values.Count; i++)
2020-04-15 19:28:42 +00:00
{
2020-06-08 20:48:18 +00:00
var added = values[i].DateAdded ?? DateTime.UnixEpoch;
2020-08-17 21:36:45 +00:00
if (DateTime.UtcNow > added.AddMinutes(Timeout) || expireAll)
2020-04-15 19:28:42 +00:00
{
2020-07-26 23:14:35 +00:00
code = values[i].Code;
_logger.LogDebug("Removing expired request {code}", code);
2020-04-15 19:28:42 +00:00
2020-07-26 23:14:35 +00:00
if (!_currentRequests.TryRemove(code, out _))
{
_logger.LogWarning("Request {code} already expired", code);
}
2020-06-09 20:18:26 +00:00
}
2020-04-15 19:28:42 +00:00
}
}
2020-06-09 20:18:26 +00:00
private void ReloadConfiguration()
{
2020-06-18 06:58:58 +00:00
State = _config.Configuration.QuickConnectAvailable ? QuickConnectState.Available : QuickConnectState.Unavailable;
2020-06-09 20:18:26 +00:00
}
2020-04-15 19:28:42 +00:00
}
}