-
Notifications
You must be signed in to change notification settings - Fork 4
/
verify.go
634 lines (560 loc) · 17.8 KB
/
verify.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
package replidentity
import (
"encoding/base64"
"errors"
"fmt"
"strings"
"time"
"github.com/o1egl/paseto"
"golang.org/x/crypto/ed25519"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"github.com/replit/go-replidentity/paserk"
"github.com/replit/go-replidentity/protos/external/goval/api"
)
type verifier struct {
claims *MessageClaims
// signing certs can allow "any *" variants
anyReplid bool
anyUser bool
anyUserID bool
anyOrg bool
anyCluster bool
anySubcluster bool
deployments bool
}
func (v *verifier) verifyToken(token string, pubkey ed25519.PublicKey) ([]byte, error) {
if len(pubkey) == 0 {
return nil, errors.New("pubkey is empty")
}
var meta string
err := paseto.NewV2().Verify(token, pubkey, &meta, nil)
if err != nil {
return nil, fmt.Errorf("failed to verify token with public key: %w", err)
}
bytes, err := base64.StdEncoding.DecodeString(meta)
if err != nil {
return nil, fmt.Errorf("failed to decode token: %w", err)
}
return bytes, nil
}
func (v *verifier) verifyTokenWithKeyID(token string, keyid string, issuer string, getPubKey PubKeySource) ([]byte, error) {
pubkey, err := getPubKey(keyid, issuer)
if err != nil {
return nil, fmt.Errorf("failed to get pubkey %s: %w", keyid, err)
}
return v.verifyToken(token, pubkey)
}
func (v *verifier) verifyTokenWithCert(token string, cert *api.GovalCert) ([]byte, error) {
var pubkey ed25519.PublicKey
var err error
if strings.HasPrefix(cert.PublicKey, paserk.PaserkPublicHeader) {
pubkey, err = paserk.PASERKPublicToPublicKey(paserk.PASERKPublic(cert.PublicKey))
} else {
pubkey, err = pemToPubkey(cert.PublicKey)
}
if err != nil {
return nil, fmt.Errorf("failed to decode public key: %w", err)
}
return v.verifyToken(token, pubkey)
}
func (v *verifier) verifyCert(certBytes []byte, signingCert *api.GovalCert) (*api.GovalCert, error) {
var cert api.GovalCert
err := proto.Unmarshal(certBytes, &cert)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal cert: %w", err)
}
// Verify that the cert is valid
err = verifyClaims(cert.Iat.AsTime(), cert.Exp.AsTime(), "", "", "", "", "", 0, false, nil)
if err != nil {
return nil, fmt.Errorf("cert is not valid: %w", err)
}
// If the parent cert is not the root cert
if signingCert != nil {
claims := parseClaims(signingCert)
if _, ok := claims.Flags[api.FlagClaim_SIGN_INTERMEDIATE_CERT]; !ok {
return nil, fmt.Errorf("signing cert doesn't have authority to sign intermediate certs")
}
// Verify the cert claims agrees with its signer
authorizedClaims := map[string]struct{}{}
var anyReplid, anyUser, anyUserID, anyOrg, anyCluster, anySubcluster, deployments bool
for _, claim := range signingCert.Claims {
authorizedClaims[claim.String()] = struct{}{}
switch tc := claim.Claim.(type) {
case *api.CertificateClaim_Flag:
if tc.Flag == api.FlagClaim_ANY_REPLID {
anyReplid = true
}
if tc.Flag == api.FlagClaim_ANY_USER {
anyUser = true
}
if tc.Flag == api.FlagClaim_ANY_USER_ID {
anyUserID = true
}
if tc.Flag == api.FlagClaim_ANY_ORG {
anyOrg = true
}
if tc.Flag == api.FlagClaim_ANY_CLUSTER {
anyCluster = true
}
if tc.Flag == api.FlagClaim_ANY_SUBCLUSTER {
anySubcluster = true
}
if tc.Flag == api.FlagClaim_DEPLOYMENTS {
deployments = true
}
}
}
for _, claim := range cert.Claims {
switch tc := claim.Claim.(type) {
case *api.CertificateClaim_Flag:
if tc.Flag == api.FlagClaim_ANY_REPLID {
v.anyReplid = true
}
if tc.Flag == api.FlagClaim_ANY_USER {
v.anyUser = true
}
if tc.Flag == api.FlagClaim_ANY_USER_ID {
v.anyUserID = true
}
if tc.Flag == api.FlagClaim_ANY_ORG {
v.anyOrg = true
}
if tc.Flag == api.FlagClaim_ANY_CLUSTER {
v.anyCluster = true
}
if tc.Flag == api.FlagClaim_ANY_SUBCLUSTER {
v.anySubcluster = true
}
if tc.Flag == api.FlagClaim_DEPLOYMENTS {
v.deployments = true
}
case *api.CertificateClaim_Replid:
if anyReplid {
continue
}
case *api.CertificateClaim_User:
if anyUser {
continue
}
case *api.CertificateClaim_UserId:
if anyUserID {
continue
}
case *api.CertificateClaim_Org:
if anyOrg {
continue
}
case *api.CertificateClaim_Cluster:
if anyCluster {
continue
}
case *api.CertificateClaim_Subcluster:
if anySubcluster {
continue
}
case *api.CertificateClaim_Deployment:
if deployments || !tc.Deployment {
continue
}
}
if _, ok := authorizedClaims[claim.String()]; !ok {
return nil, fmt.Errorf("signing cert {%+v} does not authorize claim in {%+v}: %s", signingCert, cert, claim)
}
}
}
// Store this cert's claims so we can validate tokens later.
certClaims := parseClaims(&cert)
if certClaims != nil {
v.claims = certClaims
}
return &cert, nil
}
func (v *verifier) verifyChain(token string, getPubKey PubKeySource) ([]byte, *api.GovalCert, error) {
signingAuthority, err := getSigningAuthority(token)
if err != nil {
return nil, nil, fmt.Errorf("failed to get authority: %w", err)
}
switch signingAuth := signingAuthority.Cert.(type) {
case *api.GovalSigningAuthority_KeyId:
// If it's signed directly with a root key, grab the pubkey and verify it
verifiedBytes, err := v.verifyTokenWithKeyID(token, signingAuth.KeyId, signingAuthority.Issuer, getPubKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to verify root signiture: %w", err)
}
return verifiedBytes, nil, nil
case *api.GovalSigningAuthority_SignedCert:
// If its signed by another token, verify the other token first
signingBytes, skipLevelCert, err := v.verifyChain(signingAuth.SignedCert, getPubKey)
if err != nil {
return nil, nil, fmt.Errorf("failed to verify signing token: %w", err)
}
// Make sure the two parent certs agree
signingCert, err := v.verifyCert(signingBytes, skipLevelCert)
if err != nil {
return nil, nil, fmt.Errorf("signing cert invalid: %w", err)
}
// Now verify this token using the parent cert
verifiedBytes, err := v.verifyTokenWithCert(token, signingCert)
if err != nil {
return nil, nil, fmt.Errorf("failed to verify token: %w", err)
}
return verifiedBytes, signingCert, nil
default:
return nil, nil, fmt.Errorf("unknown token authority: %s", signingAuth)
}
}
// easy entry-point so you don't need to create a verifier yourself
func verifyChain(token string, getPubKey PubKeySource) (*verifier, []byte, *api.GovalCert, error) {
v := verifier{}
bytes, cert, err := v.verifyChain(token, getPubKey)
if err != nil {
return nil, nil, nil, err
}
return &v, bytes, cert, err
}
// checkClaimsAgainstToken ensures the claims match up with the token.
// This ensures that the final token in the chain is not spoofed via the forwarding protection private key.
func (v *verifier) checkClaimsAgainstToken(token *api.GovalReplIdentity) error {
// if the claims are nil, it means that the token was signed by the root privkey,
// which implicitly has all claims.
if v.claims == nil {
return nil
}
var cluster, subcluster string
var deployment bool
switch v := token.Runtime.(type) {
case *api.GovalReplIdentity_Deployment:
deployment = true
case *api.GovalReplIdentity_Interactive:
cluster = v.Interactive.Cluster
subcluster = v.Interactive.Subcluster
case *api.GovalReplIdentity_Hosting:
cluster = v.Hosting.Cluster
subcluster = v.Hosting.Subcluster
}
opts := verifyRawClaimsOpts{
replid: token.Replid,
user: token.User,
cluster: cluster,
subcluster: subcluster,
deployment: deployment,
claims: v.claims,
anyReplid: v.anyReplid,
anyUser: v.anyUser,
anyCluster: v.anyCluster,
anyOrg: v.anyOrg,
anySubcluster: v.anySubcluster,
allowsDeployment: v.deployments,
}
if token.Org != nil {
opts.orgId = token.GetOrg().GetId()
opts.orgType = token.GetOrg().GetType()
}
return verifyRawClaims(opts)
}
// VerifyOption specifies an additional verification step to be performed on an identity.
type VerifyOption interface {
verify(*api.GovalReplIdentity) error
}
type funcVerifyOption struct {
f func(identity *api.GovalReplIdentity) error
}
func (o *funcVerifyOption) verify(identity *api.GovalReplIdentity) error {
return o.f(identity)
}
// WithVerify allows the caller to specify an arbitrary function to perform
// verification on the identity prior to it being returned.
func WithVerify(f func(identity *api.GovalReplIdentity) error) VerifyOption {
return &funcVerifyOption{
f: f,
}
}
// WithSource verifies that the identity's origin replID matches the given
// source, if present. This can be used to enforce specific clients in servers
// when verifying identities.
func WithSource(sourceReplid string) VerifyOption {
return WithVerify(func(identity *api.GovalReplIdentity) error {
if identity.OriginReplid != "" && identity.OriginReplid != sourceReplid {
return fmt.Errorf("identity origin replid does not match. expected %q; got %q", sourceReplid, identity.OriginReplid)
}
return nil
})
}
// VerifyIdentity verifies that the given `REPL_IDENTITY` value is in fact
// signed by Goval's chain of authority, and addressed to the provided audience
// (the `REPL_ID` of the recipient).
//
// The optional options allow specifying additional verifications on the identity.
func VerifyIdentity(message string, audience []string, getPubKey PubKeySource, options ...VerifyOption) (*api.GovalReplIdentity, error) {
opts := VerifyTokenOpts{
Message: message,
Audience: audience,
GetPubKey: getPubKey,
Options: options,
Flags: []api.FlagClaim{api.FlagClaim_IDENTITY},
}
return VerifyToken(opts)
}
// VerifyRenewIdentity verifies that the given `REPL_RENEWAL` value is in fact
// signed by Goval's chain of authority, addressed to the provided audience
// (the `REPL_ID` of the recipient), and has the capability to renew the
// identity.
//
// The optional options allow specifying additional verifications on the identity.
func VerifyRenewIdentity(message string, audience []string, getPubKey PubKeySource, options ...VerifyOption) (*api.GovalReplIdentity, error) {
opts := VerifyTokenOpts{
Message: message,
Audience: audience,
GetPubKey: getPubKey,
Options: options,
Flags: []api.FlagClaim{api.FlagClaim_RENEW_IDENTITY},
}
return VerifyToken(opts)
}
type VerifyTokenOpts struct {
Message string
Audience []string
GetPubKey PubKeySource
Options []VerifyOption
Flags []api.FlagClaim
}
// VerifyToken verifies that the given `REPL_IDENTITY` value is in fact
// signed by Goval's chain of authority, and addressed to the provided audience
// (the `REPL_ID` of the recipient).
//
// The optional options allow specifying additional verifications on the identity.
func VerifyToken(opts VerifyTokenOpts) (*api.GovalReplIdentity, error) {
v, bytes, _, err := verifyChain(opts.Message, opts.GetPubKey)
if err != nil {
return nil, fmt.Errorf("failed verify message: %w", err)
}
signingAuthority, err := getSigningAuthority(opts.Message)
if err != nil {
return nil, fmt.Errorf("failed to read body type: %w", err)
}
var identity api.GovalReplIdentity
switch signingAuthority.GetVersion() {
case api.TokenVersion_BARE_REPL_TOKEN:
return nil, errors.New("wrong type of token provided")
case api.TokenVersion_TYPE_AWARE_TOKEN:
err = proto.Unmarshal(bytes, &identity)
if err != nil {
return nil, fmt.Errorf("failed to decode body: %w", err)
}
}
var validAudience bool
for _, aud := range opts.Audience {
if aud == identity.Aud {
validAudience = true
break
}
}
if !validAudience {
return nil, fmt.Errorf("message identity mismatch. expected %q, got %q", opts.Audience, identity.Aud)
}
err = v.checkClaimsAgainstToken(&identity)
if err != nil {
return nil, fmt.Errorf("claim mismatch: %w", err)
}
if v.claims != nil {
for _, flag := range opts.Flags {
if _, ok := v.claims.Flags[flag]; !ok {
return nil, fmt.Errorf("token not authorized for flag %s", flag)
}
}
} else if len(opts.Flags) > 0 {
return nil, fmt.Errorf("token not authorized for flags")
}
for _, option := range opts.Options {
err = option.verify(&identity)
if err != nil {
return nil, err
}
}
return &identity, nil
}
type verifyRawClaimsOpts struct {
replid string
user string
cluster string
subcluster string
deployment bool
claims *MessageClaims
anyReplid bool
anyUser bool
anyCluster bool
anySubcluster bool
anyOrg bool
allowsDeployment bool
orgId string
orgType api.Org_OrgType
}
func verifyRawClaims(
opts verifyRawClaimsOpts,
) error {
if opts.claims != nil {
if opts.replid != "" && !opts.anyReplid {
if _, ok := opts.claims.Repls[opts.replid]; !ok {
return errors.New("not authorized (replid)")
}
}
if opts.user != "" && !opts.anyUser {
if _, ok := opts.claims.Users[opts.user]; !ok {
return errors.New("not authorized (user)")
}
}
if opts.orgId != "" && !opts.anyOrg {
orgKey := OrgKey{
Id: opts.orgId,
Typ: opts.orgType,
}
if _, ok := opts.claims.Orgs[orgKey]; !ok {
return errors.New("not authorized (orgId)")
}
}
if opts.cluster != "" && !opts.anyCluster {
if _, ok := opts.claims.Clusters[opts.cluster]; !ok {
return errors.New("not authorized (cluster)")
}
}
if opts.subcluster != "" && !opts.anySubcluster {
if _, ok := opts.claims.Subclusters[opts.subcluster]; !ok {
return errors.New("not authorized (subcluster)")
}
}
if opts.deployment && !opts.allowsDeployment {
return errors.New("not authorized (deployment)")
}
}
return nil
}
func verifyClaims(iat time.Time, exp time.Time, replid, user, cluster, subcluster, orgId string, orgType api.Org_OrgType, deployment bool, claims *MessageClaims) error {
if iat.After(time.Now()) {
return fmt.Errorf("not valid for %s", time.Until(iat))
}
if exp.Before(time.Now()) {
return fmt.Errorf("expired %s ago", time.Since(exp))
}
opts := verifyRawClaimsOpts{
replid: replid,
user: user,
orgId: orgId,
orgType: orgType,
cluster: cluster,
subcluster: subcluster,
deployment: deployment,
claims: claims,
}
return verifyRawClaims(opts)
}
func decodeUnsafePASETO(token string) ([]byte, error) {
parts := strings.Split(token, ".")
if len(parts) != 4 {
return nil, fmt.Errorf("token not in PASETO format")
}
if parts[0] != "v2" || parts[1] != "public" {
return nil, fmt.Errorf("token does not start with v2.public.")
}
bytes, err := base64.RawURLEncoding.DecodeString(parts[2])
if err != nil {
return nil, fmt.Errorf("invalid token body payload: %w", err)
}
// v2.public tokens have a 64-byte signature after the main body.
bytes, err = base64.StdEncoding.DecodeString(string(bytes[:len(bytes)-64]))
if err != nil {
return nil, fmt.Errorf("invalid token body internal payload: %w", err)
}
return bytes, nil
}
func decodeUnsafeReplIdentity(token string) (*api.GovalReplIdentity, error) {
bytes, err := decodeUnsafePASETO(token)
if err != nil {
return nil, err
}
var replIdentity api.GovalReplIdentity
err = proto.Unmarshal(bytes, &replIdentity)
if err != nil {
return nil, fmt.Errorf("token body not an api.GovalReplIdentity: %w", err)
}
return &replIdentity, nil
}
func decodeUnsafeGovalCert(token string) (*api.GovalCert, error) {
bytes, err := decodeUnsafePASETO(token)
if err != nil {
return nil, err
}
var decodedCert api.GovalCert
err = proto.Unmarshal(bytes, &decodedCert)
if err != nil {
return nil, fmt.Errorf("token body not an api.GovalReplIdentity: %w", err)
}
return &decodedCert, nil
}
// DebugTokenAsString returns a string representation explaining a token. It does not perform any
// validation of the token, and should be used only for debugging.
func DebugTokenAsString(token string) string {
lines := []string{
"raw token:",
fmt.Sprintf(" %s", token),
}
marshalOptions := protojson.MarshalOptions{
Indent: " ",
Multiline: true,
}
// First dump the token contents.
lines = append(lines, "decoded token:")
replIdentity, err := decodeUnsafeReplIdentity(token)
if err != nil {
lines = append(lines, fmt.Sprintf(" token decode error: %v", err))
return strings.Join(lines, "\n")
}
for _, line := range strings.Split(marshalOptions.Format(replIdentity), "\n") {
lines = append(lines, fmt.Sprintf(" %s", line))
}
lines = append(lines, "signing authority chain:")
// Now dump the signing authority chain.
for {
signingAuthority, err := getSigningAuthority(token)
lines = append(lines, " signing authority:")
if err != nil {
lines = append(lines, fmt.Sprintf(" signing authority unmarshal error: %v", err))
return strings.Join(lines, "\n")
}
for _, line := range strings.Split(marshalOptions.Format(signingAuthority), "\n") {
lines = append(lines, fmt.Sprintf(" %s", line))
}
if signingAuthority.GetKeyId() != "" {
break
}
lines = append(lines, " certificate:")
token = signingAuthority.GetSignedCert()
cert, err := decodeUnsafeGovalCert(token)
if err != nil {
lines = append(lines, fmt.Sprintf(" cert unmarshal error: %v", err))
return strings.Join(lines, "\n")
}
for _, line := range strings.Split(marshalOptions.Format(cert), "\n") {
lines = append(lines, fmt.Sprintf(" %s", line))
}
lines = append(lines, "")
}
// This text is not supposed to be machine-readable, so let's make
// it extra hard for machines to parse this by word-wrapping (also makes
// it nice to print on a Repl).
const wordWrapCols = 60
var wrappedLines []string
for _, line := range lines {
indent := " "
for i := 0; i < len(line) && line[i] == ' '; i++ {
indent += " "
}
for len(line) > wordWrapCols {
wrappedLines = append(wrappedLines, line[:wordWrapCols])
line = indent + line[wordWrapCols:]
}
wrappedLines = append(wrappedLines, line)
}
lines = wrappedLines
return strings.Join(lines, "\n")
}