Debian Codegraph @

config/security/securityConfig.go

raw
1 // Copyright 2018 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package security
15
16 import (
17 "bytes"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "net/netip"
22 "net/url"
23 "reflect"
24 "slices"
25 "strconv"
26 "strings"
27
28 "github.com/gohugoio/hugo/common/herrors"
29 "github.com/gohugoio/hugo/common/types"
30 "github.com/gohugoio/hugo/config"
31 "github.com/gohugoio/hugo/parser"
32 "github.com/gohugoio/hugo/parser/metadecoders"
33 "github.com/mitchellh/mapstructure"
34 )
35
36 const securityConfigKey = "security"
37
38 // DefaultConfig holds the default security policy.
39 var DefaultConfig = Config{
40 Exec: Exec{
41 Allow: MustNewWhitelist(
42 "^(dart-)?sass$", // sass, dart-sass
43 "^go$", // for Go Modules
44 "^git$", // For Git info
45 "^node$", // Used as the runtime for Node tools.
46 "^postcss$",
47 ),
48 // These have been tested to work with Hugo's external programs
49 // on Windows, Linux and MacOS.
50 OsEnv: MustNewWhitelist(`(?i)^((HTTPS?|NO)_PROXY|PATH(EXT)?|APPDATA|TE?MP|TERM|GO\w+|(XDG_CONFIG_)?HOME|USERPROFILE|SSH_AUTH_SOCK|DISPLAY|LANG|SYSTEMDRIVE|PROGRAMDATA)$`),
51 },
52 Funcs: Funcs{
53 Getenv: MustNewWhitelist("^HUGO_", "^CI$"),
54 },
55 HTTP: HTTP{
56 // Allow URLs whose host starts with a letter (the typical
57 // "https://example.com" shape), deny anything that looks like
58 // localhost, and deny URLs with userinfo ("http://user@...") to
59 // foil the obvious SSRF bypass. Public IP literals are collateral
60 // blocks; users who need them can override security.http.urls.
61 URLs: MustNewWhitelist(
62 `(?i)^https?://[a-z0-9]`,
63 `! ^https?://\d+\.`,
64 `! (?i)localhost`,
65 `! (?i)^https?://[^/?#]*@`,
66 ),
67 Methods: MustNewWhitelist("(?i)GET|POST"),
68 },
69 Node: Node{
70 Permissions: NodePermissions{
71 Disable: false,
72 AllowRead: []string{"."},
73 AllowWrite: []string{}, // No write access by default.
74 AllowAddons: []string{"tailwindcss"}, // tailwindcss does not work without addon permissions.
75 AllowWorker: []string{"tailwindcss"}, // tailwindcss needs worker access.
76 AllowChildProcess: []string{"tailwindcss"}, // detect-libc spawns getconf on some Linux setups.
77 },
78 },
79 // Content under /content is treated as untrusted. text/html bodies are
80 // emitted verbatim and are an XSS sink, so they are denied by default.
81 // Everything else is allowed because Whitelist treats a deny-only list as
82 // "allow anything not denied".
83 AllowContent: MustNewWhitelist("! ^text/html$"),
84 }
85
86 // Config is the top level security config.
87 // <docsmeta>{"name": "security", "description": "This section holds the top level security config.", "newIn": "0.91.0" }</docsmeta>
88 type Config struct {
89 // Restricts access to os.Exec....
90 // <docsmeta>{ "newIn": "0.91.0" }</docsmeta>
91 Exec Exec `json:"exec"`
92
93 // Restricts access to certain template funcs.
94 Funcs Funcs `json:"funcs"`
95
96 // Restricts access to resources.GetRemote, getJSON, getCSV.
97 HTTP HTTP `json:"http"`
98
99 // Node holds Node.js security settings.
100 Node Node `json:"node"`
101
102 // AllowContent restricts which content media types may be used for
103 // pages under /content. Matched against the full MIME type (e.g.
104 // "text/html"). text/html is denied by default because Hugo emits the
105 // body verbatim.
106 AllowContent Whitelist `json:"allowContent"`
107
108 // Allow inline shortcodes
109 EnableInlineShortcodes bool `json:"enableInlineShortcodes"`
110 }
111
112 // Exec holds os/exec policies.
113 type Exec struct {
114 Allow Whitelist `json:"allow"`
115 OsEnv Whitelist `json:"osEnv"`
116 }
117
118 // Funcs holds template funcs policies.
119 type Funcs struct {
120 // OS env keys allowed to query in os.Getenv.
121 Getenv Whitelist `json:"getenv"`
122 }
123
124 type HTTP struct {
125 // URLs to allow in remote HTTP (resources.Get, getJSON, getCSV).
126 URLs Whitelist `json:"urls"`
127
128 // HTTP methods to allow.
129 Methods Whitelist `json:"methods"`
130
131 // Media types where the Content-Type in the response is used instead of resolving from the file content.
132 MediaTypes Whitelist `json:"mediaTypes"`
133 }
134
135 // Node holds Node.js security settings.
136 type Node struct {
137 // Permissions configures Node's --permission flag for file system access control.
138 Permissions NodePermissions `json:"permissions"`
139 }
140
141 // NodePermissions configures the Node.js permission model (--permission).
142 // Paths are relative to the working directory; "." means the working directory itself.
143 // Use "*" to allow all paths.
144 type NodePermissions struct {
145 // Disable turns off the Node.js permission model entirely.
146 Disable bool `json:"disable"`
147 AllowRead []string `json:"allowRead"`
148 AllowWrite []string `json:"allowWrite"`
149 AllowAddons []string `json:"allowAddons"`
150 AllowWorker []string `json:"allowWorker"`
151 AllowChildProcess []string `json:"allowChildProcess"`
152 }
153
154 // IsEnabled reports whether the Node.js permission model is active.
155 func (p NodePermissions) IsEnabled() bool {
156 return !p.Disable
157 }
158
159 // ToTOML converts c to TOML with [security] as the root.
160 func (c Config) ToTOML() string {
161 sec := c.ToSecurityMap()
162
163 var b bytes.Buffer
164
165 if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil {
166 panic(err)
167 }
168
169 return strings.TrimSpace(b.String())
170 }
171
172 func (c Config) CheckAllowedExec(name string) error {
173 if !c.Exec.Allow.Accept(name) {
174 return &AccessDeniedError{
175 name: name,
176 path: "security.exec.allow",
177 policies: c.ToTOML(),
178 }
179 }
180 return nil
181 }
182
183 func (c Config) CheckAllowedGetEnv(name string) error {
184 if !c.Funcs.Getenv.Accept(name) {
185 return &AccessDeniedError{
186 name: name,
187 path: "security.funcs.getenv",
188 policies: c.ToTOML(),
189 }
190 }
191 return nil
192 }
193
194 func (c Config) CheckAllowedHTTPURL(u string) error {
195 deny := func(name string) error {
196 return &AccessDeniedError{
197 name: name,
198 path: "security.http.urls",
199 policies: c.ToTOML(),
200 }
201 }
202 if !c.HTTP.URLs.Accept(u) {
203 return deny(u)
204 }
205 // A host can be written as an integer/hex/octal IPv4 literal
206 // (e.g. http://2130706433/ == http://127.0.0.1/) that has no dot and
207 // thus slips past IP-literal deny rules. Re-check the canonical form so
208 // the policy treats every encoding of the same address alike.
209 if canon, ok := canonicalIPv4URL(u); ok && !c.HTTP.URLs.Accept(canon) {
210 return deny(u)
211 }
212 return nil
213 }
214
215 // canonicalIPv4URL rewrites an integer/hex/octal IPv4 host in rawURL to its
216 // canonical dotted-decimal form (inet_aton semantics), returning ok=false when
217 // the host is a normal name or already dotted-decimal.
218 func canonicalIPv4URL(rawURL string) (string, bool) {
219 u, err := url.Parse(rawURL)
220 if err != nil {
221 return "", false
222 }
223 host := u.Hostname()
224 ip, ok := parseInetAtonIPv4(host)
225 if !ok || ip.String() == host {
226 return "", false
227 }
228 if port := u.Port(); port != "" {
229 u.Host = ip.String() + ":" + port
230 } else {
231 u.Host = ip.String()
232 }
233 return u.String(), true
234 }
235
236 // parseInetAtonIPv4 parses the inet_aton IPv4 forms (1–4 dot-separated parts,
237 // each decimal, octal "0..." or hex "0x..."), e.g. "2130706433", "0x7f.0.0.1".
238 func parseInetAtonIPv4(host string) (netip.Addr, bool) {
239 if host == "" {
240 return netip.Addr{}, false
241 }
242 parts := strings.Split(host, ".")
243 if len(parts) > 4 {
244 return netip.Addr{}, false
245 }
246 vals := make([]uint64, len(parts))
247 for i, p := range parts {
248 v, ok := parseCInt(p)
249 if !ok {
250 return netip.Addr{}, false
251 }
252 vals[i] = v
253 }
254 maxLast := []uint64{0xffffffff, 0xffffff, 0xffff, 0xff}[len(parts)-1]
255 var n uint64
256 for i, v := range vals {
257 if i == len(parts)-1 {
258 if v > maxLast {
259 return netip.Addr{}, false
260 }
261 n |= v
262 } else {
263 if v > 0xff {
264 return netip.Addr{}, false
265 }
266 n |= v << (8 * (3 - i))
267 }
268 }
269 return netip.AddrFrom4([4]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}), true
270 }
271
272 func parseCInt(s string) (uint64, bool) {
273 base := 10
274 switch {
275 case len(s) >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'):
276 base, s = 16, s[2:]
277 case len(s) >= 2 && s[0] == '0':
278 base, s = 8, s[1:]
279 }
280 if s == "" {
281 return 0, false
282 }
283 v, err := strconv.ParseUint(s, base, 64)
284 if err != nil {
285 return 0, false
286 }
287 return v, true
288 }
289
290 func (c Config) CheckAllowedHTTPMethod(method string) error {
291 if !c.HTTP.Methods.Accept(method) {
292 return &AccessDeniedError{
293 name: method,
294 path: "security.http.method",
295 policies: c.ToTOML(),
296 }
297 }
298 return nil
299 }
300
301 func (c Config) CheckAllowedContent(mediaType string) error {
302 if !c.AllowContent.Accept(mediaType) {
303 return &AccessDeniedError{
304 name: mediaType,
305 path: "security.allowContent",
306 policies: c.ToTOML(),
307 }
308 }
309 return nil
310 }
311
312 // ToSecurityMap converts c to a map with 'security' as the root key.
313 func (c Config) ToSecurityMap() map[string]any {
314 // Take it to JSON and back to get proper casing etc.
315 asJson, err := json.Marshal(c)
316 herrors.Must(err)
317 m := make(map[string]any)
318 herrors.Must(json.Unmarshal(asJson, &m))
319
320 // Add the root
321 sec := map[string]any{
322 "security": m,
323 }
324 return sec
325 }
326
327 // DecodeConfig creates a privacy Config from a given Hugo configuration.
328 func DecodeConfig(cfg config.Provider) (Config, error) {
329 sc := DefaultConfig
330 // Deep copy slices to prevent mapstructure from mutating DefaultConfig.
331 sc.Node.Permissions.AllowRead = slices.Clone(sc.Node.Permissions.AllowRead)
332 sc.Node.Permissions.AllowWrite = slices.Clone(sc.Node.Permissions.AllowWrite)
333 sc.Node.Permissions.AllowAddons = slices.Clone(sc.Node.Permissions.AllowAddons)
334 sc.Node.Permissions.AllowWorker = slices.Clone(sc.Node.Permissions.AllowWorker)
335 sc.Node.Permissions.AllowChildProcess = slices.Clone(sc.Node.Permissions.AllowChildProcess)
336 if cfg.IsSet(securityConfigKey) {
337 m := cfg.GetStringMap(securityConfigKey)
338 dec, err := mapstructure.NewDecoder(
339 &mapstructure.DecoderConfig{
340 WeaklyTypedInput: true,
341 Result: &sc,
342 DecodeHook: stringSliceToWhitelistHook(),
343 },
344 )
345 if err != nil {
346 return sc, err
347 }
348
349 if err = dec.Decode(m); err != nil {
350 return sc, err
351 }
352 }
353
354 if !sc.EnableInlineShortcodes {
355 // Legacy
356 sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes")
357 }
358
359 return sc, nil
360 }
361
362 func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType {
363 return func(
364 f reflect.Type,
365 t reflect.Type,
366 data any,
367 ) (any, error) {
368 if t != reflect.TypeFor[Whitelist]() {
369 return data, nil
370 }
371
372 wl := types.ToStringSlicePreserveString(data)
373
374 return NewWhitelist(wl...)
375 }
376 }
377
378 // AccessDeniedError represents a security policy conflict.
379 type AccessDeniedError struct {
380 path string
381 name string
382 policies string
383 }
384
385 func (e *AccessDeniedError) Error() string {
386 return fmt.Sprintf("access denied: %q is not whitelisted in policy %q; the current security configuration is:\n\n%s\n\n", e.name, e.path, e.policies)
387 }
388
389 // IsAccessDenied reports whether err is an AccessDeniedError
390 func IsAccessDenied(err error) bool {
391 var notFoundErr *AccessDeniedError
392 return errors.As(err, &notFoundErr)
393 }