Merge remote-tracking branch 'upstream/develop' into admin-create-users
[akkoma] / lib / pleroma / plugs / http_security_plug.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Plugs.HTTPSecurityPlug do
6 alias Pleroma.Config
7 import Plug.Conn
8
9 def init(opts), do: opts
10
11 def call(conn, _options) do
12 if Config.get([:http_security, :enabled]) do
13 conn
14 |> merge_resp_headers(headers())
15 |> maybe_send_sts_header(Config.get([:http_security, :sts]))
16 else
17 conn
18 end
19 end
20
21 defp headers do
22 referrer_policy = Config.get([:http_security, :referrer_policy])
23 report_uri = Config.get([:http_security, :report_uri])
24
25 headers = [
26 {"x-xss-protection", "1; mode=block"},
27 {"x-permitted-cross-domain-policies", "none"},
28 {"x-frame-options", "DENY"},
29 {"x-content-type-options", "nosniff"},
30 {"referrer-policy", referrer_policy},
31 {"x-download-options", "noopen"},
32 {"content-security-policy", csp_string() <> ";"}
33 ]
34
35 if report_uri do
36 report_group = %{
37 "group" => "csp-endpoint",
38 "max-age" => 10_886_400,
39 "endpoints" => [
40 %{"url" => report_uri}
41 ]
42 }
43
44 headers ++ [{"reply-to", Jason.encode!(report_group)}]
45 else
46 headers
47 end
48 end
49
50 defp csp_string do
51 scheme = Config.get([Pleroma.Web.Endpoint, :url])[:scheme]
52 static_url = Pleroma.Web.Endpoint.static_url()
53 websocket_url = Pleroma.Web.Endpoint.websocket_url()
54 report_uri = Config.get([:http_security, :report_uri])
55
56 connect_src = "connect-src 'self' #{static_url} #{websocket_url}"
57
58 connect_src =
59 if Mix.env() == :dev do
60 connect_src <> " http://localhost:3035/"
61 else
62 connect_src
63 end
64
65 script_src =
66 if Mix.env() == :dev do
67 "script-src 'self' 'unsafe-eval'"
68 else
69 "script-src 'self'"
70 end
71
72 main_part = [
73 "default-src 'none'",
74 "base-uri 'self'",
75 "frame-ancestors 'none'",
76 "img-src 'self' data: https:",
77 "media-src 'self' https:",
78 "style-src 'self' 'unsafe-inline'",
79 "font-src 'self'",
80 "manifest-src 'self'",
81 connect_src,
82 script_src
83 ]
84
85 report = if report_uri, do: ["report-uri #{report_uri}; report-to csp-endpoint"], else: []
86
87 insecure = if scheme == "https", do: ["upgrade-insecure-requests"], else: []
88
89 (main_part ++ report ++ insecure)
90 |> Enum.join("; ")
91 end
92
93 defp maybe_send_sts_header(conn, true) do
94 max_age_sts = Config.get([:http_security, :sts_max_age])
95 max_age_ct = Config.get([:http_security, :ct_max_age])
96
97 merge_resp_headers(conn, [
98 {"strict-transport-security", "max-age=#{max_age_sts}; includeSubDomains"},
99 {"expect-ct", "enforce, max-age=#{max_age_ct}"}
100 ])
101 end
102
103 defp maybe_send_sts_header(conn, _), do: conn
104 end