private SecurityHeadersPolicyBuilder WithCsp(bool reportOnly, string baseUri, bool blockAllMixedContent, string childSources, string connectSources,
                                              string defaultSources, string fontSources, string formAction, string frameAncestorsSources, string frameSources, string imageSources,
                                              string manifestSources, string mediaSources, string objectSources, string pluginTypes, string reportUri, ContentSecurityPolicyRequireSriFor?requireSriFor,
                                              bool sandbox, ContentSecurityPolicySandboxFlags sandboxFlags,
                                              string scriptSources, ContentSecurityPolicyInlineExecution scriptInlineExecution, string styleSources, ContentSecurityPolicyInlineExecution styleInlineExecution,
                                              bool upgradeInsecureRequests, string workerSources)
 {
     return(WithCsp(reportOnly, new ContentSecurityPolicyHeaderValue
     {
         BaseUri = baseUri,
         BlockAllMixedContent = blockAllMixedContent,
         ChildSources = childSources,
         ConnectSources = connectSources,
         DefaultSources = defaultSources,
         FontSources = fontSources,
         FormAction = formAction,
         FrameAncestorsSources = frameAncestorsSources,
         FrameSources = frameSources,
         ImageSources = imageSources,
         ManifestSources = manifestSources,
         MediaSources = mediaSources,
         ObjectSources = objectSources,
         PluginTypes = pluginTypes,
         ReportUri = reportUri,
         RequireSriFor = requireSriFor,
         Sandbox = sandbox,
         SandboxFlags = sandboxFlags,
         ScriptSources = scriptSources,
         ScriptInlineExecution = scriptInlineExecution,
         StyleSources = styleSources,
         StyleInlineExecution = styleInlineExecution,
         UpgradeInsecureRequests = upgradeInsecureRequests,
         WorkerSources = workerSources
     }));
 }
        private async Task ApplyContentSecurityPolicy(TagHelperOutput output, string uniqueId)
        {
            ContentSecurityPolicyHelper cspHelper = new ContentSecurityPolicyHelper(ViewContext);

            ContentSecurityPolicyInlineExecution currentInlineExecution = cspHelper.GetCurrentInlineExecution(output.TagName);

            if (currentInlineExecution == ContentSecurityPolicyInlineExecution.Nonce)
            {
                output.Attributes.Add(ContentSecurityPolicyHelper.NonceAttribute, cspHelper.GetCurrentNonce());
            }
            else if (currentInlineExecution.IsHashBased())
            {
                string contentHash = null;

                if (!String.IsNullOrEmpty(uniqueId))
                {
                    contentHash = cspHelper.GetHashFromCache(uniqueId);
                }

                if (contentHash == null)
                {
                    string content = output.Content.IsModified ? output.Content.GetContent() : (await output.GetChildContentAsync()).GetContent();
                    contentHash = ContentSecurityPolicyHelper.ComputeHash(currentInlineExecution, content);

                    if (!String.IsNullOrEmpty(uniqueId))
                    {
                        cspHelper.AddHashToCache(uniqueId, contentHash);
                    }
                }

                cspHelper.AddHashToInlineExecutionSources(output.TagName, contentHash);
            }
        }
Exemple #3
0
 /// <summary>
 /// Instantiates a new <see cref="ContentSecurityPolicyHeaderValue"/>.
 /// </summary>
 public ContentSecurityPolicyHeaderValue()
 {
     _blockAllMixedContent = false;
     _defaultSources       = NoneSource;
     _sandbox                 = false;
     _sandboxFlags            = ContentSecurityPolicySandboxFlags.None;
     _scriptInlineExecution   = ContentSecurityPolicyInlineExecution.Refuse;
     _styleInlineExecution    = ContentSecurityPolicyInlineExecution.Refuse;
     _upgradeInsecureRequests = false;
 }
Exemple #4
0
        internal static string ComputeHash(ContentSecurityPolicyInlineExecution hashAlgorithm, string elementContent)
        {
            HashAlgorithmInfo hashAlgorithmInfo = _hashAlgorithmsInfos[hashAlgorithm];

            byte[] elementHashBytes = null;

            using (HashAlgorithm hashAlgorithmImplementation = hashAlgorithmInfo.AlgorithmImplementationCreator())
            {
                elementContent   = elementContent.Replace("\r\n", "\n");
                elementHashBytes = hashAlgorithmImplementation.ComputeHash(Encoding.UTF8.GetBytes(elementContent));
            }

            return(hashAlgorithmInfo.SourcePrefix + Convert.ToBase64String(elementHashBytes));
        }
