-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlitebastion.go
More file actions
258 lines (241 loc) · 7.54 KB
/
Copy pathlitebastion.go
File metadata and controls
258 lines (241 loc) · 7.54 KB
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
// Command litebastion runs a reverse proxy service that allows un-addressable
// applications (for example those running behind a firewall or a NAT, or where
// the operator doesn't wish to take the DoS risk of being reachable from the
// Internet) to accept HTTP requests.
//
// Backends are identified by an Ed25519 public key, they authenticate with a
// self-signed TLS 1.3 certificate, and are reachable at a sub-path prefixed by
// the key hash.
//
// Read more at https://c2sp.org/https-bastion.
package main
import (
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"flag"
"fmt"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"filippo.io/torchwood/bastion"
"filippo.io/torchwood/internal/slogconsole"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/net/http2"
"golang.org/x/sync/errgroup"
)
var listenAddr = flag.String("listen", "localhost:8443", "host and port to listen at")
var listenHTTP = flag.String("listen-http", "", "host:port or localhost port to listen for HTTP requests")
var tlsCertFile = flag.String("tls-cert", "", "path to TLS certificate; disables ACME")
var tlsKeyFile = flag.String("tls-key", "", "path to TLS private key; disables ACME")
var autocertCache = flag.String("cache", "", "directory to cache ACME certificates at")
var autocertHost = flag.String("host", "", "host to obtain ACME certificate for")
var autocertEmail = flag.String("email", "", "")
var allowedBackendsFile = flag.String("backends", "", "file of accepted key hashes, one per line, reloaded on SIGHUP")
var homeRedirect = flag.String("home-redirect", "", "redirect / to this URL")
var obscurityFlag = flag.Bool("obscurity", false, "enable obscurity mode (disable / and /logz endpoints)")
var logLevel = flag.String("log-level", "info", "log level (debug, info, warn, error)")
type keyHash [sha256.Size]byte
func main() {
flag.Parse()
var level slog.Level
if err := level.UnmarshalText([]byte(*logLevel)); err != nil {
logFatal("unknown log level, must be one of 'debug', 'info', 'warn', or 'error'")
}
console := slogconsole.New(nil)
console.SetFilter(slogconsole.IPAddressFilter)
h := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: level})
slog.SetDefault(slog.New(slogconsole.MultiHandler(h, console)))
http2.VerboseLogs = true // will go to DEBUG due to SetLogLoggerLevel
slog.SetLogLoggerLevel(slog.LevelDebug)
var reloadCert func() error
var getCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error)
switch {
case *tlsKeyFile != "" && *tlsCertFile != "":
var cert atomic.Pointer[tls.Certificate]
reloadCert = func() error {
c, err := tls.LoadX509KeyPair(*tlsCertFile, *tlsKeyFile)
if err != nil {
return err
}
cert.Store(&c)
return nil
}
if err := reloadCert(); err != nil {
logFatal("can't load certificates", "err", err)
}
getCertificate = func(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
return cert.Load(), nil
}
case *autocertCache != "" && *autocertHost != "" && *autocertEmail != "":
m := &autocert.Manager{
Cache: autocert.DirCache(*autocertCache),
Prompt: autocert.AcceptTOS,
Email: *autocertEmail,
HostPolicy: autocert.HostWhitelist(*autocertHost),
}
getCertificate = m.GetCertificate
reloadCert = func() error { return nil }
default:
logFatal("-cache, -host, and -email or -tls-key and -tls-cert are required")
}
if *allowedBackendsFile == "" {
logFatal("-backends is missing")
}
var allowedBackendsMu sync.RWMutex
var allowedBackends map[keyHash]bool
reloadBackends := func() error {
newBackends := make(map[keyHash]bool)
backendsList, err := os.ReadFile(*allowedBackendsFile)
if err != nil {
return err
}
bs := strings.TrimSpace(string(backendsList))
for _, line := range strings.Split(bs, "\n") {
if line == "" {
continue
}
l, err := hex.DecodeString(line)
if err != nil {
return fmt.Errorf("invalid backend: %q", line)
}
if len(l) != sha256.Size {
return fmt.Errorf("invalid backend: %q", line)
}
h := keyHash(l)
newBackends[h] = true
}
allowedBackendsMu.Lock()
defer allowedBackendsMu.Unlock()
allowedBackends = newBackends
return nil
}
if err := reloadBackends(); err != nil {
logFatal("failed to load backends", "err", err)
}
slog.Info("loaded backends", "count", len(allowedBackends))
b, err := bastion.New(&bastion.Config{
AllowedBackend: func(keyHash [sha256.Size]byte) bool {
allowedBackendsMu.RLock()
defer allowedBackendsMu.RUnlock()
return allowedBackends[keyHash]
},
GetCertificate: getCertificate,
})
if err != nil {
logFatal("failed to create bastion", "err", err)
}
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP)
go func() {
for range c {
if err := reloadCert(); err != nil {
slog.Error("failed to reload certificate", "err", err)
}
if err := reloadBackends(); err != nil {
slog.Error("failed to reload backends", "err", err)
} else {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
b.FlushBackendConnections(ctx)
cancel()
slog.Info("reloaded backends")
}
}
}()
mux := http.NewServeMux()
mux.Handle("/", b)
if !*obscurityFlag {
mux.Handle("/logz", console)
}
if *homeRedirect != "" {
mux.HandleFunc("/{$}", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, *homeRedirect, http.StatusFound)
})
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
serveGroup, ctx := errgroup.WithContext(ctx)
if *listenHTTP != "" {
if _, _, err := net.SplitHostPort(*listenHTTP); err != nil {
*listenHTTP = net.JoinHostPort("localhost", *listenHTTP)
}
hs := &http.Server{
Addr: *listenHTTP,
Handler: http.MaxBytesHandler(mux, 10*1024),
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
l, err := net.Listen("tcp", *listenAddr)
if err != nil {
logFatal("failed to listen for backends", "err", err)
}
serveGroup.Go(func() error {
slog.Info("listening for HTTP", "addr", hs.Addr)
return hs.ListenAndServe()
})
serveGroup.Go(func() error {
slog.Info("listening for backends", "addr", *listenAddr)
for {
c, err := l.Accept()
if err != nil {
return err
}
go b.HandleBackendConnection(c)
}
})
serveGroup.Go(func() error {
<-ctx.Done()
slog.Info("shutting down bastion listener")
l.Close()
slog.Info("shutting down HTTP server")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
hs.Shutdown(ctx)
return nil
})
serveGroup.Wait()
slog.Info("exiting", "err", context.Cause(ctx))
return
}
hs := &http.Server{
Addr: *listenAddr,
Handler: http.MaxBytesHandler(mux, 10*1024),
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
TLSConfig: &tls.Config{
NextProtos: []string{acme.ALPNProto},
GetCertificate: getCertificate,
},
}
if err := b.ConfigureServer(hs); err != nil {
logFatal("failed to configure bastion", "err", err)
}
if err := http2.ConfigureServer(hs, nil); err != nil {
logFatal("failed to configure HTTP/2", "err", err)
}
slog.Info("listening", "addr", *listenAddr)
e := make(chan error, 1)
go func() { e <- hs.ListenAndServeTLS("", "") }()
select {
case <-ctx.Done():
slog.Info("shutting down on interrupt")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
hs.Shutdown(ctx)
case err := <-e:
slog.Error("server error", "err", err)
}
}
func logFatal(msg string, args ...interface{}) {
slog.Error(msg, args...)
os.Exit(1)
}