aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs
blob: adcc6f2cfc332da5c1665a93ef4d26db1ed2b4ee (plain)
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.QuickConnect;
using MediaBrowser.Controller.Security;
using MediaBrowser.Model.QuickConnect;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;

namespace Emby.Server.Implementations.QuickConnect
{
    /// <summary>
    /// Quick connect implementation.
    /// </summary>
    public class QuickConnectManager : IQuickConnect
    {
        private readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
        private readonly ConcurrentDictionary<string, QuickConnectResult> _currentRequests = new ConcurrentDictionary<string, QuickConnectResult>();

        private readonly IServerConfigurationManager _config;
        private readonly ILogger<QuickConnectManager> _logger;
        private readonly IAuthenticationRepository _authenticationRepository;
        private readonly IAuthorizationContext _authContext;
        private readonly IServerApplicationHost _appHost;

        /// <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>
        /// <param name="logger">Logger.</param>
        /// <param name="appHost">Application host.</param>
        /// <param name="authContext">Authentication context.</param>
        /// <param name="authenticationRepository">Authentication repository.</param>
        public QuickConnectManager(
            IServerConfigurationManager config,
            ILogger<QuickConnectManager> logger,
            IServerApplicationHost appHost,
            IAuthorizationContext authContext,
            IAuthenticationRepository authenticationRepository)
        {
            _config = config;
            _logger = logger;
            _appHost = appHost;
            _authContext = authContext;
            _authenticationRepository = authenticationRepository;

            ReloadConfiguration();
        }

        /// <inheritdoc/>
        public int CodeLength { get; set; } = 6;

        /// <inheritdoc/>
        public string TokenNamePrefix { get; set; } = "QuickConnect-";

        /// <inheritdoc/>
        public QuickConnectState State { get; private set; } = QuickConnectState.Unavailable;

        /// <inheritdoc/>
        public int RequestExpiry { get; set; } = 30;

        private bool TemporaryActivation { get; set; } = false;

        private DateTime DateActivated { get; set; }

        /// <inheritdoc/>
        public void AssertActive()
        {
            if (State != QuickConnectState.Active)
            {
                throw new InvalidOperationException("Quick connect is not active on this server");
            }
        }

        /// <inheritdoc/>
        public QuickConnectResult Activate()
        {
            // This should not call SetEnabled since that would persist the "temporary" activation to the configuration file
            State = QuickConnectState.Active;
            DateActivated = DateTime.Now;
            TemporaryActivation = true;

            return new QuickConnectResult();
        }

        /// <inheritdoc/>
        public void SetEnabled(QuickConnectState newState)
        {
            _logger.LogDebug("Changed quick connect state from {0} to {1}", State, newState);

            ExpireRequests(true);
            State = newState;

            _config.SaveConfiguration("quickconnect", new QuickConnectConfiguration()
            {
                State = State
            });

            _logger.LogDebug("Configuration saved");
        }

        /// <inheritdoc/>
        public QuickConnectResult TryConnect(string friendlyName)
        {
            ExpireRequests();

            if (State != QuickConnectState.Active)
            {
                _logger.LogDebug("Refusing quick connect initiation request, current state is {0}", State);

                return new QuickConnectResult()
                {
                    Error = "Quick connect is not active on this server"
                };
            }

            _logger.LogDebug("Got new quick connect request from {friendlyName}", friendlyName);

            var lookup = GenerateSecureRandom();
            var result = new QuickConnectResult()
            {
                Lookup = lookup,
                Secret = GenerateSecureRandom(),
                FriendlyName = friendlyName,
                DateAdded = DateTime.Now,
                Code = GenerateCode()
            };

            _currentRequests[lookup] = result;
            return result;
        }

        /// <inheritdoc/>
        public QuickConnectResult CheckRequestStatus(string secret)
        {
            ExpireRequests();
            AssertActive();

            string lookup = _currentRequests.Where(x => x.Value.Secret == secret).Select(x => x.Value.Lookup).DefaultIfEmpty(string.Empty).First();

            if (!_currentRequests.TryGetValue(lookup, out QuickConnectResult result))
            {
                throw new KeyNotFoundException("Unable to find request with provided identifier");
            }

            return result;
        }

        /// <inheritdoc/>
        public List<QuickConnectResultDto> GetCurrentRequests()
        {
            return GetCurrentRequestsInternal().Select(x => (QuickConnectResultDto)x).ToList();
        }

