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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. allowedDomain,
  50. httpContext.Items[Constants.NONCE_KEY]));
  51. }
  52. return _next(httpContext);
  53. }
  54. }
  55. // Extension method used to add the middleware to the HTTP request pipeline.
  56. public static class CSPMiddlewareExtensions
  57. {
  58. public static IApplicationBuilder UseCSP(this IApplicationBuilder builder)
  59. {
  60. return builder.UseMiddleware<CSPMiddleware>();
  61. }
  62. }
  63. }