private static void LoadMods()
    {
        // Check for Known DRM and Workarounds.
        var basicPeParser = new BasicPeParser(Environment.CurrentProcessLocation.Value);
        var drmTypes      = DRMHelper.CheckDrmAndNotify(basicPeParser, _loader.Logger, out bool requiresDelayStart);

        // Note: If loaded externally, we assume another mod loader or DLL override took care of bypassing DRM.
        bool loadedFromExternalSource = (_parameters.Flags & EntryPointFlags.LoadedExternally) != 0;

        if (loadedFromExternalSource)
        {
            Logger?.LogWriteLineAsync($"Note: Reloaded is being loaded from an external source or mod loader.", Logger.ColorInformation);
        }

        if (!requiresDelayStart || loadedFromExternalSource)
        {
            _loader.LoadForCurrentProcess();
        }
        else
        {
            Logger?.LogWriteLineAsync($"DRM Requiring Delayed Initialization ({drmTypes}) Found.\n" +
                                      $"Reloaded will try to initialize late to bypass this DRM.\n" +
                                      $"Please note this feature is experimental.\n" +
                                      $"If you encounter issues, report and/or try ASI Loader `Edit Application -> Deploy ASI Loader`", Logger.ColorWarning);

            _delayInjector = new DelayInjector(() =>
            {
                Logger?.LogWriteLineAsync($"Loading via Delayed Injection (DRM Workaround)", Logger.ColorInformation);
                _loader.LoadForCurrentProcess();
            }, _loader.Logger);
        }
    }
        private static string AddFairPlayTokenRestrictedAuthorizationPolicyFairPlay(IContentKey contentKey)
        {
            string tokenTemplateString = DRMHelper.GenerateTokenRequirementsString(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true);

            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "FairPlay Token Authorization Policy",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                    Requirements       = tokenTemplateString,
                }
            };

            // Configure FairPlay policy option.
            string FairPlayConfiguration = ConfigureFairPlayPolicyOptions();

            IContentKeyAuthorizationPolicyOption FairPlayPolicy = _context.ContentKeyAuthorizationPolicyOptions.Create("FairPlay token option", ContentKeyDeliveryType.FairPlay, restrictions, FairPlayConfiguration);
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = _context.ContentKeyAuthorizationPolicies.CreateAsync("Deliver CBC Content Key with token restrictions").Result;

            contentKeyAuthorizationPolicy.Options.Add(FairPlayPolicy);

            // Associate the content key authorization policy with the content key
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;

            return(tokenTemplateString);
        }
        private static string AddPlayReadyAndWidevineTokenRestrictedAuthorizationPolicy(IContentKey contentKey)
        {
            string tokenTemplateString = DRMHelper.GenerateTokenRequirementsString(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true);

            List <ContentKeyAuthorizationPolicyRestriction> restrictions = new List <ContentKeyAuthorizationPolicyRestriction>
            {
                new ContentKeyAuthorizationPolicyRestriction
                {
                    Name = "Playready and Widevine Token Authorization Policy",
                    KeyRestrictionType = (int)ContentKeyRestrictionType.TokenRestricted,
                    Requirements       = tokenTemplateString,
                }
            };

            // Configure PlayReady and Widevine license templates.
            string PlayReadyLicenseTemplate = ConfigurePlayReadyLicenseTemplate();
            string WidevineLicenseTemplate  = ConfigureWidevineLicenseTemplate();

            IContentKeyAuthorizationPolicyOption PlayReadyPolicy = _context.ContentKeyAuthorizationPolicyOptions.Create("PlayReady token option", ContentKeyDeliveryType.PlayReadyLicense, restrictions, PlayReadyLicenseTemplate);
            IContentKeyAuthorizationPolicyOption WidevinePolicy  = _context.ContentKeyAuthorizationPolicyOptions.Create("Widevine token option", ContentKeyDeliveryType.Widevine, restrictions, WidevineLicenseTemplate);
            IContentKeyAuthorizationPolicy       contentKeyAuthorizationPolicy = _context.ContentKeyAuthorizationPolicies.CreateAsync("Deliver Common Content Key with token restrictions").Result;

            contentKeyAuthorizationPolicy.Options.Add(PlayReadyPolicy);
            contentKeyAuthorizationPolicy.Options.Add(WidevinePolicy);

            // Associate the content key authorization policy with the content key
            contentKey.AuthorizationPolicyId = contentKeyAuthorizationPolicy.Id;
            contentKey = contentKey.UpdateAsync().Result;

            return(tokenTemplateString);
        }
