fix(libreoffice): route LibreOffice through the shared outbound proxy

This commit is contained in:
Julien Neuhart
2026-11-22 10:01:01 +01:00
parent 999038ce14
commit 6e14f3686c
8 changed files with 225 additions and 300 deletions

View File

@@ -441,12 +441,12 @@ func (a *Api) Provision(ctx *gotenberg.Context) error {
startTimeout: flags.MustDuration("libreoffice-start-timeout"),
maxMemory: uint64(max(flags.MustHumanReadableBytes("libreoffice-max-memory"), 0)),
enableMacros: flags.MustBool("libreoffice-enable-macros"),
proxyOptions: outboundProxyOptions{
allowList: flags.MustRegexpSlice("libreoffice-allow-list"),
denyList: flags.MustRegexpSlice("libreoffice-deny-list"),
denyPrivateIPs: flags.MustBool("libreoffice-deny-private-ips"),
denyPublicIPs: flags.MustBool("libreoffice-deny-public-ips"),
enableEnvironmentProxy: flags.MustBool("libreoffice-enable-environment-proxy"),
proxyOptions: gotenberg.OutboundProxyOptions{
AllowList: flags.MustRegexpSlice("libreoffice-allow-list"),
DenyList: flags.MustRegexpSlice("libreoffice-deny-list"),
DenyPrivateIPs: flags.MustBool("libreoffice-deny-private-ips"),
DenyPublicIPs: flags.MustBool("libreoffice-deny-public-ips"),
EnableEnvironmentProxy: flags.MustBool("libreoffice-enable-environment-proxy"),
},
}
@@ -508,7 +508,7 @@ func (a *Api) Validate() error {
err = errors.Join(err, fmt.Errorf("lok binary does not exist at %q; check the LOK_BIN_PATH environment variable: %w", a.args.lokBinPath, statErr))
}
if a.args.proxyOptions.enableEnvironmentProxy {
if a.args.proxyOptions.EnableEnvironmentProxy {
proxyErr := gotenberg.ValidateEnvironmentProxyVariables()
if proxyErr != nil {
err = errors.Join(err, fmt.Errorf("--libreoffice-enable-environment-proxy is set: %w", proxyErr))

View File

@@ -36,7 +36,7 @@ type libreOfficeArguments struct {
// enableMacros lets lok run the documents' macros. Off by default: a
// macro runs code inside the container.
enableMacros bool
proxyOptions outboundProxyOptions
proxyOptions gotenberg.OutboundProxyOptions
}
// libreOfficeProcess runs LibreOffice in a long-running lok process, which
@@ -270,11 +270,11 @@ func (p *libreOfficeProcess) Start(ctx context.Context, logger *slog.Logger) err
return errors.New("LibreOffice is already started")
}
proxy, err := newLibreOfficeProxy(logger, p.arguments.proxyOptions)
proxy := newLibreOfficeProxy(logger, p.arguments.proxyOptions)
err = proxy.Start()
if err != nil {
return fmt.Errorf("create LibreOffice outbound proxy: %w", err)
return fmt.Errorf("start LibreOffice outbound proxy: %w", err)
}
proxy.Start()
userProfileDirPath := p.fs.NewDirPath()

View File

@@ -2,38 +2,20 @@ package api
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/dlclark/regexp2/v2"
"golang.org/x/net/http/httpproxy"
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
)
// outboundProxyOptions configures a [libreOfficeProxy].
type outboundProxyOptions struct {
allowList []*regexp2.Regexp
denyList []*regexp2.Regexp
denyPrivateIPs bool
denyPublicIPs bool
enableEnvironmentProxy bool
}
// libreOfficeProxy is an HTTP/HTTPS forward proxy that LibreOffice routes
// outbound requests through. Every proxied request goes through
// [gotenberg.DecideOutbound] so the same allow/deny lists and IP-class
// filters that protect chromium and webhook fetches also apply to
// LibreOffice's own libcurl-driven fetches.
// libreOfficeProxy is the [gotenberg.OutboundProxy] LibreOffice routes its
// outbound requests through, so the same allow/deny lists and IP-class filters
// that protect Chromium and webhook fetches also apply to LibreOffice's own
// libcurl-driven fetches.
//
// The profile ([profileConfigTmpl]) keeps LibreOffice from loading the
// images and other content an uploaded document links to. What still reaches
@@ -43,24 +25,13 @@ type outboundProxyOptions struct {
// filtering proxy in the path those requests would bypass every Go-side SSRF
// guard, because they originate inside the lok subprocess.
type libreOfficeProxy struct {
listener net.Listener
server *http.Server
client *http.Client
opts outboundProxyOptions
outbound *gotenberg.OutboundProxy
logger *slog.Logger
// upstreamProxy resolves the upstream (corporate) proxy for a destination
// URL from the standard proxy environment variables, or returns a nil URL
// to connect directly. Nil unless the operator opted into proxy-
// environment honoring. See https://github.com/gotenberg/gotenberg/issues/1592.
upstreamProxy func(*url.URL) (*url.URL, error)
// conversionMu guards conversion, the client request lok converts a
// document for: the proxy logs its refusals with it. See [attach].
conversionMu sync.Mutex
conversion *proxyConversion
stopOnce sync.Once
}
// proxyConversion is the client request a conversion runs for.
@@ -69,6 +40,35 @@ type proxyConversion struct {
logger *slog.Logger
}
// newLibreOfficeProxy returns a proxy that applies opts to every request
// LibreOffice sends. Callers must call [libreOfficeProxy.Start] before
// pointing LibreOffice at the proxy and [libreOfficeProxy.Stop] on shutdown.
func newLibreOfficeProxy(logger *slog.Logger, opts gotenberg.OutboundProxyOptions) *libreOfficeProxy {
p := &libreOfficeProxy{
logger: logger.With(slog.String("logger", "libreoffice-proxy")),
}
opts.LogRefusal = p.logRefusal
p.outbound = gotenberg.NewOutboundProxy(opts)
return p
}
// Start binds the proxy to a free local port and serves in the background
// until [libreOfficeProxy.Stop] is called.
func (p *libreOfficeProxy) Start() error {
return p.outbound.Start(p.logger)
}
// Stop shuts the proxy down, closing its tunnels. Subsequent calls are no-ops.
func (p *libreOfficeProxy) Stop(ctx context.Context) error {
return p.outbound.Stop(ctx)
}
// Addr returns the host:port the proxy listens on.
func (p *libreOfficeProxy) Addr() string {
return p.outbound.Addr()
}
// attach makes the proxy log its refusals with ctx and logger, the client
// request's, so that the records carry its correlation ID and trace, until
// the returned function runs. lok converts one document at a time, so the
@@ -102,233 +102,6 @@ func (p *libreOfficeProxy) logRefusal(fallback context.Context, rawURL string, e
gotenberg.LogOutboundRefusal(ctx, logger, "outbound request blocked by the LibreOffice filters", rawURL, err)
}
// newLibreOfficeProxy binds a proxy listener to a free local port and
// applies opts to every proxied request. Callers must call [Start]
// before pointing LibreOffice at the proxy and [Stop] on shutdown.
func newLibreOfficeProxy(logger *slog.Logger, opts outboundProxyOptions) (*libreOfficeProxy, error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return nil, fmt.Errorf("bind LibreOffice proxy listener: %w", err)
}
decideOpts := []gotenberg.DecideOption{
gotenberg.WithDenyPrivateIPs(opts.denyPrivateIPs),
gotenberg.WithDenyPublicIPs(opts.denyPublicIPs),
}
p := &libreOfficeProxy{
listener: listener,
client: gotenberg.NewOutboundHttpClient(0, opts.allowList, opts.denyList, opts.enableEnvironmentProxy, decideOpts...),
opts: opts,
logger: logger.With(slog.String("logger", "libreoffice-proxy")),
}
if opts.enableEnvironmentProxy {
// Honor the standard proxy environment variables, credentials
// included. httpproxy reads the environment now and applies NO_PROXY.
p.upstreamProxy = httpproxy.FromEnvironment().ProxyFunc()
}
p.server = &http.Server{
Handler: p,
ReadHeaderTimeout: 10 * time.Second,
}
return p, nil
}
// Addr returns the host:port the proxy listens on.
func (p *libreOfficeProxy) Addr() string {
return p.listener.Addr().String()
}
// Start serves proxy requests in a background goroutine until [Stop] is
// called.
func (p *libreOfficeProxy) Start() {
go func() {
err := p.server.Serve(p.listener)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
p.logger.ErrorContext(context.Background(), fmt.Sprintf("LibreOffice proxy serve: %s", err))
}
}()
}
// Stop gracefully shuts the proxy down. Subsequent calls are no-ops.
func (p *libreOfficeProxy) Stop(ctx context.Context) error {
var err error
p.stopOnce.Do(func() {
err = p.server.Shutdown(ctx)
})
if err != nil {
return fmt.Errorf("shutdown LibreOffice proxy: %w", err)
}
return nil
}
// ServeHTTP dispatches between CONNECT (HTTPS tunnels) and the absolute
// URL form (HTTP forward).
func (p *libreOfficeProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodConnect {
p.handleConnect(w, r)
return
}
p.handleHttp(w, r)
}
// handleHttp forwards a plain HTTP request whose URL line is absolute
// (RFC 7230 5.3.2) through the outbound HTTP client, which validates
// the destination and pins the dial.
func (p *libreOfficeProxy) handleHttp(w http.ResponseWriter, r *http.Request) {
if r.URL == nil || !r.URL.IsAbs() {
http.Error(w, "proxy: expected absolute URI", http.StatusBadRequest)
return
}
outReq := r.Clone(r.Context())
outReq.RequestURI = ""
removeHopByHopHeaders(outReq.Header)
// gosec G704: outReq.URL is exactly what the proxy is here to filter; the
// http.Client returned by NewOutboundHttpClient validates and pins it.
resp, err := p.client.Do(outReq) //nolint:gosec
if err != nil {
if gotenberg.FilterRule(err) != "" {
p.logRefusal(r.Context(), r.URL.String(), err)
} else {
p.logger.WarnContext(r.Context(), fmt.Sprintf("LibreOffice proxy rejected forward to '%s': %s", gotenberg.RedactURL(r.URL.String()), err))
}
http.Error(w, "proxy: destination rejected", http.StatusForbidden)
return
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
p.logger.DebugContext(r.Context(), fmt.Sprintf("close upstream response body: %s", closeErr))
}
}()
removeHopByHopHeaders(resp.Header)
for key, values := range resp.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.WriteHeader(resp.StatusCode)
_, copyErr := io.Copy(w, resp.Body)
if copyErr != nil {
p.logger.DebugContext(r.Context(), fmt.Sprintf("copy proxied response body: %s", copyErr))
}
}
// handleConnect implements an HTTPS tunnel. It validates the destination
// host through [gotenberg.DecideOutbound] (synthesizing an https URL),
// dials the pinned IPs returned by the decision, and splices bytes
// between client and server.
func (p *libreOfficeProxy) handleConnect(w http.ResponseWriter, r *http.Request) {
host, port, err := net.SplitHostPort(r.Host)
if err != nil {
http.Error(w, "proxy: invalid CONNECT target", http.StatusBadRequest)
return
}
deadline, ok := r.Context().Deadline()
if !ok {
deadline = time.Now().Add(30 * time.Second)
}
rawURL := (&url.URL{Scheme: "https", Host: net.JoinHostPort(host, port)}).String()
decision, err := gotenberg.DecideOutbound(r.Context(), rawURL, p.opts.allowList, p.opts.denyList, deadline,
gotenberg.WithDenyPrivateIPs(p.opts.denyPrivateIPs),
gotenberg.WithDenyPublicIPs(p.opts.denyPublicIPs),
)
if err != nil {
if gotenberg.FilterRule(err) != "" {
p.logRefusal(r.Context(), rawURL, err)
} else {
p.logger.WarnContext(r.Context(), fmt.Sprintf("LibreOffice proxy rejected CONNECT to '%s': %s", rawURL, err))
}
http.Error(w, "proxy: destination rejected", http.StatusForbidden)
return
}
// When the operator routes egress through an authenticated proxy, LibreOffice
// cannot supply the credentials, so the proxy performs the CONNECT (and
// authentication) upstream. The decision above still gated the destination.
var proxyURL *url.URL
if p.upstreamProxy != nil {
proxyURL, err = p.upstreamProxy(&url.URL{Scheme: "https", Host: net.JoinHostPort(host, port)})
if err != nil {
p.logger.WarnContext(r.Context(), fmt.Sprintf("LibreOffice proxy resolve upstream proxy for '%s': %s", rawURL, err))
http.Error(w, "proxy: upstream proxy error", http.StatusBadGateway)
return
}
}
var dest net.Conn
switch {
case proxyURL != nil:
dest, err = gotenberg.DialThroughProxy(r.Context(), proxyURL, r.Host, func(ctx context.Context, network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, 10*time.Second)
})
case len(decision.Pinned) > 0:
dest, err = gotenberg.DialPinned(r.Context(), "tcp", decision.Pinned, port)
default:
// Bypass (allow-list match) or non-http-like scheme: dial directly.
// gosec G704: host:port has cleared DecideOutbound above.
dest, err = net.DialTimeout("tcp", net.JoinHostPort(host, port), 10*time.Second) //nolint:gosec
}
if err != nil {
p.logger.WarnContext(r.Context(), fmt.Sprintf("LibreOffice proxy CONNECT dial to '%s' failed: %s", rawURL, err))
http.Error(w, "proxy: dial failed", http.StatusBadGateway)
return
}
hijacker, ok := w.(http.Hijacker)
if !ok {
_ = dest.Close()
http.Error(w, "proxy: hijack unsupported", http.StatusInternalServerError)
return
}
client, _, err := hijacker.Hijack()
if err != nil {
_ = dest.Close()
p.logger.WarnContext(r.Context(), fmt.Sprintf("LibreOffice proxy hijack failed: %s", err))
return
}
_, writeErr := client.Write([]byte("HTTP/1.1 200 Connection Established\r\n\r\n"))
if writeErr != nil {
_ = client.Close()
_ = dest.Close()
return
}
go pipeAndClose(client, dest)
go pipeAndClose(dest, client)
}
// pipeAndClose copies bytes from src to dst and closes both ends when
// the copy finishes.
func pipeAndClose(dst, src net.Conn) {
defer func() {
_ = dst.Close()
_ = src.Close()
}()
_, _ = io.Copy(dst, src)
}
// hopByHopHeaders is the set of hop-by-hop headers from RFC 7230 6.1
// plus the ones LibreOffice adds when acting as a forward-proxy client.
var hopByHopHeaders = []string{
"Connection",
"Proxy-Connection",
"Keep-Alive",
"Proxy-Authenticate",
"Proxy-Authorization",
"Te",
"Trailer",
"Transfer-Encoding",
"Upgrade",
}
// profileConfigTmpl is the registrymodifications.xcu LibreOffice loads at
// startup, in the lok process. It does three things:
//
@@ -417,14 +190,3 @@ func proxyEnv(env []string, proxyAddr string) []string {
"NO_PROXY=",
)
}
func removeHopByHopHeaders(h http.Header) {
if connection := h.Get("Connection"); connection != "" {
for name := range strings.SplitSeq(connection, ",") {
h.Del(strings.TrimSpace(name))
}
}
for _, name := range hopByHopHeaders {
h.Del(name)
}
}

