-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
238 lines (197 loc) · 5.73 KB
/
handler.go
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
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"strings"
"sync/atomic"
_ "unsafe"
"golang.org/x/net/http2"
"tailscale.com/control/controlclient"
"tailscale.com/control/controlhttp"
"tailscale.com/net/dnscache"
"tailscale.com/net/netmon"
"tailscale.com/net/tsdial"
"tailscale.com/tailcfg"
"tailscale.com/types/key"
"tailscale.com/types/logger"
)
type handler struct {
upstreamURL string
state *state
dialer *tsdial.Dialer
}
func newHandler(upstreamURL string, state *state) (*handler, error) {
h := &handler{
upstreamURL: upstreamURL,
state: state,
}
mon, err := netmon.New(log.New(os.Stderr, "netmon: ", log.LstdFlags|log.Lmsgprefix).Printf)
if err != nil {
return nil, err
}
h.dialer = tsdial.NewDialer(mon)
return h, nil
}
func (h *handler) serveKey(rw http.ResponseWriter, req *http.Request) {
if req.URL.Query().Get("v") == "" {
rw.Write([]byte(h.state.legacyKey.Public().UntypedHexString()))
return
}
resp := tailcfg.OverTLSPublicKeyResponse{
LegacyPublicKey: h.state.legacyKey.Public(),
PublicKey: h.state.noiseKey.Public(),
}
if err := json.NewEncoder(rw).Encode(resp); err != nil {
http.Error(rw, "failed to marshal keys", http.StatusInternalServerError)
return
}
}
func (h *handler) serveNoise(rw http.ResponseWriter, req *http.Request) {
log.Println("got noise connection from", req.RemoteAddr)
logHeaders(log.Default(), req.Header)
connClient, err := controlhttp.AcceptHTTP(req.Context(), rw, req, h.state.noiseKey, nil)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
defer connClient.Close()
peerPub := connClient.Peer()
l := log.New(os.Stderr, peerPub.ShortString()+": ", log.LstdFlags|log.Lmsgprefix)
l.Println("accepted noise connection")
priv, err := h.state.lookupMitmKey(peerPub)
if err != nil {
l.Println("failed to lookup MITM key:", err)
return
}
l.Println("got MITM key:", priv.Public().ShortString())
upstreamClient, err := h.getNoiseClient(req.Context(), priv, l.Printf)
if err != nil {
l.Println("failed to create upstream noise client:", err)
return
}
defer upstreamClient.Close()
l.Println("connected to upstream")
srv := &http2.Server{}
srv.ServeConn(connClient, &http2.ServeConnOpts{
Context: req.Context(),
Handler: &noiseHandler{
nc: upstreamClient,
peer: peerPub,
},
})
l.Println("finished serving noise connection")
}
func (h *handler) getNoiseClient(ctx context.Context, priv key.MachinePrivate, logf logger.Logf) (*controlclient.NoiseClient, error) {
keysResp, err := loadServerPubKeys(ctx, http.DefaultClient, h.upstreamURL)
if err != nil {
return nil, err
}
return controlclient.NewNoiseClient(controlclient.NoiseOpts{
PrivKey: priv,
ServerPubKey: keysResp.PublicKey,
ServerURL: h.upstreamURL,
Dialer: h.dialer,
DNSCache: &dnscache.Resolver{
Forward: net.DefaultResolver,
LookupIPFallback: nil, // disable DNS fallback via derps bootstrap
Logf: logf,
},
Logf: logf,
})
}
//go:linkname loadServerPubKeys tailscale.com/control/controlclient.loadServerPubKeys
func loadServerPubKeys(context.Context, *http.Client, string) (*tailcfg.OverTLSPublicKeyResponse, error)
type noiseHandler struct {
nc *controlclient.NoiseClient
peer key.MachinePublic
reqId atomic.Int32
}
func (h *noiseHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
id := h.reqId.Add(1)
l := log.New(os.Stderr, fmt.Sprintf("%s req-%d: ", h.peer.ShortString(), id), log.LstdFlags|log.Lmsgprefix)
l.Printf("%s %s", req.Method, req.URL.String())
logHeaders(l, req.Header)
reqBody, err := io.ReadAll(req.Body)
if err != nil {
l.Println("failed to read request body:", err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if req.URL.Path != "/machine/map" {
// map polls will be logged in processMapPoll
logBody(reqBody, "req body", l.Printf)
}
req.URL.Scheme = "https"
req.URL.Host = "unused"
req.Host = "unused"
req.RequestURI = ""
req.Body = io.NopCloser(bytes.NewBuffer(reqBody))
resp, err := h.nc.Do(req)
if err != nil {
l.Println("failed to proxy request:", err)
http.Error(rw, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
l.Println("upstream response:", resp.Status)
logHeaders(l, resp.Header)
for k, v := range resp.Header {
rw.Header()[k] = v
}
rw.WriteHeader(resp.StatusCode)
if req.URL.Path == "/machine/map" {
l := log.New(os.Stderr, fmt.Sprintf("%s mappoll-%d: ", h.peer.ShortString(), id), log.LstdFlags|log.Lmsgprefix)
processMapPoll(reqBody, resp.Body, rw, l.Printf)
return
}
// there is no streaming endpoints besides /machine/map, just read the whole body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
l.Println("failed to read response body:", err)
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
logBody(respBody, "resp body", l.Printf)
rw.Write(respBody)
}
var (
dumpHeaders = flag.Bool("dump-headers", true, "dump request and response headers")
dumpBodies = flag.Bool("dump-bodies", true, "dump request and response bodies")
)
func logHeaders(l *log.Logger, hdr http.Header) {
if !*dumpHeaders {
return
}
for k, v := range hdr {
l.Printf(" %s: %v", k, strings.Join(v, ", "))
}
}
func logBody(body []byte, pfx string, logf logger.Logf) {
if !*dumpBodies {
return
}
logVal(body, pfx, logf)
}
func logVal(val []byte, pfx string, logf logger.Logf) {
if len(val) == 0 {
logf("%s: <empty>", pfx)
return
}
if val[0] == '{' {
// attempt to pretty-print JSON
pretty := bytes.NewBuffer(make([]byte, 0, len(val)+256))
if err := json.Indent(pretty, val, "", " "); err == nil {
logf("%s: %s", pfx, pretty)
return
}
}
logf("%s: %q", pfx, val)
}