PluginSecurityManager.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 MediaBrowser.Model.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.com/admin/service/registration/validate";
  26. private const string AppstoreRegUrl = /*MbAdmin.HttpsUrl*/ "https://mb3admin.com/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
  34. {
  35. get { return _licenseFile ?? (_licenseFile = new MBLicenseFile(_appPaths, _fileSystem, _cryptographyProvider)); }
  36. }
  37. private readonly IHttpClient _httpClient;
  38. private readonly IJsonSerializer _jsonSerializer;
  39. private readonly IServerApplicationHost _appHost;
  40. private readonly ILogger _logger;
  41. private readonly IApplicationPaths _appPaths;
  42. private readonly IFileSystem _fileSystem;
  43. private readonly ICryptoProvider _cryptographyProvider;
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="PluginSecurityManager" /> class.
  46. /// </summary>
  47. public PluginSecurityManager(IServerApplicationHost appHost, IHttpClient httpClient, IJsonSerializer jsonSerializer,
  48. IApplicationPaths appPaths, ILogManager logManager, IFileSystem fileSystem, ICryptoProvider cryptographyProvider)
  49. {
  50. if (httpClient == null)
  51. {
  52. throw new ArgumentNullException("httpClient");
  53. }
  54. _appHost = appHost;
  55. _httpClient = httpClient;
  56. _jsonSerializer = jsonSerializer;
  57. _appPaths = appPaths;
  58. _fileSystem = fileSystem;
  59. _cryptographyProvider = cryptographyProvider;
  60. _logger = logManager.GetLogger("SecurityManager");
  61. }
  62. /// <summary>
  63. /// Gets the registration status.
  64. /// This overload supports existing plug-ins.
  65. /// </summary>
  66. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature)
  67. {
  68. return GetRegistrationStatusInternal(feature, false, null, CancellationToken.None);
  69. }
  70. /// <summary>
  71. /// Gets or sets the supporter key.
  72. /// </summary>
  73. /// <value>The supporter key.</value>
  74. public string SupporterKey
  75. {
  76. get
  77. {
  78. return LicenseFile.RegKey;
  79. }
  80. set
  81. {
  82. throw new Exception("Please call UpdateSupporterKey");
  83. }
  84. }
  85. public async Task UpdateSupporterKey(string newValue)
  86. {
  87. if (newValue != null)
  88. {
  89. newValue = newValue.Trim();
  90. }
  91. if (!string.Equals(newValue, LicenseFile.RegKey, StringComparison.Ordinal))
  92. {
  93. LicenseFile.RegKey = newValue;
  94. LicenseFile.Save();
  95. // Reset this
  96. await GetRegistrationStatusInternal("MBSupporter", true, _appHost.ApplicationVersion.ToString(), CancellationToken.None).ConfigureAwait(false);
  97. }
  98. }
  99. /// <summary>
  100. /// Register an app store sale with our back-end. It will validate the transaction with the store
  101. /// and then register the proper feature and then fill in the supporter key on success.
  102. /// </summary>
  103. /// <param name="parameters">Json parameters to send to admin server</param>
  104. public async Task RegisterAppStoreSale(string parameters)
  105. {
  106. var options = new HttpRequestOptions()
  107. {
  108. Url = AppstoreRegUrl,
  109. CancellationToken = CancellationToken.None,
  110. BufferContent = false
  111. };
  112. options.RequestHeaders.Add("X-Emby-Token", _appHost.SystemId);
  113. options.RequestContent = parameters;
  114. options.RequestContentType = "application/json";
  115. try
  116. {
  117. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  118. {
  119. var reg = await _jsonSerializer.DeserializeFromStreamAsync<RegRecord>(response.Content).ConfigureAwait(false);
  120. if (reg == null)
  121. {
  122. var msg = "Result from appstore registration was null.";
  123. _logger.Error(msg);
  124. throw new ArgumentException(msg);
  125. }
  126. if (!String.IsNullOrEmpty(reg.key))
  127. {
  128. await UpdateSupporterKey(reg.key).ConfigureAwait(false);
  129. }
  130. }
  131. }
  132. catch (ArgumentException)
  133. {
  134. SaveAppStoreInfo(parameters);
  135. throw;
  136. }
  137. catch (HttpException e)
  138. {
  139. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  140. if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired)
  141. {
  142. throw new PaymentRequiredException();
  143. }
  144. throw new Exception("Error registering store sale");
  145. }
  146. catch (Exception e)
  147. {
  148. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  149. SaveAppStoreInfo(parameters);
  150. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  151. throw new Exception("Error registering store sale");
  152. }
  153. }
  154. private void SaveAppStoreInfo(string info)
  155. {
  156. // Save all transaction information to a file
  157. try
  158. {
  159. _fileSystem.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  160. }
  161. catch (IOException)
  162. {
  163. }
  164. }
  165. private SemaphoreSlim _regCheckLock = new SemaphoreSlim(1, 1);
  166. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature, bool forceCallToServer, string version, CancellationToken cancellationToken)
  167. {
  168. await _regCheckLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  169. try
  170. {
  171. var regInfo = LicenseFile.GetRegInfo(feature);
  172. var lastChecked = regInfo == null ? DateTime.MinValue : regInfo.LastChecked;
  173. var expDate = regInfo == null ? DateTime.MinValue : regInfo.ExpirationDate;
  174. var maxCacheDays = 14;
  175. var nextCheckDate = new[] { expDate, lastChecked.AddDays(maxCacheDays) }.Min();
  176. if (nextCheckDate > DateTime.UtcNow.AddDays(maxCacheDays))
  177. {
  178. nextCheckDate = DateTime.MinValue;
  179. }
  180. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  181. var reg = new RegRecord
  182. {
  183. // Cache the result for up to a week
  184. registered = regInfo != null && nextCheckDate >= DateTime.UtcNow && expDate >= DateTime.UtcNow,
  185. expDate = expDate
  186. };
  187. var key = SupporterKey;
  188. if (!forceCallToServer && string.IsNullOrWhiteSpace(key))
  189. {
  190. return new MBRegistrationRecord();
  191. }
  192. var success = reg.registered;
  193. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)) || (!reg.registered))
  194. {
  195. var data = new Dictionary<string, string>
  196. {
  197. { "feature", feature },
  198. { "key", key },
  199. { "mac", _appHost.SystemId },
  200. { "systemid", _appHost.SystemId },
  201. { "ver", version },
  202. { "platform", _appHost.OperatingSystemDisplayName }
  203. };
  204. try
  205. {
  206. var options = new HttpRequestOptions
  207. {
  208. Url = MBValidateUrl,
  209. // Seeing block length errors
  210. EnableHttpCompression = false,
  211. BufferContent = false,
  212. CancellationToken = cancellationToken
  213. };
  214. options.SetPostData(data);
  215. using (var response = (await _httpClient.Post(options).ConfigureAwait(false)))
  216. {
  217. using (var json = response.Content)
  218. {
  219. reg = await _jsonSerializer.DeserializeFromStreamAsync<RegRecord>(json).ConfigureAwait(false);
  220. success = true;
  221. }
  222. }
  223. if (reg.registered)
  224. {
  225. _logger.Info("Registered for feature {0}", feature);
  226. LicenseFile.AddRegCheck(feature, reg.expDate);
  227. }
  228. else
  229. {
  230. _logger.Info("Not registered for feature {0}", feature);
  231. LicenseFile.RemoveRegCheck(feature);
  232. }
  233. }
  234. catch (Exception e)
  235. {
  236. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  237. }
  238. }
  239. var record = new MBRegistrationRecord
  240. {
  241. IsRegistered = reg.registered,
  242. ExpirationDate = reg.expDate,
  243. RegChecked = true,
  244. RegError = !success
  245. };
  246. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  247. record.IsValid = !record.RegChecked || record.IsRegistered || record.TrialVersion;
  248. return record;
  249. }
  250. finally
  251. {
  252. _regCheckLock.Release();
  253. }
  254. }
  255. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  256. {
  257. //don't set this until we've successfully obtained exp date
  258. if (!regChecked)
  259. {
  260. return false;
  261. }
  262. var isInTrial = expirationDate > DateTime.UtcNow;
  263. return isInTrial && !isRegistered;
  264. }
  265. }
  266. }