PluginSecurityManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 response = await _httpClient.GetResponse(new HttpRequestOptions
  96. {
  97. Url = "http://192.168.1.2:8096/emby/Videos/663c8a38ccfe91af6566852f78e62c26/stream.mkv?Static=true&mediaSourceId=663c8a38ccfe91af6566852f78e62c26&deviceId=hyJA92oXn4RExFTGismCnY6da91kwnTvv8YvsYf0E&Tag=bcdc02b1cdd6f1eb4a57a6812831617b"
  98. }).ConfigureAwait(false);
  99. var tasks = new List<Task>();
  100. ResetSupporterInfo();
  101. tasks.AddRange(RegisteredEntities.Select(i => i.LoadRegistrationInfoAsync()));
  102. await Task.WhenAll(tasks);
  103. }
  104. /// <summary>
  105. /// Gets the registration status.
  106. /// This overload supports existing plug-ins.
  107. /// </summary>
  108. /// <param name="feature">The feature.</param>
  109. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  110. /// <returns>Task{MBRegistrationRecord}.</returns>
  111. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent = null)
  112. {
  113. return GetRegistrationStatusInternal(feature, mb2Equivalent);
  114. }
  115. /// <summary>
  116. /// Gets the registration status.
  117. /// </summary>
  118. /// <param name="feature">The feature.</param>
  119. /// <param name="mb2Equivalent">The MB2 equivalent.</param>
  120. /// <param name="version">The version of this feature</param>
  121. /// <returns>Task{MBRegistrationRecord}.</returns>
  122. public Task<MBRegistrationRecord> GetRegistrationStatus(string feature, string mb2Equivalent, string version)
  123. {
  124. return GetRegistrationStatusInternal(feature, mb2Equivalent, version);
  125. }
  126. private Task<MBRegistrationRecord> GetSupporterRegistrationStatus()
  127. {
  128. return GetRegistrationStatusInternal("MBSupporter", null, _appHost.ApplicationVersion.ToString());
  129. }
  130. /// <summary>
  131. /// Gets or sets the supporter key.
  132. /// </summary>
  133. /// <value>The supporter key.</value>
  134. public string SupporterKey
  135. {
  136. get
  137. {
  138. return LicenseFile.RegKey;
  139. }
  140. set
  141. {
  142. var newValue = value;
  143. if (newValue != null)
  144. {
  145. newValue = newValue.Trim();
  146. }
  147. if (newValue != LicenseFile.RegKey)
  148. {
  149. LicenseFile.RegKey = newValue;
  150. LicenseFile.Save();
  151. // re-load registration info
  152. Task.Run(() => LoadAllRegistrationInfo());
  153. }
  154. }
  155. }
  156. /// <summary>
  157. /// Register an app store sale with our back-end. It will validate the transaction with the store
  158. /// and then register the proper feature and then fill in the supporter key on success.
  159. /// </summary>
  160. /// <param name="parameters">Json parameters to send to admin server</param>
  161. public async Task RegisterAppStoreSale(string parameters)
  162. {
  163. var options = new HttpRequestOptions()
  164. {
  165. Url = AppstoreRegUrl,
  166. CancellationToken = CancellationToken.None,
  167. BufferContent = false
  168. };
  169. options.RequestHeaders.Add("X-Emby-Token", _appHost.SystemId);
  170. options.RequestContent = parameters;
  171. options.RequestContentType = "application/json";
  172. try
  173. {
  174. using (var response = await _httpClient.Post(options).ConfigureAwait(false))
  175. {
  176. var reg = _jsonSerializer.DeserializeFromStream<RegRecord>(response.Content);
  177. if (reg == null)
  178. {
  179. var msg = "Result from appstore registration was null.";
  180. _logger.Error(msg);
  181. throw new ArgumentException(msg);
  182. }
  183. if (!String.IsNullOrEmpty(reg.key))
  184. {
  185. SupporterKey = reg.key;
  186. }
  187. }
  188. }
  189. catch (ArgumentException)
  190. {
  191. SaveAppStoreInfo(parameters);
  192. throw;
  193. }
  194. catch (HttpException e)
  195. {
  196. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  197. if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.PaymentRequired)
  198. {
  199. throw new PaymentRequiredException();
  200. }
  201. throw new Exception("Error registering store sale");
  202. }
  203. catch (Exception e)
  204. {
  205. _logger.ErrorException("Error registering appstore purchase {0}", e, parameters ?? "NO PARMS SENT");
  206. SaveAppStoreInfo(parameters);
  207. //TODO - could create a re-try routine on start-up if this file is there. For now we can handle manually.
  208. throw new Exception("Error registering store sale");
  209. }
  210. }
  211. private void SaveAppStoreInfo(string info)
  212. {
  213. // Save all transaction information to a file
  214. try
  215. {
  216. _fileSystem.WriteAllText(Path.Combine(_appPaths.ProgramDataPath, "apptrans-error.txt"), info);
  217. }
  218. catch (IOException)
  219. {
  220. }
  221. }
  222. private async Task<MBRegistrationRecord> GetRegistrationStatusInternal(string feature,
  223. string mb2Equivalent = null,
  224. string version = null)
  225. {
  226. var regInfo = LicenseFile.GetRegInfo(feature);
  227. var lastChecked = regInfo == null ? DateTime.MinValue : regInfo.LastChecked;
  228. var expDate = regInfo == null ? DateTime.MinValue : regInfo.ExpirationDate;
  229. var maxCacheDays = 14;
  230. var nextCheckDate = new [] { expDate, lastChecked.AddDays(maxCacheDays) }.Min();
  231. if (nextCheckDate > DateTime.UtcNow.AddDays(maxCacheDays))
  232. {
  233. nextCheckDate = DateTime.MinValue;
  234. }
  235. //check the reg file first to alleviate strain on the MB admin server - must actually check in every 30 days tho
  236. var reg = new RegRecord
  237. {
  238. // Cache the result for up to a week
  239. registered = regInfo != null && nextCheckDate >= DateTime.UtcNow && expDate >= DateTime.UtcNow,
  240. expDate = expDate
  241. };
  242. var success = reg.registered;
  243. if (!(lastChecked > DateTime.UtcNow.AddDays(-1)) || !reg.registered)
  244. {
  245. var data = new Dictionary<string, string>
  246. {
  247. { "feature", feature },
  248. { "key", SupporterKey },
  249. { "mac", _appHost.SystemId },
  250. { "systemid", _appHost.SystemId },
  251. { "mb2equiv", mb2Equivalent },
  252. { "ver", version },
  253. { "platform", _appHost.OperatingSystemDisplayName }
  254. };
  255. try
  256. {
  257. var options = new HttpRequestOptions
  258. {
  259. Url = MBValidateUrl,
  260. // Seeing block length errors
  261. EnableHttpCompression = false,
  262. BufferContent = false
  263. };
  264. options.SetPostData(data);
  265. using (var json = (await _httpClient.Post(options).ConfigureAwait(false)).Content)
  266. {
  267. reg = _jsonSerializer.DeserializeFromStream<RegRecord>(json);
  268. success = true;
  269. }
  270. if (reg.registered)
  271. {
  272. _logger.Info("Registered for feature {0}", feature);
  273. LicenseFile.AddRegCheck(feature, reg.expDate);
  274. }
  275. else
  276. {
  277. _logger.Info("Not registered for feature {0}", feature);
  278. LicenseFile.RemoveRegCheck(feature);
  279. }
  280. }
  281. catch (Exception e)
  282. {
  283. _logger.ErrorException("Error checking registration status of {0}", e, feature);
  284. }
  285. }
  286. var record = new MBRegistrationRecord
  287. {
  288. IsRegistered = reg.registered,
  289. ExpirationDate = reg.expDate,
  290. RegChecked = true,
  291. RegError = !success
  292. };
  293. record.TrialVersion = IsInTrial(reg.expDate, record.RegChecked, record.IsRegistered);
  294. record.IsValid = !record.RegChecked || record.IsRegistered || record.TrialVersion;
  295. return record;
  296. }
  297. private bool IsInTrial(DateTime expirationDate, bool regChecked, bool isRegistered)
  298. {
  299. //don't set this until we've successfully obtained exp date
  300. if (!regChecked)
  301. {
  302. return false;
  303. }
  304. var isInTrial = expirationDate > DateTime.UtcNow;
  305. return isInTrial && !isRegistered;
  306. }
  307. /// <summary>
  308. /// Resets the supporter info.
  309. /// </summary>
  310. private void ResetSupporterInfo()
  311. {
  312. _isMbSupporter = null;
  313. _isMbSupporterInitialized = false;
  314. }
  315. }
  316. }