aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/csp.go
blob: 7ff4098d63a97aa479b7723b0bd93e3436cbb214 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package middleware

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/url"
	"reflect"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

const HeaderReportTo = "ReportTo"

type ContentSecurityPolicyConfig struct {
	Skipper                 middleware.Skipper
	ReportOnly              bool
	DefaultSrc              []CSPDirective `csp:"default-src"`
	ChildSrc                []CSPDirective `csp:"child-src"`
	ConnectSrc              []CSPDirective `csp:"connect-src"`
	FontSrc                 []CSPDirective `csp:"font-src"`
	FrameSrc                []CSPDirective `csp:"frame-src"`
	ImageSrc                []CSPDirective `csp:"img-src"`
	ManifestSrc             []CSPDirective `csp:"manifest-src"`
	MediaSrc                []CSPDirective `csp:"media-src"`
	ObjectSrc               []CSPDirective `csp:"object-src"`
	ScriptSrc               []CSPDirective `csp:"script-src"`
	StyleSrc                []CSPDirective `csp:"style-src"`
	BaseUri                 []CSPDirective `csp:"base-uri"`
	Sandbox                 []CSPSandbox   `csp:"sandbox"`
	FormAction              []CSPDirective `csp:"form-action"`
	UpgradeInsecureRequests bool           `csp:"upgrade-insecure-requests"`
	FrameAncestors          []CSPDirective `csp:"frame-ancestors"`
	ReportUri               []*url.URL     `csp:"report-uri"`                // deprecated
	ReportTo                []CSPReportTo  `csp:"report-to"`                 // experimental
	PrefetchSrc             []CSPDirective `csp:"prefetch-src"`              // experimental
	ScriptSrcElem           []CSPDirective `csp:"script-src-elem"`           // experimental
	StyleSrcElem            []CSPDirective `csp:"style-src-elem"`            // experimental
	StyleSrcAttr            []CSPDirective `csp:"script-src-attr"`           // experimental
	WorkerSrc               []CSPDirective `csp:"worker-src"`                // experimental
	NavigateTo              []CSPDirective `csp:"navigate-to"`               // experimental
	RequireTrustedTypesFor  []CSPDirective `csp:"require-trusted-types-for"` // experimental
}

func (c *ContentSecurityPolicyConfig) String() string {
	st := reflect.TypeOf(*c)
	sv := reflect.ValueOf(*c)
	lines := []string{}

	for i := 0; i < st.NumField(); i++ {
		cspTag := st.Field(i).Tag.Get("csp")
		if cspTag == "" {
			continue
		}

		v := sv.Field(i)
		switch v.Kind() {
		case reflect.Slice:
			if v.Cap() == 0 {
				continue
			}
			items := make([]string, v.Cap())
			for j := 0; j < v.Cap(); j++ {
				// Call the String() method if there is one to handle things
				// like *net.URL instances. Otherwise just treat the value as a
				// string because it probably is (all CSPDirective types are
				// strings).
				if str := v.Index(j).MethodByName("String"); str.IsValid() {
					items[j] = str.Call(nil)[0].String()
				} else {
					items[j] = v.Index(j).String()
				}
			}
			lines = append(lines, fmt.Sprintf("%s %s", cspTag, strings.Join(items, " ")))
		case reflect.Bool:
			if v.Bool() {
				lines = append(lines, cspTag)
			}
		}
	}

	return strings.Join(lines, "; ") + ";"
}

type CSPReportTo struct {
	GroupName string
	MaxAge    time.Duration
	Endpoints []*url.URL
}

func (r CSPReportTo) MarshalJSON() ([]byte, error) {
	ep := []map[string]string{}
	for _, u := range r.Endpoints {
		ep = append(ep, map[string]string{"url": u.String()})
	}

	return json.Marshal(map[string]interface{}{
		"group":     r.GroupName,
		"max_age":   r.MaxAge.Seconds(),
		"endpoints": ep,
	})
}

type CSPDirective string

const (
	CSPNone          CSPDirective = "'none'"
	CSPSelf                       = "'self'"
	CSPUnsafeInline               = "'unsafe-inline'"
	CSPUnsafeEval                 = "'unsafe-eval'"
	CSPUnsafeHashes               = "'unsafe-hashes'"
	CSPStrictDynamic              = "'strict-dynamic'"
	CSPReportSample               = "'report-sample'"
	CSPData                       = "data:"
	CSPBlob                       = "blob:"
	CSPMediastream                = "mediastream:"
	CSPFilesystem                 = "filesystem:"
	CSPHttp                       = "http:"
	CSPHttps                      = "https:"
)

func CSPHost(s string) CSPDirective {
	return CSPDirective(s)
}

func CSPNonce(n string) CSPDirective {
	return CSPDirective(fmt.Sprintf("'nonce-%s'", n))
}

func CSPShaString(size int, h string) CSPDirective {
	return CSPDirective(fmt.Sprintf("'sha%d-%s'", size, h))
}

type CSPSandbox string

const (
	CSPAllowDownloads           CSPSandbox = "allow-downloads"
	CSPAllowDownloadsNoUser                = "allow-downloads-without-user-activation"
	CSPAllowForms                          = "allow-forms"
	CSPAllowModals                         = "allow-modals"
	CSPAllowOrientationLock                = "allow-orientation-lock"
	CSPAllowPointerLock                    = "allow-pointer-lock"
	CSPAllowPopups                         = "allow-popups"
	CSPAllowPopupEscape                    = "allow-popups-to-escape-sandbox"
	CSPAllowPresentation                   = "allow-presentation"
	CSPAllowSameOrigin                     = "allow-same-origin"
	CSPAllowScripts                        = "allow-scripts"
	CSPAllowStorageAccessByUser            = "allow-storage-access-by-user-activation"
	CSPAllowTopActivation                  = "allow-top-navigation"
	CSPAllowNavigationByUser               = "allow-top-navigation-by-user-activation"
)

var DefaultContentSecurityPolicyConfig = ContentSecurityPolicyConfig{
	Skipper:    middleware.DefaultSkipper,
	DefaultSrc: []CSPDirective{CSPSelf, CSPData},
}

func ContentSecurityPolicy() echo.MiddlewareFunc {
	return ContentSecurityPolicyWithConfig(DefaultContentSecurityPolicyConfig)
}

func ContentSecurityPolicyWithConfig(config ContentSecurityPolicyConfig) echo.MiddlewareFunc {
	if config.Skipper == nil {
		config.Skipper = DefaultContentSecurityPolicyConfig.Skipper
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			if config.Skipper(c) {
				return next(c)
			}

			h := c.Response().Header()
			if config.ReportOnly {
				h.Set(echo.HeaderContentSecurityPolicyReportOnly, config.String())
			} else {
				h.Set(echo.HeaderContentSecurityPolicy, config.String())
			}

			if config.ReportTo != nil {
				rt := bytes.Buffer{}
				je := json.NewEncoder(&rt)
				for _, r := range config.ReportTo {
					_ = je.Encode(r)
					rt.WriteString(", ")
				}
				h.Set(HeaderReportTo, rt.String())
			}

			return next(c)
		}
	}
}