- Reject control chars and backslashes in redirect targets - Use proxy-added X-Forwarded-For entry, cap limiter keys - Block private/loopback/link-local addresses on image fetch - HSTS over HTTPS, generic error on custom CSS - x/crypto 0.59.0, pin golang:1.27.4-alpine3.24 and alpine:3.24.4 - Compose: cap_drop ALL, no-new-privileges, read_only, limits, labels - Add SECURITY.md, CHANGELOG.md, TODO.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
180 lines
4.8 KiB
Go
180 lines
4.8 KiB
Go
// Package imgcache downloads and stores artwork locally so pages never
|
|
// hotlink third-party image servers.
|
|
package imgcache
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
)
|
|
|
|
const MaxBytes = 15 << 20
|
|
|
|
var ErrNotImage = errors.New("that file isn't a supported image (JPEG, PNG, WebP, GIF or AVIF)")
|
|
|
|
type Cache struct {
|
|
dir string
|
|
client *http.Client
|
|
ua string
|
|
}
|
|
|
|
func New(dataDir, userAgent string) (*Cache, error) {
|
|
dir := filepath.Join(dataDir, "images")
|
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
|
return nil, err
|
|
}
|
|
// Image URLs come from the admin UI and from metadata providers, so the
|
|
// server only fetches from public addresses (no SSRF into the LAN).
|
|
dialer := &net.Dialer{Timeout: 10 * time.Second, Control: publicOnly}
|
|
transport := &http.Transport{
|
|
Proxy: http.ProxyFromEnvironment,
|
|
DialContext: dialer.DialContext,
|
|
TLSHandshakeTimeout: 10 * time.Second,
|
|
ForceAttemptHTTP2: true,
|
|
}
|
|
return &Cache{dir: dir, ua: userAgent, client: &http.Client{Timeout: 30 * time.Second, Transport: transport}}, nil
|
|
}
|
|
|
|
// errPrivateAddr is returned when an image URL points at a private address.
|
|
var errPrivateAddr = errors.New("image URL points at a private or local address")
|
|
|
|
// publicOnly refuses connections to loopback, private, link-local,
|
|
// multicast and unspecified addresses. It runs after DNS resolution, so a
|
|
// public name that resolves to a LAN address is refused too.
|
|
func publicOnly(network, address string, _ syscall.RawConn) error {
|
|
host, _, err := net.SplitHostPort(address)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ip, err := netip.ParseAddr(host)
|
|
if err != nil {
|
|
return errPrivateAddr
|
|
}
|
|
ip = ip.Unmap()
|
|
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() ||
|
|
cgnat.Contains(ip) {
|
|
return errPrivateAddr
|
|
}
|
|
return nil
|
|
}
|
|
|
|
var cgnat = netip.MustParsePrefix("100.64.0.0/10")
|
|
|
|
func (c *Cache) Dir() string { return c.dir }
|
|
|
|
var nameRe = regexp.MustCompile(`^[0-9a-f]{40}\.(jpg|png|webp|gif|avif)$`)
|
|
|
|
// ValidName reports whether name looks like a file this cache created.
|
|
func ValidName(name string) bool { return nameRe.MatchString(name) }
|
|
|
|
// Fetch downloads an image URL and returns the cached file name.
|
|
func (c *Cache) Fetch(ctx context.Context, url string) (string, error) {
|
|
if !strings.HasPrefix(url, "https://") && !strings.HasPrefix(url, "http://") {
|
|
return "", fmt.Errorf("image URL must start with http:// or https://")
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.Header.Set("User-Agent", c.ua)
|
|
req.Header.Set("Accept", "image/avif,image/webp,image/png,image/jpeg,image/*;q=0.8")
|
|
resp, err := c.client.Do(req)
|
|
if err != nil {
|
|
return "", fmt.Errorf("downloading image: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode == http.StatusNotFound {
|
|
return "", fmt.Errorf("no artwork found at that address")
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("downloading image: server returned %d", resp.StatusCode)
|
|
}
|
|
return c.Save(resp.Body)
|
|
}
|
|
|
|
// Save stores image data from r and returns the cached file name. The name
|
|
// is derived from the content, so identical images are stored once.
|
|
func (c *Cache) Save(r io.Reader) (string, error) {
|
|
data, err := io.ReadAll(io.LimitReader(r, MaxBytes+1))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(data) > MaxBytes {
|
|
return "", fmt.Errorf("image is larger than %d MB", MaxBytes>>20)
|
|
}
|
|
ext := sniff(data)
|
|
if ext == "" {
|
|
return "", ErrNotImage
|
|
}
|
|
sum := sha256.Sum256(data)
|
|
name := hex.EncodeToString(sum[:20]) + "." + ext
|
|
path := filepath.Join(c.dir, name)
|
|
if _, err := os.Stat(path); err == nil {
|
|
return name, nil
|
|
}
|
|
tmp, err := os.CreateTemp(c.dir, ".upload-*")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if _, err := tmp.Write(data); err != nil {
|
|
tmp.Close()
|
|
os.Remove(tmp.Name())
|
|
return "", err
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
os.Remove(tmp.Name())
|
|
return "", err
|
|
}
|
|
if err := os.Chmod(tmp.Name(), 0o644); err != nil {
|
|
os.Remove(tmp.Name())
|
|
return "", err
|
|
}
|
|
if err := os.Rename(tmp.Name(), path); err != nil {
|
|
os.Remove(tmp.Name())
|
|
return "", err
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
// Remove deletes a cached image. Missing files are not an error.
|
|
func (c *Cache) Remove(name string) error {
|
|
if !ValidName(name) {
|
|
return nil
|
|
}
|
|
err := os.Remove(filepath.Join(c.dir, name))
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
|
|
func sniff(b []byte) string {
|
|
switch http.DetectContentType(b) {
|
|
case "image/jpeg":
|
|
return "jpg"
|
|
case "image/png":
|
|
return "png"
|
|
case "image/webp":
|
|
return "webp"
|
|
case "image/gif":
|
|
return "gif"
|
|
}
|
|
if len(b) > 12 && bytes.Equal(b[4:8], []byte("ftyp")) && (bytes.Equal(b[8:12], []byte("avif")) || bytes.Equal(b[8:12], []byte("avis"))) {
|
|
return "avif"
|
|
}
|
|
return ""
|
|
}
|