PluginSecurityManager.cs 13 KB

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