Exemple #5
0
        internal ContentSecurityPolicyInlineExecution GetCurrentInlineExecution(string elementTagName)
        {
            ContentSecurityPolicyInlineExecution inlineExecution = ContentSecurityPolicyInlineExecution.Unsafe;

            if (_cspFeature != null)
            {
                switch (elementTagName)
                {
                case ScriptTagName:
                    inlineExecution = _cspFeature.ScriptInlineExecution;
                    break;

                case StyleTagName:
                    inlineExecution = _cspFeature.StyleInlineExecution;
                    break;
                }
            }

            return(inlineExecution);
        }
            public ContentSecurityPolicyInlineElement(ViewContext context, string elementTagName, IDictionary <string, object> htmlAttributes)
            {
                _viewContext = context;

                _inlineExecution = (ContentSecurityPolicyInlineExecution)_viewContext.HttpContext.Items[_inlineExecutionContextKeys[elementTagName]];

                _elementTag = new TagBuilder(elementTagName);
                _elementTag.MergeAttributes(htmlAttributes);
                if (_inlineExecution == ContentSecurityPolicyInlineExecution.Nonce)
                {
                    _elementTag.MergeAttribute(_nonceAttribute, (string)_viewContext.HttpContext.Items[ContentSecurityPolicyAttribute.NonceRandomContextKey]);
                }

                _viewContext.Writer.Write(_elementTag.ToString(TagRenderMode.StartTag));

                if (_inlineExecution == ContentSecurityPolicyInlineExecution.Hash)
                {
                    _viewBuilderIndex = ((StringWriter)_viewContext.Writer).GetStringBuilder().Length;
                }
            }
        internal ContentSecurityPolicyInlineElement(ViewContext context, string elementTagName, IDictionary <string, object> htmlAttributes)
        {
            _viewContext = context;

            _inlineExecution = (ContentSecurityPolicyInlineExecution)_viewContext.HttpContext.Items[_inlineExecutionContextKeys[elementTagName]];

            _elementTag = new TagBuilder(elementTagName);
            _elementTag.MergeAttributes(htmlAttributes);
            if (_inlineExecution == ContentSecurityPolicyInlineExecution.Nonce)
            {
                _elementTag.MergeAttribute(_nonceAttribute, (string)_viewContext.HttpContext.Items[ContentSecurityPolicyAttribute.NonceRandomContextKey]);
            }

            _elementTag.TagRenderMode = TagRenderMode.StartTag;
            _elementTag.WriteTo(_viewContext.Writer, HtmlEncoder.Default);

            if (_inlineExecution == ContentSecurityPolicyInlineExecution.Hash)
            {
                _viewContextWriter  = _viewContext.Writer;
                _viewContext.Writer = new StringWriter();
            }
        }
        public ContentSecurityPolicyInlineElement(ViewContext context, string elementTagName, IDictionary <string, object> htmlAttributes)
        {
            _viewContext = context;

            _cspHelper = new ContentSecurityPolicyHelper(_viewContext);
            _currentInlineExecution = _cspHelper.GetCurrentInlineExecution(elementTagName);

            _elementTag = new TagBuilder(elementTagName);
            _elementTag.MergeAttributes(htmlAttributes);
            if (_currentInlineExecution == ContentSecurityPolicyInlineExecution.Nonce)
            {
                _elementTag.MergeAttribute(ContentSecurityPolicyHelper.NonceAttribute, _cspHelper.GetCurrentNonce());
            }

            _elementTag.TagRenderMode = TagRenderMode.StartTag;
            _elementTag.WriteTo(_viewContext.Writer, HtmlEncoder.Default);

            if (_currentInlineExecution.IsHashBased())
            {
                _viewContextWriter  = _viewContext.Writer;
                _viewContext.Writer = new StringWriter();
            }
        }
        private void AppendDirectiveWithInlineExecution(ActionExecutingContext filterContext, StringBuilder policyBuilder, string directive, string source, ContentSecurityPolicyInlineExecution inlineExecution)
        {
            if (!String.IsNullOrWhiteSpace(source) || (inlineExecution != ContentSecurityPolicyInlineExecution.Refuse))
            {
                policyBuilder.Append(directive);

                if (!String.IsNullOrWhiteSpace(source))
                {
                    policyBuilder.AppendFormat(" {0}", source);
                }

                filterContext.HttpContext.Items[InlineExecutionContextKeys[directive]] = inlineExecution;
                switch (inlineExecution)
                {
                case ContentSecurityPolicyInlineExecution.Unsafe:
                    policyBuilder.Append(_unsafeInlineSource);
                    break;

                case ContentSecurityPolicyInlineExecution.Nonce:
                    string nonceRandom = GetNonceRandom(filterContext);
                    policyBuilder.AppendFormat(_nonceSourceFormat, nonceRandom);
                    break;

                case ContentSecurityPolicyInlineExecution.Hash:
                    filterContext.HttpContext.Items[HashListBuilderContextKeys[directive]] = new StringBuilder();
                    policyBuilder.Append(_hashListPlaceholders[directive]);
                    break;

                default:
                    break;
                }

                policyBuilder.Append(_directivesDelimiter);
            }
        }
 /// <summary>
 /// Adds the Content Security Policy to the policy.
 /// </summary>
 /// <param name="baseUri">The list of URLs that can be used to specify the document base URL.</param>
 /// <param name="childSources">The source list for web workers and nested browsing contexts.</param>
 /// <param name="connectSources">The source list for fetch, XMLHttpRequest, WebSocket, and EventSource connections.</param>
 /// <param name="defaultSources">The default source list for directives which can fall back to the default sources.</param>
 /// <param name="fontSources">The source list for fonts loaded using @font-face.</param>
 /// <param name="formAction">The valid endpoints for form submissions.</param>
 /// <param name="frameAncestorsSources">The valid parents that may embed a page using the frame and iframe elements.</param>
 /// <param name="frameSources">The source list for nested browsing contexts loading using elements such as frame and iframe.</param>
 /// <param name="imageSources">The source list for of images and favicons.</param>
 /// <param name="manifestSources">The source list for manifest which can be applied to the resource.</param>
 /// <param name="mediaSources">The source list for loading media using the audio and video elements.</param>
 /// <param name="objectSources">The source list for the object, embed, and applet elements.</param>
 /// <param name="reportUri">The URL to which the user agent should send reports about policy violations.</param>
 /// <param name="requireSriFor">The value indicating if the use of Subresource Integrity is required for scripts or/and styles.</param>
 /// <param name="sandbox">The value indicating if sandbox policy should be applied.</param>
 /// <param name="sandboxFlags">The sandboxing flags (only used when Sandbox is true).</param>
 /// <param name="scriptSources">The source list for scripts.</param>
 /// <param name="scriptInlineExecution">The inline execution mode for scripts.</param>
 /// <param name="styleSources">The source list for stylesheets.</param>
 /// <param name="styleInlineExecution">The inline execution mode for stylesheets.</param>
 /// <param name="blockAllMixedContent">The value indicating if block-all-mixed-content directive should be included.</param>
 /// <param name="upgradeInsecureRequests">The value indicating if upgrade-insecure-requests directive should be included.</param>
 /// <param name="pluginTypes">The types of plugins that can be embedded into a document.</param>
 /// <param name="workerSources">The source list for Worker, SharedWorker, or ServiceWorker scripts.</param>
 /// <returns>The current policy builder.</returns>
 public SecurityHeadersPolicyBuilder WithCsp(string baseUri            = null, string childSources = null, string connectSources = null,
                                             string defaultSources     = ContentSecurityPolicyHeaderValue.NoneSource, string fontSources = null, string formAction = null, string frameAncestorsSources = null, string imageSources = null,
                                             string manifestSources    = null, string mediaSources = null, string objectSources = null, string reportUri = null,
                                             bool sandbox              = false, ContentSecurityPolicySandboxFlags sandboxFlags = ContentSecurityPolicySandboxFlags.None,
                                             string scriptSources      = null, ContentSecurityPolicyInlineExecution scriptInlineExecution = ContentSecurityPolicyInlineExecution.Refuse, string styleSources = null, ContentSecurityPolicyInlineExecution styleInlineExecution = ContentSecurityPolicyInlineExecution.Refuse,
                                             bool blockAllMixedContent = false, bool upgradeInsecureRequests = false, ContentSecurityPolicyRequireSriFor?requireSriFor = null, string pluginTypes = null, string workerSources = null, string frameSources = null)
 {
     return(WithCsp(false, baseUri, blockAllMixedContent, childSources, connectSources, defaultSources, fontSources, formAction, frameAncestorsSources, frameSources,
                    imageSources, manifestSources, mediaSources, objectSources, pluginTypes, reportUri, requireSriFor, sandbox, sandboxFlags,
                    scriptSources, scriptInlineExecution, styleSources, styleInlineExecution, upgradeInsecureRequests, workerSources));
 }