        /// <inheritdoc/>
        public List<QuickConnectResult> GetCurrentRequestsInternal()
        {
            ExpireRequests();
            AssertActive();
            return _currentRequests.Values.ToList();
        }

        /// <inheritdoc/>
        public string GenerateCode()
        {
            int min = (int)Math.Pow(10, CodeLength - 1);
            int max = (int)Math.Pow(10, CodeLength);

            uint scale = uint.MaxValue;
            while (scale == uint.MaxValue)
            {
                byte[] raw = new byte[4];
                _rng.GetBytes(raw);
                scale = BitConverter.ToUInt32(raw, 0);
            }

            int code = (int)(min + ((max - min) * (scale / (double)uint.MaxValue)));
            return code.ToString(CultureInfo.InvariantCulture);
        }

        /// <inheritdoc/>
        public bool AuthorizeRequest(IRequest request, string lookup)
        {
            ExpireRequests();
            AssertActive();

            var auth = _authContext.GetAuthorizationInfo(request);

            if (!_currentRequests.TryGetValue(lookup, out QuickConnectResult result))
            {
                throw new KeyNotFoundException("Unable to find request");
            }

            if (result.Authenticated)
            {
                throw new InvalidOperationException("Request is already authorized");
            }

            result.Authentication = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);

            // Advance the time on the request so it expires sooner as the client will pick up the changes in a few seconds
            var added = result.DateAdded ?? DateTime.Now.Subtract(new TimeSpan(0, RequestExpiry, 0));
            result.DateAdded = added.Subtract(new TimeSpan(0, RequestExpiry - 1, 0));

            _authenticationRepository.Create(new AuthenticationInfo
            {
                AppName = TokenNamePrefix + result.FriendlyName,
                AccessToken = result.Authentication,
                DateCreated = DateTime.UtcNow,
                DeviceId = _appHost.SystemId,
                DeviceName = _appHost.FriendlyName,
                AppVersion = _appHost.ApplicationVersionString,
                UserId = auth.UserId
            });

            _logger.LogInformation("Allowing device {0} to login as user {1} with quick connect code {2}", result.FriendlyName, auth.User.Name, result.Code);

            return true;
        }

        /// <inheritdoc/>
        public int DeleteAllDevices(Guid user)
        {
            var raw = _authenticationRepository.Get(new AuthenticationInfoQuery()
            {
                DeviceId = _appHost.SystemId,
                UserId = user
            });

            var tokens = raw.Items.Where(x => x.AppName.StartsWith(TokenNamePrefix, StringComparison.CurrentCulture));

            foreach (var token in tokens)
            {
                _authenticationRepository.Delete(token);
                _logger.LogDebug("Deleted token {0}", token.AccessToken);
            }

            return tokens.Count();
        }

        /// <summary>
        /// Dispose.
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Dispose.
        /// </summary>
        /// <param name="disposing">Dispose unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _rng?.Dispose();
            }
        }

        private string GenerateSecureRandom(int length = 32)
        {
            var bytes = new byte[length];
            _rng.GetBytes(bytes);

            return string.Join(string.Empty, bytes.Select(x => x.ToString("x2", CultureInfo.InvariantCulture)));
        }

        /// <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)
        {
            // Check if quick connect should be deactivated
            if (TemporaryActivation && DateTime.Now > DateActivated.AddMinutes(10) && State == QuickConnectState.Active && !expireAll)
            {
                _logger.LogDebug("Quick connect time expired, deactivating");
                SetEnabled(QuickConnectState.Available);
                expireAll = true;
                TemporaryActivation = false;
            }

            // Expire stale connection requests
            var delete = new List<string>();
            var values = _currentRequests.Values.ToList();

            for (int i = 0; i < values.Count; i++)
            {
                var added = values[i].DateAdded ?? DateTime.UnixEpoch;
                if (DateTime.Now > added.AddMinutes(RequestExpiry) || expireAll)
                {
                    delete.Add(values[i].Lookup);
                }
            }

            foreach (var lookup in delete)
            {
                _logger.LogDebug("Removing expired request {lookup}", lookup);

                if (!_currentRequests.TryRemove(lookup, out _))
                {
                    _logger.LogWarning("Request {lookup} already expired", lookup);
                }
            }
        }

        private void ReloadConfiguration()
        {
            var config = _config.GetQuickConnectConfiguration();

            State = config.State;
        }
    }
}