-
Notifications
You must be signed in to change notification settings - Fork 136
/
certstore_darwin.go
490 lines (394 loc) · 12 KB
/
certstore_darwin.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
package certstore
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework CoreFoundation -framework Security
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
*/
import "C"
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"errors"
"fmt"
"io"
"unsafe"
)
// work around https://golang.org/doc/go1.10#cgo
// in go>=1.10 CFTypeRefs are translated to uintptrs instead of pointers.
var (
nilCFDictionaryRef C.CFDictionaryRef
nilSecCertificateRef C.SecCertificateRef
nilCFArrayRef C.CFArrayRef
nilCFDataRef C.CFDataRef
nilCFErrorRef C.CFErrorRef
nilCFStringRef C.CFStringRef
nilSecIdentityRef C.SecIdentityRef
nilSecKeyRef C.SecKeyRef
nilCFAllocatorRef C.CFAllocatorRef
)
// macStore is a bogus type. We have to explicitly open/close the store on
// windows, so we provide those methods here too.
type macStore int
// openStore is a function for opening a macStore.
func openStore() (macStore, error) {
return macStore(0), nil
}
// Identities implements the Store interface.
func (s macStore) Identities() ([]Identity, error) {
query := mapToCFDictionary(map[C.CFTypeRef]C.CFTypeRef{
C.CFTypeRef(C.kSecClass): C.CFTypeRef(C.kSecClassIdentity),
C.CFTypeRef(C.kSecReturnRef): C.CFTypeRef(C.kCFBooleanTrue),
C.CFTypeRef(C.kSecMatchLimit): C.CFTypeRef(C.kSecMatchLimitAll),
})
if query == nilCFDictionaryRef {
return nil, errors.New("error creating CFDictionary")
}
defer C.CFRelease(C.CFTypeRef(query))
var absResult C.CFTypeRef
if err := osStatusError(C.SecItemCopyMatching(query, &absResult)); err != nil {
if err == errSecItemNotFound {
return []Identity{}, nil
}
return nil, err
}
defer C.CFRelease(C.CFTypeRef(absResult))
// don't need to release aryResult since the abstract result is released above.
aryResult := C.CFArrayRef(absResult)
// identRefs aren't owned by us initially. newMacIdentity retains them.
n := C.CFArrayGetCount(aryResult)
identRefs := make([]C.CFTypeRef, n)
C.CFArrayGetValues(aryResult, C.CFRange{0, n}, (*unsafe.Pointer)(unsafe.Pointer(&identRefs[0])))
idents := make([]Identity, 0, n)
for _, identRef := range identRefs {
idents = append(idents, newMacIdentity(C.SecIdentityRef(identRef)))
}
return idents, nil
}
// Import implements the Store interface.
func (s macStore) Import(data []byte, password string) error {
cdata, err := bytesToCFData(data)
if err != nil {
return err
}
defer C.CFRelease(C.CFTypeRef(cdata))
cpass := stringToCFString(password)
defer C.CFRelease(C.CFTypeRef(cpass))
cops := mapToCFDictionary(map[C.CFTypeRef]C.CFTypeRef{
C.CFTypeRef(C.kSecImportExportPassphrase): C.CFTypeRef(cpass),
})
if cops == nilCFDictionaryRef {
return errors.New("error creating CFDictionary")
}
defer C.CFRelease(C.CFTypeRef(cops))
var cret C.CFArrayRef
if err := osStatusError(C.SecPKCS12Import(cdata, cops, &cret)); err != nil {
return err
}
defer C.CFRelease(C.CFTypeRef(cret))
return nil
}
// Close implements the Store interface.
func (s macStore) Close() {}
// macIdentity implements the Identity interface.
type macIdentity struct {
ref C.SecIdentityRef
kref C.SecKeyRef
cref C.SecCertificateRef
crt *x509.Certificate
chain []*x509.Certificate
}
func newMacIdentity(ref C.SecIdentityRef) *macIdentity {
C.CFRetain(C.CFTypeRef(ref))
return &macIdentity{ref: ref}
}
// Certificate implements the Identity interface.
func (i *macIdentity) Certificate() (*x509.Certificate, error) {
certRef, err := i.getCertRef()
if err != nil {
return nil, err
}
crt, err := exportCertRef(certRef)
if err != nil {
return nil, err
}
i.crt = crt
return i.crt, nil
}
// CertificateChain implements the Identity interface.
func (i *macIdentity) CertificateChain() ([]*x509.Certificate, error) {
if i.chain != nil {
return i.chain, nil
}
certRef, err := i.getCertRef()
if err != nil {
return nil, err
}
policy := C.SecPolicyCreateSSL(0, nilCFStringRef)
var trustRef C.SecTrustRef
if err := osStatusError(C.SecTrustCreateWithCertificates(C.CFTypeRef(certRef), C.CFTypeRef(policy), &trustRef)); err != nil {
return nil, err
}
defer C.CFRelease(C.CFTypeRef(trustRef))
var cfError C.CFErrorRef
if C.SecTrustEvaluateWithError(trustRef, &cfError) {
err := cfErrorError(cfError)
return nil, err
}
var (
nchain = C.SecTrustGetCertificateCount(trustRef)
chain = make([]*x509.Certificate, 0, int(nchain))
)
for i := C.CFIndex(0); i < nchain; i++ {
chainCertCpy := C.SecTrustCopyCertificateChain(trustRef)
if C.CFArrayRef(chainCertCpy) == nilCFArrayRef {
return nil, errors.New("nil certificate in the chain")
}
chainCertRef := C.SecCertificateRef(C.CFArrayGetValueAtIndex(chainCertCpy, i))
chainCert, err := exportCertRef(chainCertRef)
if err != nil {
return nil, err
}
chain = append(chain, chainCert)
C.CFRelease(C.CFTypeRef(chainCertCpy))
}
i.chain = chain
return chain, nil
}
// Signer implements the Identity interface.
func (i *macIdentity) Signer() (crypto.Signer, error) {
// pre-load the certificate so Public() is less likely to return nil
// unexpectedly.
if _, err := i.Certificate(); err != nil {
return nil, err
}
return i, nil
}
// Delete implements the Identity interface.
func (i *macIdentity) Delete() error {
itemList := []C.SecIdentityRef{i.ref}
itemListPtr := (*unsafe.Pointer)(unsafe.Pointer(&itemList[0]))
citemList := C.CFArrayCreate(nilCFAllocatorRef, itemListPtr, 1, nil)
if citemList == nilCFArrayRef {
return errors.New("error creating CFArray")
}
defer C.CFRelease(C.CFTypeRef(citemList))
query := mapToCFDictionary(map[C.CFTypeRef]C.CFTypeRef{
C.CFTypeRef(C.kSecClass): C.CFTypeRef(C.kSecClassIdentity),
C.CFTypeRef(C.kSecMatchItemList): C.CFTypeRef(citemList),
})
if query == nilCFDictionaryRef {
return errors.New("error creating CFDictionary")
}
defer C.CFRelease(C.CFTypeRef(query))
if err := osStatusError(C.SecItemDelete(query)); err != nil {
return err
}
return nil
}
// Close implements the Identity interface.
func (i *macIdentity) Close() {
if i.ref != nilSecIdentityRef {
C.CFRelease(C.CFTypeRef(i.ref))
i.ref = nilSecIdentityRef
}
if i.kref != nilSecKeyRef {
C.CFRelease(C.CFTypeRef(i.kref))
i.kref = nilSecKeyRef
}
if i.cref != nilSecCertificateRef {
C.CFRelease(C.CFTypeRef(i.cref))
i.cref = nilSecCertificateRef
}
}
// Public implements the crypto.Signer interface.
func (i *macIdentity) Public() crypto.PublicKey {
cert, err := i.Certificate()
if err != nil {
return nil
}
return cert.PublicKey
}
// Sign implements the crypto.Signer interface.
func (i *macIdentity) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
hash := opts.HashFunc()
if len(digest) != hash.Size() {
return nil, errors.New("bad digest for hash")
}
kref, err := i.getKeyRef()
if err != nil {
return nil, err
}
cdigest, err := bytesToCFData(digest)
if err != nil {
return nil, err
}
defer C.CFRelease(C.CFTypeRef(cdigest))
algo, err := i.getAlgo(hash)
if err != nil {
return nil, err
}
// sign the digest
var cerr C.CFErrorRef
csig := C.SecKeyCreateSignature(kref, algo, cdigest, &cerr)
if err := cfErrorError(cerr); err != nil {
defer C.CFRelease(C.CFTypeRef(cerr))
return nil, err
}
if csig == nilCFDataRef {
return nil, errors.New("nil signature from SecKeyCreateSignature")
}
defer C.CFRelease(C.CFTypeRef(csig))
sig := cfDataToBytes(csig)
return sig, nil
}
// getAlgo decides which algorithm to use with this key type for the given hash.
func (i *macIdentity) getAlgo(hash crypto.Hash) (algo C.SecKeyAlgorithm, err error) {
var crt *x509.Certificate
if crt, err = i.Certificate(); err != nil {
return
}
switch crt.PublicKey.(type) {
case *ecdsa.PublicKey:
switch hash {
case crypto.SHA1:
algo = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA1
case crypto.SHA256:
algo = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA256
case crypto.SHA384:
algo = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA384
case crypto.SHA512:
algo = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA512
default:
err = ErrUnsupportedHash
}
case *rsa.PublicKey:
switch hash {
case crypto.SHA1:
algo = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA1
case crypto.SHA256:
algo = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256
case crypto.SHA384:
algo = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA384
case crypto.SHA512:
algo = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA512
default:
err = ErrUnsupportedHash
}
default:
err = errors.New("unsupported key type")
}
return
}
// getKeyRef gets the SecKeyRef for this identity's pricate key.
func (i *macIdentity) getKeyRef() (C.SecKeyRef, error) {
if i.kref != nilSecKeyRef {
return i.kref, nil
}
var keyRef C.SecKeyRef
if err := osStatusError(C.SecIdentityCopyPrivateKey(i.ref, &keyRef)); err != nil {
return nilSecKeyRef, err
}
i.kref = keyRef
return i.kref, nil
}
// getCertRef gets the SecCertificateRef for this identity's certificate.
func (i *macIdentity) getCertRef() (C.SecCertificateRef, error) {
if i.cref != nilSecCertificateRef {
return i.cref, nil
}
var certRef C.SecCertificateRef
if err := osStatusError(C.SecIdentityCopyCertificate(i.ref, &certRef)); err != nil {
return nilSecCertificateRef, err
}
i.cref = certRef
return i.cref, nil
}
// exportCertRef gets a *x509.Certificate for the given SecCertificateRef.
func exportCertRef(certRef C.SecCertificateRef) (*x509.Certificate, error) {
derRef := C.SecCertificateCopyData(certRef)
if derRef == nilCFDataRef {
return nil, errors.New("error getting certificate from identity")
}
defer C.CFRelease(C.CFTypeRef(derRef))
der := cfDataToBytes(derRef)
crt, err := x509.ParseCertificate(der)
if err != nil {
return nil, err
}
return crt, nil
}
// stringToCFString converts a Go string to a CFStringRef.
func stringToCFString(gostr string) C.CFStringRef {
cstr := C.CString(gostr)
defer C.free(unsafe.Pointer(cstr))
return C.CFStringCreateWithCString(nilCFAllocatorRef, cstr, C.kCFStringEncodingUTF8)
}
// mapToCFDictionary converts a Go map[C.CFTypeRef]C.CFTypeRef to a
// CFDictionaryRef.
func mapToCFDictionary(gomap map[C.CFTypeRef]C.CFTypeRef) C.CFDictionaryRef {
var (
n = len(gomap)
keys = make([]unsafe.Pointer, 0, n)
values = make([]unsafe.Pointer, 0, n)
)
for k, v := range gomap {
keys = append(keys, unsafe.Pointer(k))
values = append(values, unsafe.Pointer(v))
}
return C.CFDictionaryCreate(nilCFAllocatorRef, &keys[0], &values[0], C.CFIndex(n), nil, nil)
}
// cfDataToBytes converts a CFDataRef to a Go byte slice.
func cfDataToBytes(cfdata C.CFDataRef) []byte {
nBytes := C.CFDataGetLength(cfdata)
bytesPtr := C.CFDataGetBytePtr(cfdata)
return C.GoBytes(unsafe.Pointer(bytesPtr), C.int(nBytes))
}
// bytesToCFData converts a Go byte slice to a CFDataRef.
func bytesToCFData(gobytes []byte) (C.CFDataRef, error) {
var (
cptr = (*C.UInt8)(nil)
clen = C.CFIndex(len(gobytes))
)
if len(gobytes) > 0 {
cptr = (*C.UInt8)(&gobytes[0])
}
cdata := C.CFDataCreate(nilCFAllocatorRef, cptr, clen)
if cdata == nilCFDataRef {
return nilCFDataRef, errors.New("error creatin cfdata")
}
return cdata, nil
}
// osStatus wraps a C.OSStatus
type osStatus C.OSStatus
const (
errSecItemNotFound = osStatus(C.errSecItemNotFound)
)
// osStatusError returns an error for an OSStatus unless it is errSecSuccess.
func osStatusError(s C.OSStatus) error {
if s == C.errSecSuccess {
return nil
}
return osStatus(s)
}
// Error implements the error interface.
func (s osStatus) Error() string {
return fmt.Sprintf("OSStatus %d", s)
}
// cfErrorError returns an error for a CFErrorRef unless it is nil.
func cfErrorError(cerr C.CFErrorRef) error {
if cerr == nilCFErrorRef {
return nil
}
code := int(C.CFErrorGetCode(cerr))
if cdescription := C.CFErrorCopyDescription(cerr); cdescription != nilCFStringRef {
defer C.CFRelease(C.CFTypeRef(cdescription))
if cstr := C.CFStringGetCStringPtr(cdescription, C.kCFStringEncodingUTF8); cstr != nil {
str := C.GoString(cstr)
return fmt.Errorf("CFError %d (%s)", code, str)
}
}
return fmt.Errorf("CFError %d", code)
}