PluginSecurityManager.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Common.Net;
  10. using MediaBrowser.Common.Security;
  11. using MediaBrowser.Controller;
  12. using MediaBrowser.Model.Cryptography;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using Microsoft.Extensions.Logging;
  16. using MediaBrowser.Model.Net;
  17. using MediaBrowser.Model.Serialization;
  18. namespace Emby.Server.Implementations.Security
  19. {
  20. /// <summary>
  21. /// Class PluginSecurityManager
  22. /// </summary>
  23. public class PluginSecurityManager : ISecurityManager
  24. {
  25. private const string MBValidateUrl = "https://mb3admin.local/admin/service/registration/validate";
  26. private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "https://mb3admin.local/admin/service/appstore/register";
  27. public async Task<bool> IsSupporter()
  28. {
  29. var result = await GetRegistrationStatusInternal("MBSupporter", false, _appHost.ApplicationVersion.ToString(), CancellationToken.None).ConfigureAwait(false);
  30. return result.IsRegistered;
  31. }
  32. private MBLicenseFile _licenseFile;
  33. private MBLicenseFile LicenseFile => _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths, _fileSystem, _cryptographyProvider));
  34. private readonly IHttpClient _httpClient;
  35. private readonly IJsonSerializer _jsonSerializer;
  36. private readonly IServerApplicationHost _appHost;
  37. private readonly ILogger _logger;
  38. private readonly IApplicationPaths _appPaths;
  39. private readonly IFileSystem _fileSystem;
  40. private readonly ICryptoProvider _cryptographyProvider;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
  43. /// </summary>
  44. public PluginSecurityManager(IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
  45. IApplicationPaths appPaths, ILoggerFactory loggerFactory, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
  46. {
  47. if (httpClient == null)
  48. {
  49. throw new ArgumentNullException(nameof(httpClient));
  50. }
  51. _appHost = appHost;
  52. _httpClient = httpClient;
  53. _jsonSerializer = jsonSerializer;
  54. _appPaths = appPaths;
  55. _fileSystem = fileSystem;
  56. _cryptographyProvider = cryptographyProvider;
  57. _logger = loggerFactory.CreateLogger("SecurityManager");
  58. }
  59. /// <summary>
  60. /// Gets the registration status.
  61. /// This overload supports existing plug-ins.
  62. /// </summary>
  63. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature)
  64. {
  65. return GetRegistrationStatusInternal(feature, false, null, CancellationToken.None);
  66. }
  67. /// <summary>
  68. /// Gets or sets the supporter key.
  69. /// </summary>
  70. /// <value>The supporter key.</value>
  71. public string SupporterKey
  72. {
  73. get => LicenseFile.RegKey;
  74. set => throw new Exception("Please call UpdateSupporterKey");
  75. }
  76. public async Task UpdateSupporterKey(string newValue)
  77. {
  78. if (newValue != null)
  79. {
  80. newValue = newValue.Trim();
  81. }
  82. if (!string.Equals(newValue, LicenseFile.RegKey, StringComparison.Ordinal))
  83. {
  84. LicenseFile.RegKey = newValue;
  85. LicenseFile.Save();
  86. // Reset this
  87. await GetRegistrationStatusInternal("MBSupporter", true, _appHost.ApplicationVersion.ToString(), CancellationToken.None).ConfigureAwait(false);
  88. }
  89. }
  90. /// <summary>
  91. /// Register an app store sale with our back-end. It will validate the transaction with the store
  92. /// and then register the proper feature and then fill in the supporter key on success.
  93. /// </summary>
  94. /// <param name="parameters">Json parameters to send to admin server</param>
  95. public async Task RegisterAppStoreSale(string parameters)
  96. {
  97. var options = new HttpRequestOptions()
  98. {
  99. Url = AppstoreRegUrl,
  100. CancellationToken = CancellationToken.None,
  101. BufferContent = false
  102. };
  103. options.RequestHeaders.Add("X-Emby-Token", _appHost.SystemId);
  104. options.RequestContent = parameters;
  105. options.RequestContentType = "application/json";
  106. try
  107. {
  108. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  109. {
  110. var reg = await _jsonSerializer.DeserializeFromStreamAsync<RegRecord>(response.Content).ConfigureAwait(false);
  111. if (reg == null)
  112. {
  113. var msg = "Result from appstore registration was null.";
  114. _logger.LogError(msg);
  115. throw new ArgumentException(msg);
  116. }
  117. if (!string.IsNullOrEmpty(reg.key))
  118. {
  119. await UpdateSupporterKey(reg.key).ConfigureAwait(false);
  120. }
  121. }
  122. }
  123. catch (ArgumentException)
  124. {
  125. SaveAppStoreInfo(parameters);
  126. throw;
  127. }
  128. catch (HttpException ex)
  129. {
  130. _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT");
  131. throw new Exception("Error registering store sale");
  132. }
  133. catch (Exception ex)
  134. {
  135. _logger.LogError(ex, "Error registering appstore purchase {parameters}", parameters ?? "NO PARMS SENT");
  136. SaveAppStoreInfo(parameters);
  137. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  138. throw new Exception("Error registering store sale");
  139. }
  140. }
  141. private void SaveAppStoreInfo(string info)
  142. {
  143. // Save all transaction information to a file
  144. try
  145. {
  146. _fileSystem.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  147. }
  148. catch (IOException)
  149. {
  150. }
  151. }
  152. private SemaphoreSlim _regCheckLock = new SemaphoreSlim(1, 1);
  153. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature, bool forceCallToServer, string version, CancellationToken cancellationToken)
  154. {
  155. await _regCheckLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  156. try
  157. {
  158. var record = new MBRegistrationRecord
  159. {
  160. IsRegistered = true,
  161. RegChecked = true,
  162. TrialVersion = false,
  163. IsValid = true,
  164. RegError = false
  165. };
  166. return record;
  167. }
  168. finally
  169. {
  170. _regCheckLock.Release();
  171. }
  172. }
  173. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  174. {
  175. //don't set this until we've successfully obtained exp date
  176. if (!regChecked)
  177. {
  178. return false;
  179. }
  180. var isInTrial = expirationDate > DateTime.UtcNow;
  181. return isInTrial && !isRegistered;
  182. }
  183. }
  184. }