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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
|
package main
import (
"context"
"crypto/tls"
"database/sql"
"errors"
"flag"
"fmt"
"log"
"log/slog"
"net"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/acme/autocert"
_ "modernc.org/sqlite"
"within.website/x/internal"
"within.website/x/xess"
)
var (
useAutocert = flag.Bool("use-autocert", false, "if true, provision certs with autocert")
autocertCacheDir = flag.String("autocert-cache-dir", "", "location to store cached certificates and ACME account details")
autocertDomainNames = flag.String("autocert-domain-names", "", "comma-separated list of TLS hostnames to allow")
autocertEmail = flag.String("autocert-email", "", "ACME account contact email")
bind = flag.String("bind", ":3004", "port to listen on")
certDir = flag.String("cert-dir", "/xe/pki", "where to read mounted certificates from")
certFname = flag.String("cert-fname", "tls.crt", "certificate filename")
fpDatabase = flag.String("fp-database", "", "location of fingerprint database")
keyFname = flag.String("key-fname", "tls.key", "key filename")
httpBind = flag.String("http-bind", "", "if set, plain HTTP port to listen on to forward requests to https")
proxyTo = flag.String("proxy-to", "http://localhost:5000", "where to reverse proxy to")
)
func main() {
internal.HandleStartup()
slog.Info("starting",
"bind", *bind,
"cert-dir", *certDir,
"cert-fname", *certFname,
"fp-database", *fpDatabase,
"key-fname", *keyFname,
"proxy-to", *proxyTo,
"use-autocert", *useAutocert,
"autocert-cache-dir", *autocertCacheDir,
"autocert-domain-names", *autocertDomainNames,
"autocert-email", *autocertEmail,
)
var tc *tls.Config
switch *useAutocert {
case true:
slog.Info("using autocert")
var fail bool
if *autocertCacheDir == "" {
fmt.Fprintln(os.Stderr, "cannot use --autocert without --autocert-cache-dir")
fail = true
}
if *autocertDomainNames == "" {
fmt.Fprintln(os.Stderr, "cannot use --autocert without --autocert-domain-names")
fail = true
}
if *autocertEmail == "" {
fmt.Fprintln(os.Stderr, "cannot use --autocert without --autocert-email")
fail = true
}
if *httpBind != ":80" {
fmt.Fprintln(os.Stderr, "cannot use --autocert without --http-bind=:80")
fail = true
}
if fail {
log.Fatal("autocert configuration errors")
}
m := &autocert.Manager{
Cache: autocert.DirCache(*autocertCacheDir),
Prompt: autocert.AcceptTOS,
Email: *autocertEmail,
HostPolicy: autocert.HostWhitelist(strings.Split(*autocertDomainNames, ",")...),
}
go func() {
slog.Info("listening for plain HTTP", "http-bind", *httpBind)
log.Fatal(http.ListenAndServe(*httpBind, m.HTTPHandler(http.HandlerFunc(xess.NotFound))))
}()
tc = m.TLSConfig()
case false:
cert := filepath.Join(*certDir, *certFname)
key := filepath.Join(*certDir, *keyFname)
kpr, err := NewKeypairReloader(cert, key)
if err != nil {
log.Fatal(err)
}
tc = &tls.Config{GetCertificate: kpr.GetCertificate}
}
u, err := url.Parse(*proxyTo)
if err != nil {
log.Fatal(err)
}
var db *sql.DB
if fpDatabase != nil {
var err error
db, err = sql.Open("sqlite", *fpDatabase)
if err != nil {
log.Fatal(err)
}
if err := db.Ping(); err != nil {
log.Fatal(err)
}
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS fingerprints
( "application" TEXT
, "user_agent_string" TEXT
, "notes" TEXT
, "ja4_fingerprint" TEXT
, ip_address TEXT
)`); err != nil {
log.Fatal(err)
}
}
h := httputil.NewSingleHostReverseProxy(u)
oldDirector := h.Director
if u.Scheme == "unix" {
h = &httputil.ReverseProxy{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", strings.TrimPrefix(*proxyTo, "unix://"))
},
},
}
}
h.Director = func(req *http.Request) {
oldDirector(req)
host, _, _ := net.SplitHostPort(req.RemoteAddr)
if host != "" {
req.Header.Set("X-Real-Ip", host)
}
fp := GetTLSFingerprint(req)
if fp != nil {
if fp.JA3N() != nil {
req.Header.Set("X-TLS-Fingerprint-JA3N", fp.JA3N().String())
}
if fp.JA4() != nil {
req.Header.Set("X-TLS-Fingerprint-JA4", fp.JA4().String())
}
}
// if tcpFP := GetTCPFingerprint(req); tcpFP != nil {
// req.Header.Set("X-TCP-Fingerprint-JA4T", tcpFP.String())
// }
if ja4 := req.Header.Get("X-TLS-Fingerprint-JA4"); db != nil && ja4 != "" {
var application, userAgent, notes sql.NullString
if err := db.QueryRowContext(req.Context(), "SELECT application, user_agent_string, notes FROM fingerprints WHERE ja4_fingerprint = ?", ja4).Scan(&application, &userAgent, ¬es); err == nil {
slog.Debug("found a hit", "application", application, "userAgent", userAgent, "notes", notes)
if application.Valid {
req.Header.Set("Xe-X-Relayd-Ja4-Application", application.String)
}
if userAgent.Valid {
req.Header.Set("Xe-X-Relayd-Ja4-UserAgent", userAgent.String)
}
if notes.Valid {
req.Header.Set("Xe-X-Relayd-Ja4-Notes", notes.String)
}
} else if errors.Is(err, sql.ErrNoRows) {
userAgent := req.UserAgent()
notes := fmt.Sprintf("Observed via relayd on host %s at %s", req.Host, time.Now().Format(time.RFC3339))
ip, _, _ := net.SplitHostPort(req.RemoteAddr)
if _, err := db.ExecContext(req.Context(), "INSERT INTO fingerprints(user_agent_string, notes, ja4_fingerprint, ip_address) VALUES (?, ?, ?, ?)", userAgent, notes, ja4, ip); err != nil {
slog.Error("can't insert fingerprint into database", "err", err)
}
req.Header.Set("Xe-X-Relayd-New-Client", "true")
} else {
slog.Debug("can't read from database", "err", err)
}
}
req.Header.Set("X-Forwarded-Host", req.URL.Host)
req.Header.Set("X-Forwarded-Proto", "https")
req.Header.Set("X-Forwarded-Scheme", "https")
req.Header.Set("X-Request-Id", uuid.NewString())
req.Header.Set("X-Scheme", "https")
req.Header.Set("X-HTTP-Version", req.Proto)
}
srv := &http.Server{
Addr: *bind,
Handler: h,
TLSConfig: tc,
}
applyTLSFingerprinter(srv)
log.Fatal(srv.ListenAndServeTLS("", ""))
}
type keypairReloader struct {
certMu sync.RWMutex
cert *tls.Certificate
certPath string
keyPath string
modTime time.Time
}
func NewKeypairReloader(certPath, keyPath string) (*keypairReloader, error) {
result := &keypairReloader{
certPath: certPath,
keyPath: keyPath,
|