-
Notifications
You must be signed in to change notification settings - Fork 43
/
osxkeychain.go
285 lines (240 loc) · 9.37 KB
/
osxkeychain.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
package osxkeychain
import (
"crypto/x509"
"errors"
"fmt"
"unsafe"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-xcode/certificateutil"
)
/*
#cgo CFLAGS: -mmacosx-version-min=10.7 -D__MAC_OS_X_VERSION_MAX_ALLOWED=1060
#cgo LDFLAGS: -framework CoreFoundation -framework Security
#include <stdlib.h>
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
*/
import "C"
// ExportFromKeychain ...
func ExportFromKeychain(itemRefsToExport []C.CFTypeRef, isAskForPassword bool) ([]byte, error) {
passphraseCString := C.CString("")
defer C.free(unsafe.Pointer(passphraseCString))
var exportedData C.CFDataRef
var exportParams C.SecItemImportExportKeyParameters
exportParams.keyUsage = 0
exportParams.keyAttributes = 0
exportParams.version = C.SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION
if isAskForPassword {
exportParams.flags = C.kSecKeySecurePassphrase
exportParams.passphrase = 0
exportParams.alertTitle = 0
promptText := C.CString("Enter a password which will be used to protect the exported items")
defer C.free(unsafe.Pointer(promptText))
exportParams.alertPrompt = convertCStringToCFString(promptText)
} else {
exportParams.flags = 0
exportParams.passphrase = (C.CFTypeRef)(convertCStringToCFString(passphraseCString))
exportParams.alertTitle = 0
exportParams.alertPrompt = 0
}
// create a C array from the input
ptr := (*unsafe.Pointer)(unsafe.Pointer(&itemRefsToExport[0]))
cfArrayForExport := C.CFArrayCreate(
C.kCFAllocatorDefault,
ptr,
C.CFIndex(len(itemRefsToExport)),
&C.kCFTypeArrayCallBacks)
// do the export!
status := C.SecItemExport(C.CFTypeRef(cfArrayForExport),
C.kSecFormatPKCS12,
0, //C.kSecItemPemArmour, // Use kSecItemPemArmour to add PEM armour - the .p12 generated by Keychain Access.app does NOT have PEM armour
&exportParams,
&exportedData)
if status != C.errSecSuccess {
return nil, fmt.Errorf("SecItemExport: error (OSStatus): %d", status)
}
// exportedData now contains your PKCS12 data
// make sure it'll be released properly!
defer C.CFRelease(C.CFTypeRef(exportedData))
dataBytes := convertCFDataRefToGoBytes(exportedData)
if dataBytes == nil || len(dataBytes) < 1 {
return nil, errors.New("ExportFromKeychain: failed to convert export data - nil or empty")
}
log.Debugf("Export - success")
return dataBytes, nil
}
func convertCFDataRefToGoBytes(cfdata C.CFDataRef) []byte {
return C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(cfdata)), (C.int)(C.CFDataGetLength(cfdata)))
}
// ReleaseRef ...
func ReleaseRef(refItem C.CFTypeRef) {
C.CFRelease(refItem)
}
// ReleaseIdentityWithRefList ...
func ReleaseIdentityWithRefList(refItems []IdentityWithRefModel) {
for _, itm := range refItems {
ReleaseRef(itm.KeychainRef)
}
}
// CreateEmptyCFTypeRefSlice ...
func CreateEmptyCFTypeRefSlice() []C.CFTypeRef {
return []C.CFTypeRef{}
}
// GetCertificateDataFromIdentityRef ...
func GetCertificateDataFromIdentityRef(identityRef C.CFTypeRef) (*x509.Certificate, error) {
secIdentityRef := C.SecIdentityRef(identityRef)
var secCertificateRef C.SecCertificateRef
osStatusCode := C.SecIdentityCopyCertificate(secIdentityRef, &secCertificateRef)
if osStatusCode != C.errSecSuccess {
return nil, fmt.Errorf("failed to call SecItemCopyMatch - OSStatus: %d", osStatusCode)
}
certificateCFData := C.SecCertificateCopyData(secCertificateRef)
if certificateCFData == 0 {
return nil, errors.New("GetCertificateDataFromIdentityRef: SecCertificateCopyData: Failed to convert certificate data")
}
defer C.CFRelease(C.CFTypeRef(certificateCFData))
certData := convertCFDataRefToGoBytes(certificateCFData)
return x509.ParseCertificate(certData)
}
// IdentityWithRefModel ...
type IdentityWithRefModel struct {
KeychainRef C.CFTypeRef
Label string
}
// FindAndValidateIdentity ...
// IMPORTANT: you have to C.CFRelease the returned items (one-by-one)!!
// you can use the ReleaseIdentityWithRefList method to do that
func FindAndValidateIdentity(identityLabel string) (*IdentityWithRefModel, error) {
foundIdentityRefs, err := FindIdentity(identityLabel)
if err != nil {
return nil, fmt.Errorf("failed to find Identity, error: %s", err)
}
if len(foundIdentityRefs) < 1 {
return nil, nil
}
// check validity
var latestIdentityRef *IdentityWithRefModel
var latestCertificate x509.Certificate
for _, aIdentityRef := range foundIdentityRefs {
cert, err := GetCertificateDataFromIdentityRef(aIdentityRef.KeychainRef)
if err != nil {
return nil, fmt.Errorf("failed to read certificate data, error: %s", err)
}
if err := certificateutil.CheckValidity(*cert); err != nil {
log.Warnf("Certificate is not valid, skipping: %s", err)
continue
}
if latestIdentityRef == nil || cert.NotAfter.After(latestCertificate.NotAfter) {
latestIdentityRef = &aIdentityRef
latestCertificate = *cert
}
}
return latestIdentityRef, nil
}
// FindIdentity ...
// IMPORTANT: you have to C.CFRelease the returned items (one-by-one)!!
// you can use the ReleaseIdentityWithRefList method to do that
func FindIdentity(identityLabel string) ([]IdentityWithRefModel, error) {
queryDict := C.CFDictionaryCreateMutable(C.kCFAllocatorDefault, 0, nil, nil)
defer C.CFRelease(C.CFTypeRef(queryDict))
C.CFDictionaryAddValue(queryDict, unsafe.Pointer(C.kSecClass), unsafe.Pointer(C.kSecClassIdentity))
C.CFDictionaryAddValue(queryDict, unsafe.Pointer(C.kSecMatchLimit), unsafe.Pointer(C.kSecMatchLimitAll))
C.CFDictionaryAddValue(queryDict, unsafe.Pointer(C.kSecReturnAttributes), unsafe.Pointer(C.kCFBooleanTrue))
C.CFDictionaryAddValue(queryDict, unsafe.Pointer(C.kSecReturnRef), unsafe.Pointer(C.kCFBooleanTrue))
var resultRefs C.CFTypeRef
osStatusCode := C.SecItemCopyMatching((C.CFDictionaryRef)(queryDict), &resultRefs)
if osStatusCode != C.errSecSuccess {
return nil, fmt.Errorf("failed to call SecItemCopyMatch - OSStatus: %d", osStatusCode)
}
defer C.CFRelease(C.CFTypeRef(resultRefs))
identitiesArrRef := C.CFArrayRef(resultRefs)
identitiesCount := C.CFArrayGetCount(identitiesArrRef)
if identitiesCount < 1 {
return nil, fmt.Errorf("no Identity (certificate + related private key) found in your Keychain")
}
log.Debugf("identitiesCount: %d", identitiesCount)
// filter the identities, by label
var retIdentityRefs []IdentityWithRefModel
for i := C.CFIndex(0); i < identitiesCount; i++ {
aIdentityRef := C.CFArrayGetValueAtIndex(identitiesArrRef, i)
log.Debugf("aIdentityRef: %#v", aIdentityRef)
aIdentityDictRef := C.CFDictionaryRef(aIdentityRef)
log.Debugf("aIdentityDictRef: %#v", aIdentityDictRef)
lablCSting := C.CString("labl")
defer C.free(unsafe.Pointer(lablCSting))
vrefCSting := C.CString("v_Ref")
defer C.free(unsafe.Pointer(vrefCSting))
labl, err := getCFDictValueUTF8String(aIdentityDictRef, C.CFTypeRef(convertCStringToCFString(lablCSting)))
if err != nil {
log.Warnf("FindIdentity: failed to get 'labl' property: %s", err)
continue
}
log.Debugf("labl: %#v", labl)
if labl != identityLabel {
continue
}
log.Debugf("Found identity with label: %s", labl)
vrefRef, err := getCFDictValueRef(aIdentityDictRef, C.CFTypeRef(convertCStringToCFString(vrefCSting)))
if err != nil {
log.Warnf("FindIdentity: failed to get 'v_Ref' property: %s", err)
continue
}
log.Debugf("vrefRef: %#v", vrefRef)
// retain the pointer
vrefRef = C.CFRetain(vrefRef)
// store it
retIdentityRefs = append(retIdentityRefs, IdentityWithRefModel{
KeychainRef: vrefRef,
Label: labl,
})
}
return retIdentityRefs, nil
}
//
// --- UTIL METHODS
//
func getCFDictValueRef(dict C.CFDictionaryRef, key C.CFTypeRef) (C.CFTypeRef, error) {
var retVal C.CFTypeRef
exist := C.CFDictionaryGetValueIfPresent(dict, unsafe.Pointer(key), (*unsafe.Pointer)(unsafe.Pointer(retVal)))
// log.Debugf("retVal: %#v", retVal)
if exist == C.Boolean(0) {
return 0, errors.New("getCFDictValueRef: Key doesn't exist")
}
// return retVal, nil
return (C.CFTypeRef)(C.CFDictionaryGetValue(dict, unsafe.Pointer(key))), nil
}
func getCFDictValueCFStringRef(dict C.CFDictionaryRef, key C.CFTypeRef) (C.CFStringRef, error) {
val, err := getCFDictValueRef(dict, key)
if err != nil {
return 0, err
}
if val == 0 {
return 0, errors.New("getCFDictValueCFStringRef: Nil value returned")
}
if C.CFGetTypeID(val) != C.CFStringGetTypeID() {
return 0, errors.New("getCFDictValueCFStringRef: value is not a string")
}
return C.CFStringRef(val), nil
}
func convertCStringToCFString(cstring *C.char) C.CFStringRef {
return C.CFStringCreateWithCString(C.kCFAllocatorDefault, cstring, C.kCFStringEncodingUTF8)
}
func getCFDictValueUTF8String(dict C.CFDictionaryRef, key C.CFTypeRef) (string, error) {
valCFStringRef, err := getCFDictValueCFStringRef(dict, key)
if err != nil {
return "", err
}
log.Debugf("valCFStringRef: %#v", valCFStringRef)
if valCFStringRef == 0 {
return "", errors.New("getCFDictValueUTF8String: Nil value")
}
strLen := C.CFStringGetLength(valCFStringRef)
log.Debugf("strLen: %d", strLen)
charUTF8Len := C.CFStringGetMaximumSizeForEncoding(strLen, C.kCFStringEncodingUTF8) + 1
log.Debugf("charUTF8Len: %d", charUTF8Len)
cstrBytes := make([]byte, charUTF8Len, charUTF8Len)
if C.Boolean(0) == C.CFStringGetCString(valCFStringRef, (*C.char)(unsafe.Pointer(&cstrBytes[0])), charUTF8Len, C.kCFStringEncodingUTF8) {
return "", errors.New("getCFDictValueUTF8String: CFStringGetCString: failed to convert value to string")
}
return C.GoString((*C.char)(unsafe.Pointer(&cstrBytes[0]))), nil
}