| 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" |
| 22 |
"net/netip" |
| 23 |
"net/url" |
| 24 |
"reflect" |
| 25 |
"slices" |
| 26 |
"strconv" |
| 27 |
"strings" |
| 28 |
|
| 29 |
"github.com/gohugoio/hugo/common/herrors" |
| 30 |
"github.com/gohugoio/hugo/common/types" |
| 31 |
"github.com/gohugoio/hugo/config" |
| 32 |
"github.com/gohugoio/hugo/parser" |
| 33 |
"github.com/gohugoio/hugo/parser/metadecoders" |
| 34 |
"github.com/mitchellh/mapstructure" |
| 35 |
) |
| 36 |
|
| 37 |
const securityConfigKey = "security" |
| 38 |
|
| 39 |
// DefaultConfig holds the default security policy. |
| 40 |
var DefaultConfig = Config{ |
| 41 |
Exec: Exec{ |
| 42 |
Allow: MustNewWhitelist( |
| 43 |
"^(dart-)?sass$", // sass, dart-sass |
| 44 |
"^go$", // for Go Modules |
| 45 |
"^git$", // For Git info |
| 46 |
"^node$", // Used as the runtime for Node tools. |
| 47 |
"^postcss$", |
| 48 |
), |
| 49 |
// These have been tested to work with Hugo's external programs |
| 50 |
// on Windows, Linux and MacOS. |
| 51 |
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)$`), |
| 52 |
}, |
| 53 |
Funcs: Funcs{ |
| 54 |
Getenv: MustNewWhitelist("^HUGO_", "^CI$"), |
| 55 |
}, |
| 56 |
HTTP: HTTP{ |
| 57 |
// Allow URLs whose host starts with a letter (the typical |
| 58 |
// "https://example.com" shape), deny anything that looks like |
| 59 |
// localhost, and deny URLs with userinfo ("http://user@...") to |
| 60 |
// foil the obvious SSRF bypass. Public IP literals are collateral |
| 61 |
// blocks; users who need them can override security.http.urls. |
| 62 |
URLs: MustNewWhitelist( |
| 63 |
`(?i)^https?://[a-z0-9]`, |
| 64 |
`! (?i)^https?://\d+\.`, |
| 65 |
`! (?i)localhost`, |
| 66 |
`! (?i)^https?://[^/?#]*@`, |
| 67 |
), |
| 68 |
Methods: MustNewWhitelist("(?i)GET|POST"), |
| 69 |
}, |
| 70 |
Node: Node{ |
| 71 |
Permissions: NodePermissions{ |
| 72 |
Disable: false, |
| 73 |
AllowRead: []string{"."}, |
| 74 |
AllowWrite: []string{}, // No write access by default. |
| 75 |
AllowAddons: []string{"tailwindcss"}, // tailwindcss does not work without addon permissions. |
| 76 |
AllowWorker: []string{"tailwindcss"}, // tailwindcss needs worker access. |
| 77 |
AllowChildProcess: []string{"tailwindcss"}, // detect-libc spawns getconf on some Linux setups. |
| 78 |
}, |
| 79 |
}, |
| 80 |
// Content under /content is treated as untrusted. text/html bodies are |
| 81 |
// emitted verbatim and are an XSS sink, so they are denied by default. |
| 82 |
// The same goes for text/org, whose export blocks and inline snippets |
| 83 |
// pass raw HTML through unescaped. |
| 84 |
// Everything else is allowed because Whitelist treats a deny-only list as |
| 85 |
// "allow anything not denied". |
| 86 |
AllowContent: MustNewWhitelist("! ^text/html$", "! ^text/org$"), |
| 87 |
} |
| 88 |
|
| 89 |
// Config is the top level security config. |
| 90 |
// <docsmeta>{"name": "security", "description": "This section holds the top level security config.", "newIn": "0.91.0" }</docsmeta> |
| 91 |
type Config struct { |
| 92 |
// Restricts access to os.Exec.... |
| 93 |
// <docsmeta>{ "newIn": "0.91.0" }</docsmeta> |
| 94 |
Exec Exec `json:"exec"` |
| 95 |
|
| 96 |
// Restricts access to certain template funcs. |
| 97 |
Funcs Funcs `json:"funcs"` |
| 98 |
|
| 99 |
// Restricts access to resources.GetRemote, getJSON, getCSV. |
| 100 |
HTTP HTTP `json:"http"` |
| 101 |
|
| 102 |
// Node holds Node.js security settings. |
| 103 |
Node Node `json:"node"` |
| 104 |
|
| 105 |
// AllowContent restricts which content media types may be used for |
| 106 |
// pages under /content. Matched against the full MIME type (e.g. |
| 107 |
// "text/html"). text/html is denied by default because Hugo emits the |
| 108 |
// body verbatim. |
| 109 |
AllowContent Whitelist `json:"allowContent"` |
| 110 |
|
| 111 |
// Allow inline shortcodes |
| 112 |
EnableInlineShortcodes bool `json:"enableInlineShortcodes"` |
| 113 |
} |
| 114 |
|
| 115 |
// Exec holds os/exec policies. |
| 116 |
type Exec struct { |
| 117 |
Allow Whitelist `json:"allow"` |
| 118 |
OsEnv Whitelist `json:"osEnv"` |
| 119 |
} |
| 120 |
|
| 121 |
// Funcs holds template funcs policies. |
| 122 |
type Funcs struct { |
| 123 |
// OS env keys allowed to query in os.Getenv. |
| 124 |
Getenv Whitelist `json:"getenv"` |
| 125 |
} |
| 126 |
|
| 127 |
type HTTP struct { |
| 128 |
// URLs to allow in remote HTTP (resources.Get, getJSON, getCSV). |
| 129 |
URLs Whitelist `json:"urls"` |
| 130 |
|
| 131 |
// Whether to honor the HTTP_PROXY, HTTPS_PROXY and NO_PROXY environment |
| 132 |
// variables for remote HTTP. Off by default, as a proxy hides the |
| 133 |
// resolved destination address from the security policy. |
| 134 |
// <docsmeta>{ "newIn": "0.166.0" }</docsmeta> |
| 135 |
ProxyFromEnvironment bool `json:"proxyFromEnvironment"` |
| 136 |
|
| 137 |
// HTTP methods to allow. |
| 138 |
Methods Whitelist `json:"methods"` |
| 139 |
|
| 140 |
// Media types where the Content-Type in the response is used instead of resolving from the file content. |
| 141 |
MediaTypes Whitelist `json:"mediaTypes"` |
| 142 |
} |
| 143 |
|
| 144 |
// Node holds Node.js security settings. |
| 145 |
type Node struct { |
| 146 |
// Permissions configures Node's --permission flag for file system access control. |
| 147 |
Permissions NodePermissions `json:"permissions"` |
| 148 |
} |
| 149 |
|
| 150 |
// NodePermissions configures the Node.js permission model (--permission). |
| 151 |
// Paths are relative to the working directory; "." means the working directory itself. |
| 152 |
// Use "*" to allow all paths. |
| 153 |
type NodePermissions struct { |
| 154 |
// Disable turns off the Node.js permission model entirely. |
| 155 |
Disable bool `json:"disable"` |
| 156 |
AllowRead []string `json:"allowRead"` |
| 157 |
AllowWrite []string `json:"allowWrite"` |
| 158 |
AllowAddons []string `json:"allowAddons"` |
| 159 |
AllowWorker []string `json:"allowWorker"` |
| 160 |
AllowChildProcess []string `json:"allowChildProcess"` |
| 161 |
} |
| 162 |
|
| 163 |
// IsEnabled reports whether the Node.js permission model is active. |
| 164 |
func (p NodePermissions) IsEnabled() bool { |
| 165 |
return !p.Disable |
| 166 |
} |
| 167 |
|
| 168 |
// ToTOML converts c to TOML with [security] as the root. |
| 169 |
func (c Config) ToTOML() string { |
| 170 |
sec := c.ToSecurityMap() |
| 171 |
|
| 172 |
var b bytes.Buffer |
| 173 |
|
| 174 |
if err := parser.InterfaceToConfig(sec, metadecoders.TOML, &b); err != nil { |
| 175 |
panic(err) |
| 176 |
} |
| 177 |
|
| 178 |
return strings.TrimSpace(b.String()) |
| 179 |
} |
| 180 |
|
| 181 |
func (c Config) CheckAllowedExec(name string) error { |
| 182 |
if !c.Exec.Allow.Accept(name) { |
| 183 |
return &AccessDeniedError{ |
| 184 |
name: name, |
| 185 |
path: "security.exec.allow", |
| 186 |
policies: c.ToTOML(), |
| 187 |
} |
| 188 |
} |
| 189 |
return nil |
| 190 |
} |
| 191 |
|
| 192 |
func (c Config) CheckAllowedGetEnv(name string) error { |
| 193 |
if !c.Funcs.Getenv.Accept(name) { |
| 194 |
return &AccessDeniedError{ |
| 195 |
name: name, |
| 196 |
path: "security.funcs.getenv", |
| 197 |
policies: c.ToTOML(), |
| 198 |
} |
| 199 |
} |
| 200 |
return nil |
| 201 |
} |
| 202 |
|
| 203 |
func (c Config) CheckAllowedHTTPURL(u string) error { |
| 204 |
deny := func(name string) error { |
| 205 |
return &AccessDeniedError{ |
| 206 |
name: name, |
| 207 |
path: "security.http.urls", |
| 208 |
policies: c.ToTOML(), |
| 209 |
} |
| 210 |
} |
| 211 |
if !c.HTTP.URLs.Accept(u) { |
| 212 |
return deny(u) |
| 213 |
} |
| 214 |
// A host can be written as an integer/hex/octal IPv4 literal |
| 215 |
// (e.g. http://2130706433/ == http://127.0.0.1/) that has no dot and |
| 216 |
// thus slips past IP-literal deny rules. Re-check the canonical form so |
| 217 |
// the policy treats every encoding of the same address alike. |
| 218 |
if canon, ok := canonicalIPv4URL(u); ok && !c.HTTP.URLs.Accept(canon) { |
| 219 |
return deny(u) |
| 220 |
} |
| 221 |
return nil |
| 222 |
} |
| 223 |
|
| 224 |
// CheckAllowedHTTPAddress reports whether a dial-time destination address may |
| 225 |
// be connected to. address is the resolved "host:port" passed to a net.Dialer |
| 226 |
// control hook, i.e. the actual address the HTTP client is about to connect to. |
| 227 |
// |
| 228 |
// The security.http.urls allowlist only inspects the URL text and never sees |
| 229 |
// the resolved address, so a hostname that resolves to a loopback, private or |
| 230 |
// link-local (including the cloud metadata endpoint) address would otherwise |
| 231 |
// satisfy the policy and let resources.GetRemote reach an internal endpoint. |
| 232 |
// We deny any non–global-unicast or private address here to close that gap. |
| 233 |
func (c Config) CheckAllowedHTTPAddress(network, address string) error { |
| 234 |
// Only enforced under the default hardened allowlist. If the user has |
| 235 |
// customized security.http.urls they have opted into whatever hosts they |
| 236 |
// listed, including internal ones (e.g. a local dev server), so we do not |
| 237 |
// second-guess the resolved address. |
| 238 |
if !slices.Equal(c.HTTP.URLs.patternsStrings, DefaultConfig.HTTP.URLs.patternsStrings) { |
| 239 |
return nil |
| 240 |
} |
| 241 |
deny := func(name string) error { |
| 242 |
return &AccessDeniedError{ |
| 243 |
name: name, |
| 244 |
path: "security.http.urls", |
| 245 |
policies: c.ToTOML(), |
| 246 |
} |
| 247 |
} |
| 248 |
host, _, err := net.SplitHostPort(address) |
| 249 |
if err != nil { |
| 250 |
host = address |
| 251 |
} |
| 252 |
ip, err := netip.ParseAddr(host) |
| 253 |
if err != nil { |
| 254 |
// The dial hook always hands us a resolved IP literal; anything else |
| 255 |
// is unexpected, so fail closed. |
| 256 |
return deny(address) |
| 257 |
} |
| 258 |
if !isPublicAddr(ip) { |
| 259 |
return deny(host) |
| 260 |
} |
| 261 |
return nil |
| 262 |
} |
| 263 |
|
| 264 |
// Special-purpose ranges that Go classifies as global unicast and |
| 265 |
// non-private, but that are never reachable on the public Internet. |
| 266 |
var nonPublicPrefixes = []netip.Prefix{ |
| 267 |
netip.MustParsePrefix("100.64.0.0/10"), // Shared address space (CGNAT), RFC 6598. |
| 268 |
netip.MustParsePrefix("192.0.0.0/24"), // IETF protocol assignments. |
| 269 |
netip.MustParsePrefix("192.0.2.0/24"), // TEST-NET-1. |
| 270 |
netip.MustParsePrefix("198.18.0.0/15"), // Benchmarking. |
| 271 |
netip.MustParsePrefix("198.51.100.0/24"), // TEST-NET-2. |
| 272 |
netip.MustParsePrefix("203.0.113.0/24"), // TEST-NET-3. |
| 273 |
netip.MustParsePrefix("240.0.0.0/4"), // Reserved. |
| 274 |
netip.MustParsePrefix("2001:db8::/32"), // Documentation. |
| 275 |
netip.MustParsePrefix("3fff::/20"), // Documentation. |
| 276 |
netip.MustParsePrefix("2001:2::/48"), // Benchmarking. |
| 277 |
} |
| 278 |
|
| 279 |
// nat64Prefixes embed an IPv4 address in the low 32 bits, RFC 6052/8215. |
| 280 |
var nat64Prefixes = []netip.Prefix{ |
| 281 |
netip.MustParsePrefix("64:ff9b::/96"), |
| 282 |
netip.MustParsePrefix("64:ff9b:1::/48"), |
| 283 |
} |
| 284 |
|
| 285 |
func isPublicAddr(ip netip.Addr) bool { |
| 286 |
ip = ip.Unmap() |
| 287 |
for _, p := range nat64Prefixes { |
| 288 |
if p.Contains(ip) { |
| 289 |
b := ip.As16() |
| 290 |
return isPublicAddr(netip.AddrFrom4([4]byte(b[12:]))) |
| 291 |
} |
| 292 |
} |
| 293 |
if !ip.IsGlobalUnicast() || ip.IsPrivate() { |
| 294 |
return false |
| 295 |
} |
| 296 |
for _, p := range nonPublicPrefixes { |
| 297 |
if p.Contains(ip) { |
| 298 |
return false |
| 299 |
} |
| 300 |
} |
| 301 |
return true |
| 302 |
} |
| 303 |
|
| 304 |
// canonicalIPv4URL rewrites an integer/hex/octal IPv4 host in rawURL to its |
| 305 |
// canonical dotted-decimal form (inet_aton semantics), returning ok=false when |
| 306 |
// the host is a normal name or already dotted-decimal. |
| 307 |
func canonicalIPv4URL(rawURL string) (string, bool) { |
| 308 |
u, err := url.Parse(rawURL) |
| 309 |
if err != nil { |
| 310 |
return "", false |
| 311 |
} |
| 312 |
host := u.Hostname() |
| 313 |
ip, ok := parseInetAtonIPv4(host) |
| 314 |
if !ok || ip.String() == host { |
| 315 |
return "", false |
| 316 |
} |
| 317 |
if port := u.Port(); port != "" { |
| 318 |
u.Host = ip.String() + ":" + port |
| 319 |
} else { |
| 320 |
u.Host = ip.String() |
| 321 |
} |
| 322 |
return u.String(), true |
| 323 |
} |
| 324 |
|
| 325 |
// parseInetAtonIPv4 parses the inet_aton IPv4 forms (1–4 dot-separated parts, |
| 326 |
// each decimal, octal "0..." or hex "0x..."), e.g. "2130706433", "0x7f.0.0.1". |
| 327 |
func parseInetAtonIPv4(host string) (netip.Addr, bool) { |
| 328 |
if host == "" { |
| 329 |
return netip.Addr{}, false |
| 330 |
} |
| 331 |
parts := strings.Split(host, ".") |
| 332 |
if len(parts) > 4 { |
| 333 |
return netip.Addr{}, false |
| 334 |
} |
| 335 |
vals := make([]uint64, len(parts)) |
| 336 |
for i, p := range parts { |
| 337 |
v, ok := parseCInt(p) |
| 338 |
if !ok { |
| 339 |
return netip.Addr{}, false |
| 340 |
} |
| 341 |
vals[i] = v |
| 342 |
} |
| 343 |
maxLast := []uint64{0xffffffff, 0xffffff, 0xffff, 0xff}[len(parts)-1] |
| 344 |
var n uint64 |
| 345 |
for i, v := range vals { |
| 346 |
if i == len(parts)-1 { |
| 347 |
if v > maxLast { |
| 348 |
return netip.Addr{}, false |
| 349 |
} |
| 350 |
n |= v |
| 351 |
} else { |
| 352 |
if v > 0xff { |
| 353 |
return netip.Addr{}, false |
| 354 |
} |
| 355 |
n |= v << (8 * (3 - i)) |
| 356 |
} |
| 357 |
} |
| 358 |
return netip.AddrFrom4([4]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)}), true |
| 359 |
} |
| 360 |
|
| 361 |
func parseCInt(s string) (uint64, bool) { |
| 362 |
base := 10 |
| 363 |
switch { |
| 364 |
case len(s) >= 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'): |
| 365 |
base, s = 16, s[2:] |
| 366 |
case len(s) >= 2 && s[0] == '0': |
| 367 |
base, s = 8, s[1:] |
| 368 |
} |
| 369 |
if s == "" { |
| 370 |
return 0, false |
| 371 |
} |
| 372 |
v, err := strconv.ParseUint(s, base, 64) |
| 373 |
if err != nil { |
| 374 |
return 0, false |
| 375 |
} |
| 376 |
return v, true |
| 377 |
} |
| 378 |
|
| 379 |
func (c Config) CheckAllowedHTTPMethod(method string) error { |
| 380 |
if !c.HTTP.Methods.Accept(method) { |
| 381 |
return &AccessDeniedError{ |
| 382 |
name: method, |
| 383 |
path: "security.http.method", |
| 384 |
policies: c.ToTOML(), |
| 385 |
} |
| 386 |
} |
| 387 |
return nil |
| 388 |
} |
| 389 |
|
| 390 |
func (c Config) CheckAllowedContent(mediaType string) error { |
| 391 |
if !c.AllowContent.Accept(mediaType) { |
| 392 |
return &AccessDeniedError{ |
| 393 |
name: mediaType, |
| 394 |
path: "security.allowContent", |
| 395 |
policies: c.ToTOML(), |
| 396 |
} |
| 397 |
} |
| 398 |
return nil |
| 399 |
} |
| 400 |
|
| 401 |
// ToSecurityMap converts c to a map with 'security' as the root key. |
| 402 |
func (c Config) ToSecurityMap() map[string]any { |
| 403 |
// Take it to JSON and back to get proper casing etc. |
| 404 |
asJson, err := json.Marshal(c) |
| 405 |
herrors.Must(err) |
| 406 |
m := make(map[string]any) |
| 407 |
herrors.Must(json.Unmarshal(asJson, &m)) |
| 408 |
|
| 409 |
// Add the root |
| 410 |
sec := map[string]any{ |
| 411 |
"security": m, |
| 412 |
} |
| 413 |
return sec |
| 414 |
} |
| 415 |
|
| 416 |
// DecodeConfig creates a privacy Config from a given Hugo configuration. |
| 417 |
func DecodeConfig(cfg config.Provider) (Config, error) { |
| 418 |
sc := DefaultConfig |
| 419 |
// Deep copy slices to prevent mapstructure from mutating DefaultConfig. |
| 420 |
sc.Node.Permissions.AllowRead = slices.Clone(sc.Node.Permissions.AllowRead) |
| 421 |
sc.Node.Permissions.AllowWrite = slices.Clone(sc.Node.Permissions.AllowWrite) |
| 422 |
sc.Node.Permissions.AllowAddons = slices.Clone(sc.Node.Permissions.AllowAddons) |
| 423 |
sc.Node.Permissions.AllowWorker = slices.Clone(sc.Node.Permissions.AllowWorker) |
| 424 |
sc.Node.Permissions.AllowChildProcess = slices.Clone(sc.Node.Permissions.AllowChildProcess) |
| 425 |
if cfg.IsSet(securityConfigKey) { |
| 426 |
m := cfg.GetStringMap(securityConfigKey) |
| 427 |
dec, err := mapstructure.NewDecoder( |
| 428 |
&mapstructure.DecoderConfig{ |
| 429 |
WeaklyTypedInput: true, |
| 430 |
Result: &sc, |
| 431 |
DecodeHook: stringSliceToWhitelistHook(), |
| 432 |
}, |
| 433 |
) |
| 434 |
if err != nil { |
| 435 |
return sc, err |
| 436 |
} |
| 437 |
|
| 438 |
if err = dec.Decode(m); err != nil { |
| 439 |
return sc, err |
| 440 |
} |
| 441 |
} |
| 442 |
|
| 443 |
if !sc.EnableInlineShortcodes { |
| 444 |
// Legacy |
| 445 |
sc.EnableInlineShortcodes = cfg.GetBool("enableInlineShortcodes") |
| 446 |
} |
| 447 |
|
| 448 |
return sc, nil |
| 449 |
} |
| 450 |
|
| 451 |
func stringSliceToWhitelistHook() mapstructure.DecodeHookFuncType { |
| 452 |
return func( |
| 453 |
f reflect.Type, |
| 454 |
t reflect.Type, |
| 455 |
data any, |
| 456 |
) (any, error) { |
| 457 |
if t != reflect.TypeFor[Whitelist]() { |
| 458 |
return data, nil |
| 459 |
} |
| 460 |
|
| 461 |
wl := types.ToStringSlicePreserveString(data) |
| 462 |
|
| 463 |
return NewWhitelist(wl...) |
| 464 |
} |
| 465 |
} |
| 466 |
|
| 467 |
// AccessDeniedError represents a security policy conflict. |
| 468 |
type AccessDeniedError struct { |
| 469 |
path string |
| 470 |
name string |
| 471 |
policies string |
| 472 |
} |
| 473 |
|
| 474 |
func (e *AccessDeniedError) Error() string { |
| 475 |
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) |
| 476 |
} |
| 477 |
|
| 478 |
// IsAccessDenied reports whether err is an AccessDeniedError |
| 479 |
func IsAccessDenied(err error) bool { |
| 480 |
var notFoundErr *AccessDeniedError |
| 481 |
return errors.As(err, ¬FoundErr) |
| 482 |
} |