Beispiel #4
0
        public static HttpResponseMessage Run([HttpTrigger(AuthorizationLevel.Function, "get", Route = "token/asset/{assetId}/key/{keyId}")] HttpRequestMessage req, string assetId, string keyId, TraceWriter log)
        {
            // Create and cache the Media Services credentials in a static class variable
            _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey);

            // Used the cached credentials to create CloudMediaContext
            _context = new CloudMediaContext(_cachedCredentials);

            var asset = _context.Assets.Where(a => a.Id == assetId).FirstOrDefault();

            if (asset == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound, $"Asset {assetId} doesn't exist."));
            }

            // Get the raw key value that we'll need to pass to generate the token bec. we specified TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate.
            Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(keyId);

            TokenRestrictionTemplate tokenTemplate = DRMHelper.GenerateTokenRequirements(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true);


            string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(
                tokenTemplate,
                new SymmetricVerificationKey(Convert.FromBase64String(_tokenPrimaryVerificationKey)),
                rawkey,
                DateTime.UtcNow.AddDays(365)
                );

            var tokenResponse = new TokenResponse {
                Token = testToken, TokenBase64 = testToken.Base64Encode()
            };

            return(req.CreateResponse(HttpStatusCode.OK, tokenResponse));
        }
        /// <summary>
        /// Create and associate a key
        /// </summary>
        /// <param name="asset"></param>
        /// <returns></returns>
        private static IContentKey CreateContentKey(IAsset asset, ContentKeyType contentKeyType)
        {
            // Create envelope encryption content key
            Guid keyId      = Guid.NewGuid();
            var  contentKey = DRMHelper.GetRandomBuffer(16);

            IContentKey key = _context.ContentKeys.Create(keyId, contentKey, $"ContentKey {contentKeyType.ToString()}", contentKeyType);

            // Associate the key with the asset.
            asset.ContentKeys.Add(key);

            return(key);
        }
        public static async Task <object> Run([HttpTrigger("post", WebHookType = "genericJson")] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("GetToken requested.");

            var tRequest = await req.Content.ReadAsAsync <TokenRequest>();

            // Sanity checks
            #region Sanity checks
            if (tRequest == null || tRequest.AssetId == null || tRequest.KeyId == null)
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest, new
                {
                    error = "Invalid token request."
                }));
            }
            #endregion

            // Create and cache the Media Services credentials in a static class variable
            _cachedCredentials = new MediaServicesCredentials(_mediaServicesAccountName, _mediaServicesAccountKey);

            // Used the cached credentials to create CloudMediaContext
            _context = new CloudMediaContext(_cachedCredentials);

            var asset = _context.Assets.Where(a => a.Id == tRequest.AssetId).FirstOrDefault();
            if (asset == null)
            {
                return(req.CreateResponse(HttpStatusCode.NotFound, new
                {
                    error = $"Asset {tRequest.AssetId} doesn't exist."
                }));
            }

            // Get the raw key value that we'll need to pass to generate the token bec. we specified TokenClaim.ContentKeyIdentifierClaim in during the creation of TokenRestrictionTemplate.
            Guid rawkey = EncryptionUtils.GetKeyIdAsGuid(tRequest.KeyId);

            TokenRestrictionTemplate tokenTemplate = DRMHelper.GenerateTokenRequirements(_tokenPrimaryVerificationKey, _tokenAlternativeVerificationKey, _tokenScope, _tokenIssuer, true);


            string testToken = TokenRestrictionTemplateSerializer.GenerateTestToken(
                tokenTemplate,
                new SymmetricVerificationKey(Convert.FromBase64String(_tokenPrimaryVerificationKey)),
                rawkey,
                DateTime.UtcNow.AddDays(365)
                );

            var tokenResponse = new TokenResponse {
                Token = testToken, TokenBase64 = testToken.Base64Encode()
            };
            return(req.CreateResponse(HttpStatusCode.OK, tokenResponse));
        }