-
Notifications
You must be signed in to change notification settings - Fork 43
/
key_test.go
295 lines (253 loc) · 8.57 KB
/
key_test.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
package pkcs11key
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"fmt"
"math/big"
"reflect"
"testing"
"github.com/miekg/pkcs11"
)
type mockCtx struct {
currentSearch []*pkcs11.Attribute
}
const sessionHandle = pkcs11.SessionHandle(17)
// A trivial RSA public key for use in testing. We provide a CKA_ID and a
// marshalled copy so we can return the relevent items from the mocked pkcs11
// module.
var rsaKey = &rsa.PublicKey{N: big.NewInt(1), E: 1}
const rsaPrivateKeyHandle = pkcs11.ObjectHandle(23)
const rsaPublicKeyHandle = pkcs11.ObjectHandle(24)
const rsaKeyID = byte(0x04)
// A fake EC public key for use in testing. See RSA above.
var ecKey = &ecdsa.PublicKey{X: big.NewInt(1), Y: big.NewInt(1), Curve: elliptic.P256()}
const ecPrivateKeyHandle = pkcs11.ObjectHandle(32)
const ecPublicKeyHandle = pkcs11.ObjectHandle(33)
const ecKeyID = byte(0x03)
var slots = []uint{7, 8, 9}
var tokenInfo = pkcs11.TokenInfo{
Label: "token label",
}
func (c *mockCtx) CloseSession(sh pkcs11.SessionHandle) error {
return nil
}
func (c *mockCtx) FindObjectsFinal(sh pkcs11.SessionHandle) error {
c.currentSearch = []*pkcs11.Attribute{}
return nil
}
func (c *mockCtx) FindObjectsInit(sh pkcs11.SessionHandle, temp []*pkcs11.Attribute) error {
c.currentSearch = temp
return nil
}
func (c *mockCtx) FindObjects(sh pkcs11.SessionHandle, max int) ([]pkcs11.ObjectHandle, bool, error) {
if reflect.DeepEqual(c.currentSearch, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_RSA),
pkcs11.NewAttribute(pkcs11.CKA_MODULUS, rsaKey.N.Bytes()),
pkcs11.NewAttribute(pkcs11.CKA_PUBLIC_EXPONENT, big.NewInt(int64(rsaKey.E)).Bytes()),
}) {
return []pkcs11.ObjectHandle{rsaPublicKeyHandle}, false, nil
}
if reflect.DeepEqual(c.currentSearch, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
pkcs11.NewAttribute(pkcs11.CKA_ID, []byte{rsaKeyID}),
}) {
return []pkcs11.ObjectHandle{rsaPrivateKeyHandle}, false, nil
}
if reflect.DeepEqual(c.currentSearch, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY),
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_EC),
pkcs11.NewAttribute(pkcs11.CKA_EC_PARAMS, []uint8{0x6, 0x8, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x3, 0x1, 0x7}),
pkcs11.NewAttribute(pkcs11.CKA_EC_POINT, []uint8{0x4, 0x41, 0x4, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1}),
}) {
return []pkcs11.ObjectHandle{ecPublicKeyHandle}, false, nil
}
if reflect.DeepEqual(c.currentSearch, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY),
pkcs11.NewAttribute(pkcs11.CKA_ID, []byte{ecKeyID}),
}) {
return []pkcs11.ObjectHandle{ecPrivateKeyHandle}, false, nil
}
fmt.Println("unrecognized search:")
for _, v := range c.currentSearch {
fmt.Printf(" Type: %x, Value: %x\n", v.Type, v.Value)
}
return nil, false, nil
}
func p11Attribute(Type uint, Value []byte) *pkcs11.Attribute {
return &pkcs11.Attribute{
Type: Type,
Value: Value,
}
}
func rsaPublicAttributes(template []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
var output []*pkcs11.Attribute
for _, a := range template {
if a.Type == pkcs11.CKA_ID {
output = append(output, p11Attribute(a.Type, []byte{rsaKeyID}))
}
}
return output, nil
}
func rsaPrivateAttributes(template []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
var output []*pkcs11.Attribute
for _, a := range template {
// Return CKA_ALWAYS_AUTHENTICATE = 1 (true)
if a.Type == pkcs11.CKA_ALWAYS_AUTHENTICATE {
output = append(output, p11Attribute(a.Type, []byte{byte(1)}))
}
}
return output, nil
}
func ecPublicKeyAttributes(template []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
var output []*pkcs11.Attribute
for _, a := range template {
switch a.Type {
case pkcs11.CKA_ID:
output = append(output, p11Attribute(a.Type, []byte{byte(ecKeyID)}))
}
}
return output, nil
}
func (c *mockCtx) GetAttributeValue(sh pkcs11.SessionHandle, o pkcs11.ObjectHandle, template []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
switch o {
case rsaPrivateKeyHandle:
return rsaPrivateAttributes(template)
case rsaPublicKeyHandle:
return rsaPublicAttributes(template)
case ecPublicKeyHandle:
return ecPublicKeyAttributes(template)
default:
return nil, nil
}
}
func (c *mockCtx) GetSlotList(tokenPresent bool) ([]uint, error) {
return slots, nil
}
func (c *mockCtx) GetTokenInfo(slotID uint) (pkcs11.TokenInfo, error) {
return tokenInfo, nil
}
func (c *mockCtx) Initialize() error {
return nil
}
func (c *mockCtx) Login(sh pkcs11.SessionHandle, userType uint, pin string) error {
return nil
}
func (c *mockCtx) Logout(sh pkcs11.SessionHandle) error {
return nil
}
func (c *mockCtx) OpenSession(slotID uint, flags uint) (pkcs11.SessionHandle, error) {
return sessionHandle, nil
}
func (c *mockCtx) SignInit(sh pkcs11.SessionHandle, m []*pkcs11.Mechanism, o pkcs11.ObjectHandle) error {
return nil
}
func (c *mockCtx) Sign(sh pkcs11.SessionHandle, message []byte) ([]byte, error) {
return message, nil
}
func setup(t *testing.T, pubKey crypto.PublicKey) *Key {
ps := Key{
module: &mockCtx{},
tokenLabel: "token label",
pin: "unused",
publicKey: pubKey,
}
err := ps.setup()
if err != nil {
t.Fatalf("Failed to set up Key of type %T: %s", pubKey, err)
}
return &ps
}
var signInput = []byte("1234567890 1234567890 1234567890")
func sign(t *testing.T, ps *Key) []byte {
// Sign input must be exactly 32 bytes to match SHA256 size. In normally
// usage, Sign would be called by e.g. x509.CreateCertificate, which would
// handle padding to the necessary size.
output, err := ps.Sign(rand.Reader, signInput, crypto.SHA256)
if err != nil {
t.Fatalf("Failed to sign: %s", err)
}
if len(output) < len(signInput) {
t.Fatalf("Invalid signature size %d, expected at least %d", len(output), len(signInput))
}
i := len(output) - len(signInput)
if !bytes.Equal(output[i:], signInput) {
t.Fatal("Incorrect sign output")
}
return output
}
func TestInitializeBadModule(t *testing.T) {
ctx, err := initialize("/dev/null")
if err == nil {
t.Errorf("Expected failure when initializing modulePath /dev/null, got none")
}
if ctx != nil {
t.Errorf("Expected nil ctx when initializing modulePath /dev/null")
}
}
func TestInitializeKeyNotFound(t *testing.T) {
pubKey := &rsa.PublicKey{N: big.NewInt(2), E: 2}
ps := Key{
module: &mockCtx{},
tokenLabel: "token label",
pin: "unused",
publicKey: pubKey,
}
err := ps.setup()
expectedText := "looking up public key: no objects found"
if err == nil {
t.Errorf("Expected error looking up nonexistent key")
} else if err.Error() != expectedText {
t.Errorf("Expected error to contain %q, got %q", expectedText, err)
}
}
func TestSign(t *testing.T) {
ps := setup(t, rsaKey)
sig := sign(t, ps)
// Check that the RSA signature starts with the SHA256 hash prefix
var sha256Pre = []byte{0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}
if !(bytes.Equal(sha256Pre, sig[0:19])) {
t.Fatal("RSA signature doesn't start with prefix")
}
pub := ps.Public()
// Check public key is of right type
_, ok := pub.(*rsa.PublicKey)
if !ok {
t.Errorf("Attempted to get RSA key from Key, got key of type %s. Expected *rsa.PublicKey", reflect.TypeOf(pub))
}
ps = setup(t, ecKey)
sig = sign(t, ps)
if !(bytes.Equal(signInput, sig)) {
t.Fatal("ECDSA signature error")
}
}
// This is a version of the mock that gives CKR_ATTRIBUTE_TYPE_INVALID when
// asked about the CKA_ALWAYS_AUTHENTICATE attribute.
type mockCtxFailsAlwaysAuthenticate struct {
mockCtx
}
func (c *mockCtxFailsAlwaysAuthenticate) GetAttributeValue(sh pkcs11.SessionHandle, o pkcs11.ObjectHandle, template []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) {
for _, a := range template {
if a.Type == pkcs11.CKA_ALWAYS_AUTHENTICATE {
return nil, pkcs11.Error(pkcs11.CKR_ATTRIBUTE_TYPE_INVALID)
}
}
return c.mockCtx.GetAttributeValue(sh, o, template)
}
func TestAttributeTypeInvalid(t *testing.T) {
ps := &Key{
module: &mockCtxFailsAlwaysAuthenticate{},
tokenLabel: "token label",
pin: "unused",
publicKey: rsaKey,
}
err := ps.setup()
if err != nil {
t.Errorf("Failed to set up with a token that returns CKR_ATTRIBUTE_TYPE_INVALID: %s", err)
}
}