The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CSPMiddleware.cs 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Http;
  7. using Teknik.Configuration;
  8. using Teknik.Utilities;
  9. namespace Teknik.Middleware
  10. {
  11. // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
  12. public class CSPMiddleware
  13. {
  14. private readonly RequestDelegate _next;
  15. public CSPMiddleware(RequestDelegate next)
  16. {
  17. _next = next;
  18. }
  19. public Task Invoke(HttpContext httpContext, Config config)
  20. {
  21. if (!httpContext.Request.IsLocal())
  22. {
  23. // Default to nothing allowed
  24. string allowedDomain = "'none'";
  25. // Allow this domain
  26. string host = httpContext.Request.Headers["Host"];
  27. if (!string.IsNullOrEmpty(host))
  28. {
  29. string domain = host.GetDomain();
  30. allowedDomain = string.Format("*.{0} {0}", domain);
  31. }
  32. // If a CDN is enabled, then add the cdn host
  33. if (config.UseCdn)
  34. {
  35. allowedDomain += " " + config.CdnHost;
  36. }
  37. httpContext.Response.Headers.Append("Content-Security-Policy", string.Format(
  38. "default-src 'none'; " +
  39. "script-src blob: 'unsafe-eval' 'nonce-{1}' {0}; " +
  40. "style-src 'unsafe-inline' {0}; " +
  41. "img-src data: *; " +
  42. "font-src data: {0}; " +
  43. "connect-src wss: blob: data: {0}; " +
  44. "media-src *; " +
  45. "worker-src blob: mediastream: {0}; " +
  46. "form-action {0}; " +
  47. "base-uri {0}; " +
  48. "frame-ancestors {0}; " +
  49. "object-src {0};",
  50. allowedDomain,
  51. httpContext.Items[Constants.NONCE_KEY]));
  52. }
  53. return _next(httpContext);
  54. }
  55. }
  56. // Extension method used to add the middleware to the HTTP request pipeline.
  57. public static class CSPMiddlewareExtensions
  58. {
  59. public static IApplicationBuilder UseCSP(this IApplicationBuilder builder)
  60. {
  61. return builder.UseMiddleware<CSPMiddleware>();
  62. }
  63. }
  64. }