PluginSecurityManager.cs 7.5 KB

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