-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathopk.go
100 lines (83 loc) · 2.33 KB
/
opk.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
package signedattestation
import (
"bytes"
"context"
"crypto"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/openpubkey/openpubkey/client"
"github.com/openpubkey/openpubkey/pktoken"
"github.com/openpubkey/openpubkey/util"
"github.com/secure-systems-lab/go-securesystemslib/dsse"
)
const (
OpkSignatureID = "OPK"
)
type opkSignerVerifier struct {
provider client.OpenIdProvider
}
func NewOPKSignerVerifier(provider client.OpenIdProvider) dsse.SignerVerifier {
return &opkSignerVerifier{provider: provider}
}
func (sv *opkSignerVerifier) Sign(ctx context.Context, data []byte) ([]byte, error) {
hash := s256(data)
hashHex := hex.EncodeToString(hash)
signer, err := util.GenKeyPair(jwa.ES256)
if err != nil {
return nil, fmt.Errorf("error generating key pair: %w", err)
}
opkClient := client.OpkClient{Op: sv.provider}
pkToken, err := opkClient.OidcAuth(ctx, signer, jwa.ES256, map[string]any{"att": hashHex}, true)
if err != nil {
return nil, fmt.Errorf("error getting PK token: %w", err)
}
pkTokenJSON, err := json.Marshal(pkToken)
if err != nil {
return nil, fmt.Errorf("error marshalling PK token to JSON: %w", err)
}
return pkTokenJSON, nil
}
func (sv *opkSignerVerifier) Verify(ctx context.Context, data, sig []byte) error {
token := &pktoken.PKToken{}
err := json.Unmarshal(sig, token)
if err != nil {
return fmt.Errorf("error unmarshalling PK token from JSON: %w", err)
}
err = client.VerifyPKToken(ctx, token, sv.provider)
if err != nil {
return fmt.Errorf("error verifying PK token: %w", err)
}
cicPH, err := token.Cic.ProtectedHeaders().AsMap(ctx)
if err != nil {
return fmt.Errorf("error getting CIC protected headers: %w", err)
}
att, ok := cicPH["att"]
if !ok {
return fmt.Errorf("CIC protected headers missing att")
}
attStr, ok := att.(string)
if !ok {
return fmt.Errorf("att is not a string")
}
attDigest, err := hex.DecodeString(attStr)
if err != nil {
return fmt.Errorf("error decoding att: %w", err)
}
if !bytes.Equal(attDigest, s256(data)) {
return fmt.Errorf("att does not match data")
}
return nil
}
func (*opkSignerVerifier) Public() crypto.PublicKey {
return nil
}
func (*opkSignerVerifier) KeyID() (string, error) {
return OpkSignatureID, nil
}
func s256(data []byte) []byte {
h := sha256.Sum256(data)
return h[:]
}