2020-04-15 12:28:42 -07:00
using System ;
2020-06-09 13:18:26 -07:00
using System.Collections.Concurrent ;
2020-04-15 12:28:42 -07:00
using System.Globalization ;
using System.Linq ;
using System.Security.Cryptography ;
2021-06-22 18:09:54 -07:00
using System.Threading.Tasks ;
2020-08-17 14:36:45 -07:00
using MediaBrowser.Common.Extensions ;
using MediaBrowser.Controller.Authentication ;
2020-04-18 23:33:09 -07:00
using MediaBrowser.Controller.Configuration ;
2021-06-23 20:07:08 -07:00
using MediaBrowser.Controller.Net ;
2020-04-15 12:28:42 -07:00
using MediaBrowser.Controller.QuickConnect ;
2021-04-13 17:01:21 -07:00
using MediaBrowser.Controller.Session ;
2020-04-15 12:28:42 -07:00
using MediaBrowser.Model.QuickConnect ;
using Microsoft.Extensions.Logging ;
namespace Emby.Server.Implementations.QuickConnect
{
/// <summary>
/// Quick connect implementation.
/// </summary>
2020-06-09 16:40:35 -07:00
public class QuickConnectManager : IQuickConnect , IDisposable
2020-04-15 12:28:42 -07:00
{
2021-06-18 10:31:47 -07:00
/// <summary>
/// The length of user facing codes.
/// </summary>
private const int CodeLength = 6 ;
/// <summary>
/// The time (in minutes) that the quick connect token is valid.
/// </summary>
private const int Timeout = 10 ;
2021-06-23 20:07:08 -07:00
private readonly RNGCryptoServiceProvider _rng = new ( ) ;
private readonly ConcurrentDictionary < string , QuickConnectResult > _currentRequests = new ( ) ;
private readonly ConcurrentDictionary < string , ( DateTime Timestamp , AuthenticationResult AuthenticationResult ) > _authorizedSecrets = new ( ) ;
2020-04-15 12:28:42 -07:00
2020-06-09 11:28:40 -07:00
private readonly IServerConfigurationManager _config ;
private readonly ILogger < QuickConnectManager > _logger ;
2021-04-13 17:01:21 -07:00
private readonly ISessionManager _sessionManager ;
2020-04-15 12:28:42 -07: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>
2020-04-18 23:33:09 -07:00
/// <param name="config">Configuration.</param>
2020-04-24 16:51:19 -07:00
/// <param name="logger">Logger.</param>
2021-06-22 18:09:54 -07:00
/// <param name="sessionManager">Session Manager.</param>
2020-04-15 12:28:42 -07:00
public QuickConnectManager (
2020-04-18 23:33:09 -07:00
IServerConfigurationManager config ,
2020-04-24 16:51:19 -07:00
ILogger < QuickConnectManager > logger ,
2021-06-22 18:09:54 -07:00
ISessionManager sessionManager )
2020-04-15 12:28:42 -07:00
{
2020-04-18 23:33:09 -07:00
_config = config ;
2020-04-24 16:51:19 -07:00
_logger = logger ;
2021-04-13 17:01:21 -07:00
_sessionManager = sessionManager ;
2020-04-18 23:33:09 -07:00
}
2021-06-18 10:31:47 -07:00
/// <inheritdoc />
public bool IsEnabled = > _config . Configuration . QuickConnectAvailable ;
2020-04-15 12:28:42 -07:00
2021-06-18 10:31:47 -07:00
/// <summary>
/// Assert that quick connect is currently active and throws an exception if it is not.
/// </summary>
private void AssertActive ( )
2020-04-15 12:28:42 -07:00
{
2021-06-18 10:31:47 -07:00
if ( ! IsEnabled )
2020-04-15 12:28:42 -07:00
{
2021-06-18 10:31:47 -07:00
throw new AuthenticationException ( "Quick connect is not active on this server" ) ;
2020-04-15 12:28:42 -07:00
}
}
/// <inheritdoc/>
2021-06-23 20:07:08 -07:00
public QuickConnectResult TryConnect ( AuthorizationInfo authorizationInfo )
2020-04-15 12:28:42 -07:00
{
2021-06-23 20:07:08 -07:00
if ( string . IsNullOrEmpty ( authorizationInfo . DeviceId ) )
{
throw new ArgumentException ( nameof ( authorizationInfo . DeviceId ) + " is required" ) ;
}
if ( string . IsNullOrEmpty ( authorizationInfo . Device ) )
{
throw new ArgumentException ( nameof ( authorizationInfo . Device ) + " is required" ) ;
}
if ( string . IsNullOrEmpty ( authorizationInfo . Client ) )
{
throw new ArgumentException ( nameof ( authorizationInfo . Client ) + " is required" ) ;
}
if ( string . IsNullOrEmpty ( authorizationInfo . Version ) )
{
throw new ArgumentException ( nameof ( authorizationInfo . Version ) + "is required" ) ;
}
2021-06-18 10:31:47 -07:00
AssertActive ( ) ;
2020-04-23 21:44:15 -07:00
ExpireRequests ( ) ;
2020-04-18 23:33:09 -07:00
2021-06-18 10:31:47 -07:00
var secret = GenerateSecureRandom ( ) ;
2020-06-17 23:29:47 -07:00
var code = GenerateCode ( ) ;
2021-06-23 20:07:08 -07:00
var result = new QuickConnectResult (
secret ,
code ,
DateTime . UtcNow ,
authorizationInfo . DeviceId ,
authorizationInfo . Device ,
authorizationInfo . Client ,
authorizationInfo . Version ) ;
2020-04-15 12:28:42 -07:00
2020-06-17 23:29:47 -07:00
_currentRequests [ code ] = result ;
2020-04-15 12:28:42 -07:00
return result ;
}
/// <inheritdoc/>
public QuickConnectResult CheckRequestStatus ( string secret )
{
2020-04-18 23:33:09 -07:00
AssertActive ( ) ;
2021-06-18 10:31:47 -07:00
ExpireRequests ( ) ;
2020-04-15 12:28:42 -07:00
2020-06-17 23:29:47 -07:00
string code = _currentRequests . Where ( x = > x . Value . Secret = = secret ) . Select ( x = > x . Value . Code ) . DefaultIfEmpty ( string . Empty ) . First ( ) ;
2020-04-15 12:28:42 -07:00
2021-06-18 10:31:47 -07:00
if ( ! _currentRequests . TryGetValue ( code , out QuickConnectResult ? result ) )
2020-04-15 12:28:42 -07:00
{
2020-06-17 23:29:47 -07:00
throw new ResourceNotFoundException ( "Unable to find request with provided secret" ) ;
2020-04-15 12:28:42 -07:00
}
2020-06-09 13:18:26 -07:00
return result ;
2020-04-15 12:28:42 -07:00
}
2021-06-18 10:31:47 -07:00
/// <summary>
/// Generates a short code to display to the user to uniquely identify this request.
/// </summary>
/// <returns>A short, unique alphanumeric string.</returns>
private string GenerateCode ( )
2020-04-15 12:28:42 -07:00
{
2020-07-26 16:14:35 -07:00
Span < byte > raw = stackalloc byte [ 4 ] ;
2020-04-15 12:28:42 -07: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 16:14:35 -07:00
scale = BitConverter . ToUInt32 ( raw ) ;
2020-04-15 12:28:42 -07:00
}
2020-06-09 11:28:40 -07:00
int code = ( int ) ( min + ( ( max - min ) * ( scale / ( double ) uint . MaxValue ) ) ) ;
2020-04-15 12:28:42 -07:00
return code . ToString ( CultureInfo . InvariantCulture ) ;
}
/// <inheritdoc/>
2021-06-22 18:09:54 -07:00
public async Task < bool > AuthorizeRequest ( Guid userId , string code )
2020-04-15 12:28:42 -07:00
{
AssertActive ( ) ;
2021-06-18 10:31:47 -07:00
ExpireRequests ( ) ;
2020-04-15 12:28:42 -07:00
2021-06-18 10:31:47 -07:00
if ( ! _currentRequests . TryGetValue ( code , out QuickConnectResult ? result ) )
2020-04-15 12:28:42 -07:00
{
2020-06-17 23:29:47 -07:00
throw new ResourceNotFoundException ( "Unable to find request" ) ;
2020-04-15 12:28:42 -07:00
}
if ( result . Authenticated )
{
throw new InvalidOperationException ( "Request is already authorized" ) ;
}
2020-06-17 23:29:47 -07:00
// 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.
2021-06-23 20:07:08 -07:00
result . DateAdded = DateTime . UtcNow . Add ( TimeSpan . FromMinutes ( 1 ) ) ;
2020-04-15 12:28:42 -07:00
2021-06-23 20:07:08 -07:00
var authenticationResult = await _sessionManager . AuthenticateDirect ( new AuthenticationRequest
{
UserId = userId ,
DeviceId = result . DeviceId ,
DeviceName = result . DeviceName ,
App = result . AppName ,
AppVersion = result . AppVersion
} ) . ConfigureAwait ( false ) ;
_authorizedSecrets [ result . Secret ] = ( DateTime . UtcNow , authenticationResult ) ;
result . Authenticated = true ;
_currentRequests [ code ] = result ;
2020-04-15 12:28:42 -07:00
2021-06-23 20:07:08 -07:00
_logger . LogDebug ( "Authorizing device with code {Code} to login as user {UserId}" , code , userId ) ;
2020-04-18 23:33:09 -07:00
2020-04-15 12:28:42 -07:00
return true ;
}
2021-06-23 20:07:08 -07:00
/// <inheritdoc/>
public AuthenticationResult GetAuthorizedRequest ( string secret )
{
AssertActive ( ) ;
ExpireRequests ( ) ;
if ( ! _authorizedSecrets . TryGetValue ( secret , out var result ) )
{
throw new ResourceNotFoundException ( "Unable to find request" ) ;
}
return result . AuthenticationResult ;
}
2020-06-09 11:28:40 -07:00
/// <summary>
/// Dispose.
/// </summary>
public void Dispose ( )
{
Dispose ( true ) ;
GC . SuppressFinalize ( this ) ;
}
2020-04-15 12:28:42 -07:00
2020-06-09 11:28:40 -07:00
/// <summary>
/// Dispose.
/// </summary>
/// <param name="disposing">Dispose unmanaged resources.</param>
protected virtual void Dispose ( bool disposing )
{
if ( disposing )
{
2021-06-18 10:31:47 -07:00
_rng . Dispose ( ) ;
2020-06-09 11:28:40 -07:00
}
}
2020-06-09 13:18:26 -07:00
2020-04-15 12:28:42 -07:00
private string GenerateSecureRandom ( int length = 32 )
{
2020-07-26 16:14:35 -07:00
Span < byte > bytes = stackalloc byte [ length ] ;
2020-04-15 12:28:42 -07:00
_rng . GetBytes ( bytes ) ;
2020-11-25 15:40:31 -07:00
return Convert . ToHexString ( bytes ) ;
2020-04-15 12:28:42 -07:00
}
2021-06-18 10:31:47 -07:00
/// <summary>
/// Expire quick connect requests that are over the time limit. If <paramref name="expireAll"/> is true, all requests are unconditionally expired.
/// </summary>
/// <param name="expireAll">If true, all requests will be expired.</param>
private void ExpireRequests ( bool expireAll = false )
2020-04-15 12:28:42 -07:00
{
2021-06-18 10:31:47 -07:00
// All requests before this timestamp have expired
var minTime = DateTime . UtcNow . AddMinutes ( - Timeout ) ;
2020-04-18 23:33:09 -07:00
2020-06-08 13:48:18 -07:00
// Expire stale connection requests
2021-04-30 06:09:36 -07:00
foreach ( var ( _ , currentRequest ) in _currentRequests )
2020-04-15 12:28:42 -07:00
{
2021-06-23 20:07:08 -07:00
if ( expireAll | | currentRequest . DateAdded < minTime )
2020-04-15 12:28:42 -07:00
{
2021-04-30 06:09:36 -07:00
var code = currentRequest . Code ;
_logger . LogDebug ( "Removing expired request {Code}" , code ) ;
2020-04-15 12:28:42 -07:00
2020-07-26 16:14:35 -07:00
if ( ! _currentRequests . TryRemove ( code , out _ ) )
{
2021-04-30 06:09:36 -07:00
_logger . LogWarning ( "Request {Code} already expired" , code ) ;
2020-07-26 16:14:35 -07:00
}
2020-06-09 13:18:26 -07:00
}
2020-04-15 12:28:42 -07:00
}
2021-06-23 20:07:08 -07:00
foreach ( var ( secret , ( timestamp , _ ) ) in _authorizedSecrets )
{
if ( expireAll | | timestamp < minTime )
{
_logger . LogDebug ( "Removing expired secret {Secret}" , secret ) ;
if ( ! _authorizedSecrets . TryRemove ( secret , out _ ) )
{
_logger . LogWarning ( "Secret {Secret} already expired" , secret ) ;
}
}
}
2020-04-15 12:28:42 -07:00
}
}
}