View File

@@ -18,6 +18,8 @@ import (
"time"
"github.com/dlclark/regexp2/v2"
"github.com/gotenberg/gotenberg/v9/pkg/gotenberg"
)
func compileRegexes(t *testing.T, patterns ...string) []*regexp2.Regexp {
@@ -33,13 +35,13 @@ func compileRegexes(t *testing.T, patterns ...string) []*regexp2.Regexp {
return out
}
func startProxy(t *testing.T, opts outboundProxyOptions) *libreOfficeProxy {
func startProxy(t *testing.T, opts gotenberg.OutboundProxyOptions) *libreOfficeProxy {
t.Helper()
p, err := newLibreOfficeProxy(slog.New(slog.DiscardHandler), opts)
p := newLibreOfficeProxy(slog.New(slog.DiscardHandler), opts)
err := p.Start()
if err != nil {
t.Fatalf("new proxy: %v", err)
t.Fatalf("start proxy: %v", err)
}
p.Start()
t.Cleanup(func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -55,7 +57,7 @@ func TestLibreOfficeProxy_HttpForwardAllowed(t *testing.T) {
}))
defer origin.Close()
p := startProxy(t, outboundProxyOptions{})
p := startProxy(t, gotenberg.OutboundProxyOptions{})
proxyURL, _ := url.Parse("http://" + p.Addr())
client := &http.Client{
@@ -84,8 +86,8 @@ func TestLibreOfficeProxy_HttpForwardDenyListRejects(t *testing.T) {
}))
defer origin.Close()
p := startProxy(t, outboundProxyOptions{
denyList: compileRegexes(t, `.*`),
p := startProxy(t, gotenberg.OutboundProxyOptions{
DenyList: compileRegexes(t, `.*`),
})
proxyURL, _ := url.Parse("http://" + p.Addr())
@@ -113,7 +115,7 @@ func TestLibreOfficeProxy_HttpForwardDenyPrivateIPsRejects(t *testing.T) {
}))
defer origin.Close()
p := startProxy(t, outboundProxyOptions{denyPrivateIPs: true})
p := startProxy(t, gotenberg.OutboundProxyOptions{DenyPrivateIPs: true})
proxyURL, _ := url.Parse("http://" + p.Addr())
client := &http.Client{
@@ -149,7 +151,7 @@ func TestLibreOfficeProxy_ConnectTunnelHappyPath(t *testing.T) {
_, _ = io.Copy(conn, conn)
}()
p := startProxy(t, outboundProxyOptions{})
p := startProxy(t, gotenberg.OutboundProxyOptions{})
conn, err := net.DialTimeout("tcp", p.Addr(), 2*time.Second)
if err != nil {
@@ -206,7 +208,7 @@ func TestLibreOfficeProxy_ConnectDenyListRejects(t *testing.T) {
}
defer listener.Close()
p := startProxy(t, outboundProxyOptions{denyList: compileRegexes(t, `.*`)})
p := startProxy(t, gotenberg.OutboundProxyOptions{DenyList: compileRegexes(t, `.*`)})
conn, err := net.DialTimeout("tcp", p.Addr(), 2*time.Second)
if err != nil {
@@ -237,7 +239,7 @@ func TestLibreOfficeProxy_ConnectDenyPrivateIPsRejects(t *testing.T) {
}
defer listener.Close()
p := startProxy(t, outboundProxyOptions{denyPrivateIPs: true})
p := startProxy(t, gotenberg.OutboundProxyOptions{DenyPrivateIPs: true})
conn, err := net.DialTimeout("tcp", p.Addr(), 2*time.Second)
if err != nil {
@@ -262,12 +264,57 @@ func TestLibreOfficeProxy_ConnectDenyPrivateIPsRejects(t *testing.T) {
}
}
func TestLibreOfficeProxy_StopIsIdempotent(t *testing.T) {
p, err := newLibreOfficeProxy(slog.New(slog.DiscardHandler), outboundProxyOptions{})
// A tunnel only exposes its host and port, so the deny list sees its root URL:
// a rule anchored on "host/" refuses it as it refuses the plain request, and
// the refusal is logged with the conversion.
func TestLibreOfficeProxy_ConnectDenyListMatchesTheRootURL(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("new proxy: %v", err)
t.Fatalf("listen: %v", err)
}
defer listener.Close()
target := listener.Addr().String()
p := startProxy(t, gotenberg.OutboundProxyOptions{
DenyList: compileRegexes(t, `^https://`+regexp2.Escape(target)+`/`),
})
var records []map[string]string
logger := slog.New(recordingHandler{records: &records}).With(slog.String("correlation_id", "foo"))
detach := p.attach(context.Background(), logger)
defer detach()
conn, err := net.DialTimeout("tcp", p.Addr(), 2*time.Second)
if err != nil {
t.Fatalf("dial proxy: %v", err)
}
defer conn.Close()
_, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target)
if err != nil {
t.Fatalf("write CONNECT: %v", err)
}
statusLine, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
t.Fatalf("read response: %v", err)
}
if !strings.Contains(statusLine, "403") {
t.Fatalf("CONNECT status: got %q, want 403", statusLine)
}
if len(records) != 1 || records[0]["correlation_id"] != "foo" || records[0]["rule"] != "deny-list" {
t.Fatalf("records = %v, want one deny-list refusal with the conversion's correlation ID", records)
}
}
func TestLibreOfficeProxy_StopIsIdempotent(t *testing.T) {
p := newLibreOfficeProxy(slog.New(slog.DiscardHandler), gotenberg.OutboundProxyOptions{})
err := p.Start()
if err != nil {
t.Fatalf("start proxy: %v", err)
}
p.Start()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
@@ -406,8 +453,8 @@ func (h recordingHandler) WithGroup(string) slog.Handler { return h }
// A request the filters refuse during a conversion is logged with the
// conversion's logger, which carries the client request's correlation ID.
func TestLibreOfficeProxy_LogsRefusalsWithTheConversion(t *testing.T) {
p := startProxy(t, outboundProxyOptions{
denyList: compileRegexes(t, `^http://styles\.example\.com/`),
p := startProxy(t, gotenberg.OutboundProxyOptions{
DenyList: compileRegexes(t, `^http://styles\.example\.com/`),
})
var records []map[string]string

View File

@@ -1315,6 +1315,52 @@ Feature: /forms/libreoffice/convert
Then the response status code should be 200
Then the helper server should NOT have received a canary request
# LibreOffice follows a redirect itself, through the proxy again, so the
# filters see every hop.
@libreoffice-ssrf
Scenario: POST /forms/libreoffice/convert (Canary style sheet loads through a redirect)
Given I have a static server
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| downloadFrom | [{"url":"{helper}/canary-page/testdata/canary-stylesheet-redirect-html/index.html"}] | field |
Then the response status code should be 200
Then the helper server should have received the following canary request(s):
| style.css |
@libreoffice-ssrf
Scenario: POST /forms/libreoffice/convert (Canary redirect into the deny-list never leaves)
Given I have a static server
Given I have a Gotenberg container with the following environment variable(s):
| LIBREOFFICE_DENY_LIST | ^{helper}/canary/ |
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| downloadFrom | [{"url":"{helper}/canary-page/testdata/canary-stylesheet-redirect-html/index.html"}] | field |
Then the response status code should be 200
Then the helper server should NOT have received a canary request
# Control for the HTTPS canary below: with no filter in the way, LibreOffice
# opens a tunnel for the HTTPS style sheet an HTML document links.
@libreoffice-ssrf
Scenario: POST /forms/libreoffice/convert (HTTPS canary tunnel opens when no filter refuses it)
Given I have a static server
Given I have a default Gotenberg container
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| downloadFrom | [{"url":"{helper}/canary-page/testdata/canary-stylesheet-https-html/index.html"}] | field |
Then the response status code should be 200
Then the helper server should have received the following canary request(s):
| https |
# A tunnel only exposes its host and port: the deny-list sees its root URL,
# so a host rule ending in "/" refuses it.
@libreoffice-ssrf
Scenario: POST /forms/libreoffice/convert (HTTPS canary in the deny-list never leaves)
Given I have a static server
Given I have a Gotenberg container with the following environment variable(s):
| LIBREOFFICE_DENY_LIST | ^https://host\.docker\.internal:[0-9]+/ |
When I make a "POST" request to Gotenberg at the "/forms/libreoffice/convert" endpoint with the following form data and header(s):
| downloadFrom | [{"url":"{helper}/canary-page/testdata/canary-stylesheet-https-html/index.html"}] | field |
Then the response status code should be 200
Then the helper server should NOT have received a canary request
# The helper server resolves to a non-public address. An allow-list match
# would bypass the check: none here.
@libreoffice-ssrf

View File

@@ -58,6 +58,12 @@ type server struct {
// refusal holds only if the list stays empty.
canaries []string
// httpsPort is where the HTTPS canary listens, set by start. It records
// every connection as a request to /canary/https: a converter only gets
// one through a tunnel the filters let open, and the TLS handshake that
// follows fails, as the converter does not trust the helper.
httpsPort int
shutdown context.CancelFunc
done chan struct{}
}
@@ -231,7 +237,15 @@ func newServer(ctx context.Context, workdir string) (*server, error) {
}
canary := fmt.Sprintf("http://%s/canary", c.Request().Host)
host, _, err := net.SplitHostPort(c.Request().Host)
if err != nil {
return c.String(http.StatusBadRequest, fmt.Sprintf("split host %q: %s", c.Request().Host, err))
}
s.mu.Lock()
httpsCanary := fmt.Sprintf("https://%s/canary", net.JoinHostPort(host, fmt.Sprint(s.httpsPort)))
s.mu.Unlock()
b = []byte(strings.ReplaceAll(string(b), "{canary}", canary))
b = []byte(strings.ReplaceAll(string(b), "{canary-https}", httpsCanary))
contentType := mime.TypeByExtension(filepath.Ext(path))
if contentType == "" {
@@ -367,6 +381,16 @@ func (s *server) start(ctx context.Context) (int, error) {
port := ln.Addr().(*net.TCPAddr).Port
httpsLn, err := listenOutsideEphemeralRange()
if err != nil {
_ = ln.Close()
return 0, err
}
s.mu.Lock()
s.httpsPort = httpsLn.Addr().(*net.TCPAddr).Port
s.mu.Unlock()
startConfig := echo.StartConfig{
Listener: ln,
HideBanner: true,
@@ -377,6 +401,8 @@ func (s *server) start(ctx context.Context) (int, error) {
s.shutdown = cancel
s.done = make(chan struct{})
go s.serveHTTPSCanary(serveCtx, httpsLn)
go func() {
defer close(s.done)
@@ -389,6 +415,28 @@ func (s *server) start(ctx context.Context) (int, error) {
return port, nil
}
// serveHTTPSCanary records each connection ln accepts as a canary request,
// then closes it, until ctx ends.
func (s *server) serveHTTPSCanary(ctx context.Context, ln net.Listener) {
go func() {
<-ctx.Done()
_ = ln.Close()
}()
for {
conn, err := ln.Accept()
if err != nil {
return
}
s.mu.Lock()
s.canaries = append(s.canaries, "CONNECT /canary/https")
s.mu.Unlock()
_ = conn.Close()
}
}
func (s *server) stop(ctx context.Context) error {
if s.shutdown == nil {
return nil

View File

@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Canary</title>
<link rel="stylesheet" href="{canary-https}/style.css" />
</head>
<body>
<p>LibreOffice opens a tunnel for the HTTPS style sheet this page links.</p>
</body>
</html>

View File

@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Canary</title>
<link rel="stylesheet" href="{canary}-redirect/style.css" />
</head>
<body>
<p>LibreOffice follows the redirect of the style sheet this page links.</p>
</body>
</html>