I'm trying to add a Content Security Policy (CSP) to the project - an ocean of errors!

Volk Volk 551 Reputation points
2023-08-09T15:10:17.0566667+00:00

Hi!

I'm trying to add CSP first with the line "Content-Security-Policy-Report-Only" to fix errors in the verification mode.

As it is told, for example, here:

Implementing Content Security Policy (CSP) in ASP.NET Core
https://dotnetthoughts.net/implementing-content-security-policy-in-aspnetcore/

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script Content Security Policy directive:default-src self
https://stackoverflow.com/questions/72376413/refused-to-evaluate-a-string-as-javascript-because-unsafe-eval-is-not-an-allow

app.Use(async (context, next) =>
            {
                context.Response.Headers.Add(
                    "Content-Security-Policy-Report-Only",

                    "default-src 'self'" +

                    "connect-src 'self'" +

                    "script-src 'self'" +

                    "img-src * data:;" +

                    "style-src 'self' 'unsafe-inline'" +

                    "frame-src *"
                );
               
                await next();
            });

CSP_0

But when I start adding external hosts, console tell me that they don't work. In addition, there are strange errors where local hosts are specified. There are even more mistakes.

app.Use(async (context, next) =>
            {
                context.Response.Headers.Add(
                    "Content-Security-Policy-Report-Only",

                    "default-src 'self'" +

                    "connect-src 'self'" +

                    "script-src 'self' 'unsafe-eval' https://cdn.datatables.net https://cdnjs.cloudflare.com https://code.jquery.com https://kit.fontawesome.com" +

                    "img-src * data:;" +

                    "style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.gstatic.com https://ka-f.fontawesome.com https://code.jquery.com https://cdn.datatables.net https://fonts.googleapis.com https://cdn.jsdelivr.net;" +

                    "frame-src *"
                );               
                await next();
            });

CSP_1

How to add CSP to context.Response.Headers, if errors generate errors?
How to implement local hosts with wss//localhost, ws://localhost in general?
Why is there such a horror when implementing CSP?

Can I implement CSP only separately on one page, where the user uploads something to the server (a vulnerable place), and not to the entire site (domain/host)?

Thanks!

Developer technologies | ASP.NET | ASP.NET Core
Microsoft 365 and Office | Development | Office JavaScript API
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-08-10T08:06:19.31+00:00

    Hi @Volk Volk

    User's image

    For the above error, this is exactly what the Content Security Policy (CSP) do. The CSP defines a list of policies/directives and initial values that specify which resources your site allows/blocks, for the no allows resources, it will show the above error.

    To understand the Content Security Policy (CSP), we should learn the policy syntax and directives first:

    The CSP Syntax: Content-Security-Policy: <policy-directive>; <policy-directive>

    where <policy-directive> consists of: <directive> <value> with no internal punctuation.

    Here are some commonly used directives. For detailed reference see Content-Security-Policy:

    default-src:Serves as a fallback for the other fetch directives.

    img-src:Specifies valid sources of images and favicons.

    script-src:Specifies valid sources for JavaScript and WebAssembly resources.

    An overview of the allowed values are listed below. For detailed reference see CSP Source Values and the documentation for individual directives.

    'self':Only allow resources from the current origin.

    'unsafe-inline': Allow use of inline resources.

    You can refer to the following sample:

    In the _Layout.cshtml page: add the custom section in the head.

        @await RenderSectionAsync("MyHead", required: false)
    

    In the Index.cshtml page: Use <meta> tag to set the CSP policy:

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    @section MyHead{
        <meta http-equiv="Content-Security-Policy" content="default-src 'self';" />
    }
    
    <style type="text/css">
     body {
         color: red;
     }
    </style>
    <script type="text/javascript">
        document.onload = alert('hi!');
    </script>
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>
            Learn about
            <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.
        </p>
    
        User ID: @Html.Raw(Request.Query["userId"])
        <img src="https://www.w3schools.com/html/img_girl.jpg" />
    
    </div>
    
    

    In the Privacy.cshtml page: set different CSP policy:

    @page
    @model PrivacyModel
    @{
        ViewData["Title"] = "Privacy Policy";
    }
    @section MyHead{
        <meta http-equiv="Content-Security-Policy" content="default-src 'self' wss:; connect-src 'self' http: wss: ws:;script-src 'self' 'unsafe-inline' scripts.localhost; style-src 'self' 'unsafe-inline' styles.localhost; img-src https://www.w3schools.com 'self' 'unsafe-inline';" />
    }
    <h1>@ViewData["Title"]</h1>
    
    <p>Use this page to detail your site's privacy policy.</p>
    <style type="text/css">
        body {
            color: red;
        }
    </style>
    <script type="text/javascript">
        document.onload = alert('hi!');
    </script>
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>
            Learn about
            <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.
        </p>
    
        User ID: @Html.Raw(Request.Query["userId"])
        <img src="https://www.w3schools.com/html/img_girl.jpg" />
    
    </div>
    

    The result as below: as we can see that, in the index page, the CSP policy will refuse the related resource.

    User's image

    Can I implement CSP only separately on one page, where the user uploads something to the server (a vulnerable place), and not to the entire site (domain/host)?

    For this problem, you can use the <meta> in the specified page, refer to the above sample. Or you can set the response header in the OnGet method (razor page application), like this:

            public void OnGet()
            {
               Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
            }
    

    Or in the HttpGet action method (MVC application):

            public IActionResult Index()
            {
                Response.Headers.Add("Content-Security-Policy", "default-src 'self';");
                return View();
            }
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.