Exemple #11
0
 /// <summary>
 /// Returns value indicating if inline execution mode is one of hash based ones.
 /// </summary>
 /// <param name="inlineExecution">The inline execution mode.</param>
 /// <returns>True if inline execution mode is hash based, otherwise false.</returns>
 public static bool IsHashBased(this ContentSecurityPolicyInlineExecution inlineExecution)
 {
     return((inlineExecution == ContentSecurityPolicyInlineExecution.Hash) ||
            (inlineExecution == ContentSecurityPolicyInlineExecution.Hash384) ||
            (inlineExecution == ContentSecurityPolicyInlineExecution.Hash512));
 }
Exemple #12
0
        private void AppendHeaderValueDirectiveWithInlineExecution(StringBuilder headerValueBuilder, string directiveName, string directiveValue, ContentSecurityPolicyInlineExecution inlineExecution, string nonce, IEnumerable <string> hashes)
        {
            if (!String.IsNullOrWhiteSpace(directiveValue) || (inlineExecution != ContentSecurityPolicyInlineExecution.Refuse))
            {
                headerValueBuilder.Append(directiveName);

                if (!String.IsNullOrWhiteSpace(directiveValue))
                {
                    headerValueBuilder.AppendFormat(" {0}", directiveValue);
                }

                if (inlineExecution == ContentSecurityPolicyInlineExecution.Unsafe)
                {
                    headerValueBuilder.Append(_unsafeInlineSource);
                }
                else if (inlineExecution == ContentSecurityPolicyInlineExecution.Nonce)
                {
                    if (String.IsNullOrWhiteSpace(nonce))
                    {
                        throw new InvalidOperationException("Nonce mode for Content Security Policy inline execution requires providing nonce value.");
                    }

                    headerValueBuilder.AppendFormat(_nonceSourceFormat, nonce);
                }
                else if (inlineExecution.IsHashBased() && (hashes != null))
                {
                    foreach (string inlineHash in hashes)
                    {
                        headerValueBuilder.AppendFormat(_hashSourceFormat, inlineHash);
                    }
                }

                headerValueBuilder.Append(_directiveDelimiter);
            }
        }
            public ContentSecurityPolicyInlineElement(ViewContext context, string elementTagName, IDictionary<string, object> htmlAttributes)
            {
                _viewContext = context;

                _inlineExecution = (ContentSecurityPolicyInlineExecution)_viewContext.HttpContext.Items[_inlineExecutionContextKeys[elementTagName]];

                _elementTag = new TagBuilder(elementTagName);
                _elementTag.MergeAttributes(htmlAttributes);
                if (_inlineExecution == ContentSecurityPolicyInlineExecution.Nonce)
                {
                    _elementTag.MergeAttribute(_nonceAttribute, (string)_viewContext.HttpContext.Items[ContentSecurityPolicyAttribute.NonceRandomContextKey]);
                }

                _viewContext.Writer.Write(_elementTag.ToString(TagRenderMode.StartTag));

                if (_inlineExecution == ContentSecurityPolicyInlineExecution.Hash)
                {
                    _viewBuilderIndex = ((StringWriter)_viewContext.Writer).GetStringBuilder().Length;
                }
            }
        private void AppendDirectiveWithInlineExecution(ActionExecutingContext filterContext, StringBuilder policyBuilder, string directive, string source, ContentSecurityPolicyInlineExecution inlineExecution)
        {
            if (!String.IsNullOrWhiteSpace(source) || (inlineExecution != ContentSecurityPolicyInlineExecution.Refuse))
            {
                policyBuilder.Append(directive);

                if (!String.IsNullOrWhiteSpace(source))
                {
                    policyBuilder.AppendFormat(" {0}", source);
                }

                filterContext.HttpContext.Items[InlineExecutionContextKeys[directive]] = inlineExecution;
                switch (inlineExecution)
                {
                    case ContentSecurityPolicyInlineExecution.Unsafe:
                        policyBuilder.Append(_unsafeInlineSource);
                        break;
                    case ContentSecurityPolicyInlineExecution.Nonce:
                        string nonceRandom = GetNonceRandom(filterContext);
                        policyBuilder.AppendFormat(_nonceSourceFormat, nonceRandom);
                        break;
                    case ContentSecurityPolicyInlineExecution.Hash:
                        filterContext.HttpContext.Items[HashListBuilderContextKeys[directive]] = new StringBuilder();
                        policyBuilder.Append(_hashListPlaceholders[directive]);
                        break;
                    default:
                        break;
                }

                policyBuilder.Append(_directivesDelimiter);
            }
        }