/
router.go
415 lines (349 loc) · 14.2 KB
/
router.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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
package router
import (
"bytes"
"context"
"crypto/sha256"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"github.com/Rocket-Rescue-Node/credentials"
"github.com/Rocket-Rescue-Node/credentials/pb"
"github.com/Rocket-Rescue-Node/rescue-proxy/consensuslayer"
"github.com/Rocket-Rescue-Node/rescue-proxy/executionlayer"
"github.com/Rocket-Rescue-Node/rescue-proxy/metrics"
gbp "github.com/Rocket-Rescue-Node/guarded-beacon-proxy"
"github.com/ethereum/go-ethereum/common"
rptypes "github.com/rocket-pool/rocketpool-go/types"
"go.uber.org/zap"
"google.golang.org/grpc/metadata"
)
type ProxyRouter struct {
Addr string
BeaconURL *url.URL
GRPCAddr string
GRPCBeaconURL string
TLSCertFile string
TLSKeyFile string
Logger *zap.Logger
EL executionlayer.ExecutionLayer
CL consensuslayer.ConsensusLayer
CredentialSecret string
EnableSoloValidators bool
gbp *gbp.GuardedBeaconProxy
m *metrics.MetricsRegistry
gm *metrics.MetricsRegistry
auth *auth
}
// Used to avoid collisions in context.WithValue()
// see: https://pkg.go.dev/context#WithValue
type prContextKey string
const prContextOperatorTypeKey = prContextKey("operator_type")
const prContextNodeAddrKey = prContextKey("node")
func (pr *ProxyRouter) logCredentialSharing(operatorType credentials.OperatorType,
rpInfo *executionlayer.RPInfo,
validatorInfo *consensuslayer.ValidatorInfo,
credNodeAddr common.Address) {
var chainNodeAddress common.Address
if rpInfo == nil {
if operatorType == pb.OperatorType_OT_ROCKETPOOL {
// The credential was issued to a rp node, but the validator appears to be solo.
pr.m.Counter("credential_sharing_rp_to_solo").Inc()
return
}
// Solo validators on rv will not be looked up
if validatorInfo == nil {
return
}
// On pbp we will, so we can check
chainNodeAddress = validatorInfo.WithdrawalAddress
} else {
if operatorType == pb.OperatorType_OT_SOLO {
// The credential was issued to a solo validator, but appears to be used on a rp validator.
pr.m.Counter("credential_sharing_solo_to_rp").Inc()
return
}
chainNodeAddress = rpInfo.NodeAddress
}
if bytes.Equal(credNodeAddr[:], chainNodeAddress[:]) {
return
}
// Someone got a credential with one node and used it on a different node.
switch operatorType {
case pb.OperatorType_OT_SOLO:
pr.m.Counter("credential_sharing_solo_to_solo").Inc()
case pb.OperatorType_OT_ROCKETPOOL:
pr.m.Counter("credential_sharing_rp_to_rp").Inc()
}
}
func (pr *ProxyRouter) readContext(ctx context.Context) ([]byte, credentials.OperatorType, error) {
// Grab the authorized node address, only used for metrics/logging
authedNode, ok := ctx.Value(prContextNodeAddrKey).([]byte)
if !ok {
return nil, 0, fmt.Errorf("unable to retrieve node address")
}
// Grab the credential type, only used for metrics/logging
operatorType, ok := ctx.Value(prContextOperatorTypeKey).(credentials.OperatorType)
if !ok {
return nil, 0, fmt.Errorf("unable to retrieve operator_type")
}
return authedNode, operatorType, nil
}
func (pr *ProxyRouter) prepareBeaconProposerGuard(proposers gbp.PrepareBeaconProposerRequest, ctx context.Context) (gbp.AuthenticationStatus, error) {
pr.m.Counter("prepare_beacon_proposer").Inc()
// Create a slice of the indices
indices := make([]string, 0, len(proposers))
// Validate each proposer's fee recipient
for _, proposer := range proposers {
indices = append(indices, proposer.ValidatorIndex)
}
// Get the index->info map
validatorMap, err := pr.CL.GetValidatorInfo(indices)
if err != nil {
pr.Logger.Error("Error while querying CL for validator info", zap.Error(err))
return gbp.InternalError, nil
}
authedNode, operatorType, err := pr.readContext(ctx)
if err != nil {
pr.Logger.Warn("Error reading cached data from request context", zap.Error(err))
return gbp.InternalError, nil
}
// Iterate the results and check the fee recipients against our expected values
// Note: we iterate the map from the HTTP request to ensure every key is present in the
// response from the consensuslayer abstraction
for _, proposer := range proposers {
validatorInfo, found := validatorMap[proposer.ValidatorIndex]
if !found {
pr.Logger.Warn("Pubkey for index not found in response from cl.",
zap.String("requested index", proposer.ValidatorIndex))
return gbp.BadRequest, fmt.Errorf("unknown validator index %s", proposer.ValidatorIndex)
}
pubkey := validatorInfo.Pubkey
// Next we need to get the expected fee recipient for the pubkey
rpInfo, err := pr.EL.GetRPInfo(pubkey)
if err != nil {
pr.Logger.Panic("error querying cache", zap.Error(err))
return gbp.InternalError, fmt.Errorf("error with cache, please report it to Rescue Node maintainers")
}
pr.logCredentialSharing(operatorType, rpInfo, validatorInfo, common.BytesToAddress(authedNode))
if rpInfo == nil {
// Solo validators may only use their withdrawal credential in prepare_beacon_proposer
if !validatorInfo.Is0x01 ||
!strings.EqualFold(validatorInfo.WithdrawalAddress.String(), proposer.FeeRecipient) {
pr.m.Counter("prepare_beacon_incorrect_fee_recipient_solo").Inc()
return gbp.Forbidden,
fmt.Errorf("attempting to set fee recipient to %s differs from 0x01 credential withdrawal address %x",
proposer.FeeRecipient,
validatorInfo.WithdrawalAddress,
)
}
pr.m.Counter("prepare_beacon_correct_fee_recipient_solo").Inc()
metrics.ObserveSoloValidator(validatorInfo.WithdrawalAddress, validatorInfo.Pubkey)
continue
}
// If the fee recipient matches expectations, good, move on to the next one
if strings.EqualFold(rpInfo.ExpectedFeeRecipient.String(), proposer.FeeRecipient) {
pr.m.Counter("prepare_beacon_correct_fee_recipient").Inc()
metrics.ObserveValidator(rpInfo.NodeAddress, pubkey)
continue
}
// rETH address is a 'safe' default fee recipient, and should be allowed.
// However, it does indicate a misconfigured node, so log it.
if strings.EqualFold(pr.EL.REthAddress().String(), proposer.FeeRecipient) {
pr.m.Counter("prepare_beacon_reth_fee_recipient").Inc()
pr.Logger.Warn("prepare_beacon_proposer called with rETH fee recipient",
zap.String("expected", rpInfo.ExpectedFeeRecipient.String()),
zap.String("node", rpInfo.NodeAddress.String()))
continue
}
// Looks like a cheater- fee recipient doesn't match expectations
pr.m.Counter("prepare_beacon_incorrect_fee_recipient").Inc()
pr.Logger.Warn("prepare_beacon_proposer called with unexpected fee recipient",
zap.String("expected", rpInfo.ExpectedFeeRecipient.String()), zap.String("got", proposer.FeeRecipient))
return gbp.Conflict, fmt.Errorf("actual fee recipient %s didn't match expected fee recipient %s",
proposer.FeeRecipient,
rpInfo.ExpectedFeeRecipient.String(),
)
}
// At this point all the fee recipients match our expectations. Proxy the request
return gbp.Allowed, nil
}
func (pr *ProxyRouter) registerValidatorGuard(validators gbp.RegisterValidatorRequest, ctx context.Context) (gbp.AuthenticationStatus, error) {
pr.m.Counter("register_validator").Inc()
authedNode, operatorType, err := pr.readContext(ctx)
if err != nil {
pr.Logger.Warn("Error reading cached data from request context", zap.Error(err))
return gbp.InternalError, nil
}
for _, validator := range validators {
pubkeyStr := strings.TrimPrefix(validator.Message.Pubkey, "0x")
pubkey, err := rptypes.HexToValidatorPubkey(pubkeyStr)
if err != nil {
pr.Logger.Warn("Malformed pubkey in register_validator_request", zap.Error(err), zap.String("pubkey", pubkeyStr))
return gbp.BadRequest, fmt.Errorf("error parsing pubkey from request body: %v", err)
}
// Grab the expected fee recipient for the pubkey
rpInfo, err := pr.EL.GetRPInfo(pubkey)
if err != nil {
pr.Logger.Panic("error querying cache", zap.Error(err))
return gbp.InternalError, fmt.Errorf("error with cache, please report it to Rescue Node maintainers")
}
pr.logCredentialSharing(operatorType, rpInfo, nil, common.BytesToAddress(authedNode))
if rpInfo == nil {
// Solo validators can do whatever they want in register_validator.
// The endpoint requires a signature, which the BN will validate, so
// we know for sure that the downstream user has custody of the BLS keys.
// The only thing to do is record some metrics
feeRecipient := common.HexToAddress(validator.Message.FeeRecipient)
metrics.ObserveSoloValidator(feeRecipient, pubkey)
continue
}
if strings.EqualFold(rpInfo.ExpectedFeeRecipient.String(), validator.Message.FeeRecipient) {
// This fee recipient matches expectations, carry on to the next validator
pr.m.Counter("register_validator_correct_fee_recipient").Inc()
metrics.ObserveValidator(rpInfo.NodeAddress, pubkey)
continue
}
if strings.EqualFold(pr.EL.REthAddress().String(), validator.Message.FeeRecipient) {
// rETH address is a 'safe' default fee recipient, and should be allowed.
// However, it does indicate a misconfigured node, so log it.
pr.m.Counter("register_validator_reth_fee_recipient").Inc()
pr.Logger.Warn("register_validator called with rETH fee recipient",
zap.String("expected", rpInfo.ExpectedFeeRecipient.String()),
zap.String("node", rpInfo.NodeAddress.String()))
continue
}
pr.m.Counter("register_validator_incorrect_fee_recipient").Inc()
pr.Logger.Warn("register_validator called with unexpected fee recipient",
zap.String("expected", rpInfo.ExpectedFeeRecipient.String()),
zap.String("got", validator.Message.FeeRecipient),
)
return gbp.Conflict, fmt.Errorf("actual fee recipient %s didn't match expected fee recipient %s",
validator.Message.FeeRecipient,
rpInfo.ExpectedFeeRecipient.String(),
)
}
// At this point all the fee recipients match our expectations. Proxy the request
return gbp.Allowed, nil
}
// https://github.com/ChainSafe/lodestar/issues/6154
func (pr *ProxyRouter) urlDecode(username, password string) (string, string) {
u, err := url.QueryUnescape(username)
if err != nil {
u = username
}
p, err := url.QueryUnescape(password)
if err != nil {
p = password
}
if username != u || password != p {
pr.m.Counter("url_decoded").Inc()
}
return u, p
}
// Adds authentication to any handler.
func (pr *ProxyRouter) authenticate(r *http.Request) (gbp.AuthenticationStatus, context.Context, error) {
// Authenticate the request here, return 403 and exit early as needed.
// Start by grabbing basicauth
username, password, ok := r.BasicAuth()
if !ok {
pr.m.Counter("missing_credentials").Inc()
pr.Logger.Debug("Received request with no credentials on guarded endpoint")
return gbp.Unauthorized, nil, fmt.Errorf("missing credentials")
}
// https://github.com/ChainSafe/lodestar/issues/6154
username, password = pr.urlDecode(username, password)
ac, err := pr.auth.authenticate(username, password)
if err != nil {
pr.m.Counter("unauthed").Inc()
pr.Logger.Debug("Unable to authenticate credentials", zap.Error(err))
return err.gbpStatus, nil, err
}
// If auth succeeds:
if ac.Credential.OperatorType == pb.OperatorType_OT_ROCKETPOOL {
pr.m.Counter("auth_ok").Inc()
} else {
// If we're dropping solo traffic, 429 it here
if !pr.EnableSoloValidators {
return gbp.TooManyRequests, nil, fmt.Errorf("solo validator support was manually disabled, but may be restored later")
}
pr.m.Counter("auth_ok_solo").Inc()
}
pr.Logger.Debug("Proxying Guarded URI", zap.String("uri", r.RequestURI))
// Add the node address to the request context
ctx := context.WithValue(r.Context(), prContextNodeAddrKey, ac.Credential.NodeId)
// Add the operator type to the request context
ctx = context.WithValue(ctx, prContextOperatorTypeKey, ac.Credential.OperatorType)
return gbp.Allowed, ctx, nil
}
func (pr *ProxyRouter) grpcAuthenticate(md metadata.MD) (gbp.AuthenticationStatus, context.Context, error) {
val, exists := md["rprnauth"]
if !exists || len(val) < 1 {
pr.gm.Counter("auth_header_missing").Inc()
pr.Logger.Debug("grpc access without auth header", zap.Bool("exists", exists))
return gbp.Unauthorized, nil, fmt.Errorf("headers missing")
}
auth := strings.Split(val[0], ":")
if len(auth) != 2 {
pr.gm.Counter("auth_header_malformed").Inc()
pr.Logger.Debug("grpc access with invalid auth header")
return gbp.Unauthorized, nil, fmt.Errorf("headers invalid")
}
ac, err := pr.auth.authenticate(auth[0], auth[1])
if err != nil {
pr.gm.Counter("unauthed").Inc()
pr.Logger.Debug("Unable to authenticate credentials", zap.Error(err))
return err.gbpStatus, nil, err
}
if ac.Credential.OperatorType == pb.OperatorType_OT_ROCKETPOOL {
pr.gm.Counter("auth_ok").Inc()
} else {
// If we're dropping solo traffic, 429 it here
if !pr.EnableSoloValidators {
return gbp.TooManyRequests, nil, fmt.Errorf("solo validator support was manually disabled, but may be restored later")
}
pr.gm.Counter("auth_ok_solo").Inc()
}
ctx := context.WithValue(context.Background(), prContextNodeAddrKey, ac.Credential.NodeId)
ctx = context.WithValue(ctx, prContextOperatorTypeKey, ac.Credential.OperatorType)
return gbp.Allowed, ctx, nil
}
func (pr *ProxyRouter) Init() {
// Initialize the auth handler
pr.auth = initAuth(
credentials.NewCredentialManager(
sha256.New,
[]byte(pr.CredentialSecret),
),
)
// Create the reverse proxy.
pr.gbp = &gbp.GuardedBeaconProxy{
BeaconURL: pr.BeaconURL,
GRPCBeaconURL: pr.GRPCBeaconURL,
HTTPAuthenticator: pr.authenticate,
GRPCAuthenticator: pr.grpcAuthenticate,
PrepareBeaconProposerGuard: pr.prepareBeaconProposerGuard,
RegisterValidatorGuard: pr.registerValidatorGuard,
}
pr.gbp.TLS.CertFile = pr.TLSCertFile
pr.gbp.TLS.KeyFile = pr.TLSKeyFile
pr.m = metrics.NewMetricsRegistry("http_proxy")
pr.gm = metrics.NewMetricsRegistry("grpc_proxy")
}
func (pr *ProxyRouter) Start() error {
pr.gbp.Addr = pr.Addr
pr.gbp.GRPCAddr = pr.GRPCAddr
return pr.gbp.ListenAndServe()
}
func (pr *ProxyRouter) Serve(httpListener net.Listener, grpcListener net.Listener) error {
pr.gbp.Addr = httpListener.Addr().String()
if grpcListener != nil {
pr.gbp.GRPCAddr = grpcListener.Addr().String()
return pr.gbp.Serve(httpListener, &grpcListener)
}
return pr.gbp.Serve(httpListener, nil)
}
func (pr *ProxyRouter) Stop(ctx context.Context) {
pr.gbp.Stop(ctx)
}