-
Notifications
You must be signed in to change notification settings - Fork 0
/
pkcs11.go
247 lines (205 loc) · 5.76 KB
/
pkcs11.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
package pkcs11jwt
import (
"context"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"errors"
"fmt"
"math/big"
"encoding/asn1"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/ThalesIgnite/crypto11"
)
type PKConfig struct {
KeyID string
Path string
PKCS_ID []byte
TokenLabel string
KeyLabel string
Pin string
SlotNumber *int
publicKeyFromPK crypto.PublicKey
crypto11Config crypto11.Config
}
type pkConfigKey struct{}
func (k *PKConfig) GetKeyID() string {
return k.KeyID
}
func (k *PKConfig) GetPublicKey() crypto.PublicKey {
return k.publicKeyFromPK
}
var (
SigningMethodPKRS256 *SigningMethodPK
SigningMethodPKPS256 *SigningMethodPK
SigningMethodPKES256 *SigningMethodPK
errMissingConfig = errors.New("pp: missing configuration in provided context")
errMissingYK = errors.New("pk: YK device not available")
)
type SigningMethodPK struct {
alg string
override jwt.SigningMethod
hasher crypto.Hash
}
func NewPKContext(parent context.Context, val *PKConfig) (context.Context, error) {
crypto11Config := &crypto11.Config{
Path: val.Path,
TokenLabel: val.TokenLabel,
SlotNumber: val.SlotNumber,
Pin: val.Pin,
}
cryptoctx, err := crypto11.Configure(crypto11Config)
if err != nil {
return nil, fmt.Errorf("pkcsjwt: Init error loading cryptctx %v", err)
}
defer cryptoctx.Close()
var priv crypto.Signer
if val.KeyLabel == "" && len(val.PKCS_ID) > 0 {
priv, err = cryptoctx.FindKeyPair(val.PKCS_ID, nil)
} else if val.KeyLabel != "" && len(val.PKCS_ID) == 0 {
priv, err = cryptoctx.FindKeyPair(nil, []byte(val.KeyLabel))
} else {
priv, err = cryptoctx.FindKeyPair(val.PKCS_ID, []byte(val.KeyLabel))
}
if priv == nil {
return nil, fmt.Errorf("pkcsjwt: Init could not find private key")
}
val.publicKeyFromPK = priv.Public()
val.crypto11Config = *crypto11Config
return context.WithValue(parent, pkConfigKey{}, val), nil
}
func YKFromContext(ctx context.Context) (*PKConfig, bool) {
val, ok := ctx.Value(pkConfigKey{}).(*PKConfig)
return val, ok
}
func init() {
// RS256
SigningMethodPKRS256 = &SigningMethodPK{
"PKRS256",
jwt.SigningMethodRS256,
crypto.SHA256,
}
jwt.RegisterSigningMethod(SigningMethodPKRS256.Alg(), func() jwt.SigningMethod {
return SigningMethodPKRS256
})
// PS256
SigningMethodPKPS256 = &SigningMethodPK{
"PKPS256",
jwt.SigningMethodPS256,
crypto.SHA256,
}
jwt.RegisterSigningMethod(SigningMethodPKPS256.Alg(), func() jwt.SigningMethod {
return SigningMethodPKPS256
})
// ES256
SigningMethodPKES256 = &SigningMethodPK{
"PKES256",
jwt.SigningMethodES256,
crypto.SHA256,
}
jwt.RegisterSigningMethod(SigningMethodPKES256.Alg(), func() jwt.SigningMethod {
return SigningMethodPKES256
})
}
// Alg will return the JWT header algorithm identifier this method is configured for.
func (s *SigningMethodPK) Alg() string {
return s.alg
}
// Override will override the default JWT implementation of the signing function this Cloud KMS type implements.
func (s *SigningMethodPK) Override() {
s.alg = s.override.Alg()
jwt.RegisterSigningMethod(s.alg, func() jwt.SigningMethod {
return s
})
}
func (s *SigningMethodPK) Hash() crypto.Hash {
return s.hasher
}
func (s *SigningMethodPK) Sign(signingString string, key interface{}) ([]byte, error) {
var ctx context.Context
switch k := key.(type) {
case context.Context:
ctx = k
default:
return nil, jwt.ErrInvalidKey
}
config, ok := YKFromContext(ctx)
if !ok {
return nil, errMissingConfig
}
cryptoctx, err := crypto11.Configure(&config.crypto11Config)
if err != nil {
return nil, fmt.Errorf("error loading cryptctx %v", err)
}
defer cryptoctx.Close()
var priv crypto.Signer
if config.KeyLabel == "" && len(config.PKCS_ID) > 0 {
priv, err = cryptoctx.FindKeyPair(config.PKCS_ID, nil)
} else if config.KeyLabel != "" && len(config.PKCS_ID) == 0 {
priv, err = cryptoctx.FindKeyPair(nil, []byte(config.KeyLabel))
} else {
priv, err = cryptoctx.FindKeyPair(config.PKCS_ID, []byte(config.KeyLabel))
}
if err != nil {
return nil, fmt.Errorf("could not init Crypto.signer %v", err)
}
if priv == nil {
return nil, fmt.Errorf("could not find KeyPair %v", err)
}
message := []byte(signingString)
hasher := s.Hash().New()
_, err = hasher.Write(message)
if err != nil {
return nil, fmt.Errorf("error hashing key: %v", err)
}
hashed := hasher.Sum(message[:0])
rng := rand.Reader
signer, ok := priv.(crypto.Signer)
if !ok {
return nil, fmt.Errorf("expected private key to implement crypto.Signer")
}
var signedBytes []byte
if s.Alg() == "PS256" {
sopts := &rsa.PSSOptions{
Hash: s.Hash(),
SaltLength: rsa.PSSSaltLengthEqualsHash,
}
signedBytes, err = signer.Sign(rng, hashed, sopts)
if err != nil {
return nil, fmt.Errorf(" error from signing from PKCS11 PSS: %v", err)
}
} else {
signedBytes, err = signer.Sign(rng, hashed, s.Hash())
if err != nil {
return nil, fmt.Errorf(" error from signing from PKCS11: %v", err)
}
}
if s.alg == "ES256" {
epub := priv.Public().(*ecdsa.PublicKey)
curveBits := epub.Curve.Params().BitSize
keyBytes := curveBits / 8
if curveBits%8 > 0 {
keyBytes += 1
}
out := make([]byte, 2*keyBytes)
var esig struct {
R, S *big.Int
}
if _, err := asn1.Unmarshal(signedBytes, &esig); err != nil {
return nil, err
}
esig.R.FillBytes(out[0:keyBytes])
esig.S.FillBytes(out[keyBytes:])
return out, nil
}
return signedBytes, nil
}
func YKVerfiyKeyfunc(ctx context.Context, config *PKConfig) (jwt.Keyfunc, error) {
return func(token *jwt.Token) (interface{}, error) {
return config.publicKeyFromPK, nil
}, nil
}
func (s *SigningMethodPK) Verify(signingString string, signature []byte, key interface{}) error {
return s.override.Verify(signingString, []byte(signature), key)
}