forked from keybase/go-keychain
-
Notifications
You must be signed in to change notification settings - Fork 8
/
keychain.go
422 lines (364 loc) · 11.1 KB
/
keychain.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
// +build darwin ios
package keychain
// See https://developer.apple.com/library/ios/documentation/Security/Reference/keychainservices/index.html for the APIs used below.
// Also see https://developer.apple.com/library/ios/documentation/Security/Conceptual/keychainServConcepts/01introduction/introduction.html .
/*
#cgo LDFLAGS: -framework CoreFoundation -framework Security
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
*/
import "C"
import "fmt"
type Error int
var (
ErrorUnimplemented Error = Error(C.errSecUnimplemented)
ErrorParam = Error(C.errSecParam)
ErrorAllocate = Error(C.errSecAllocate)
ErrorNotAvailable = Error(C.errSecNotAvailable)
ErrorAuthFailed = Error(C.errSecAuthFailed)
ErrorDuplicateItem = Error(C.errSecDuplicateItem)
ErrorItemNotFound = Error(C.errSecItemNotFound)
ErrorInteractionNotAllowed = Error(C.errSecInteractionNotAllowed)
ErrorDecode = Error(C.errSecDecode)
)
func checkError(errCode C.OSStatus) error {
if errCode == C.errSecSuccess {
return nil
}
return Error(errCode)
}
func (k Error) Error() string {
var msg string
// SecCopyErrorMessageString is only available on OSX, so derive manually.
switch k {
case ErrorItemNotFound:
msg = fmt.Sprintf("Item not found (%d)", k)
case ErrorDuplicateItem:
msg = fmt.Sprintf("Duplicate item (%d)", k)
case ErrorParam:
msg = fmt.Sprintf("One or more parameters passed to the function were not valid (%d)", k)
case -25243:
msg = fmt.Sprintf("No access for item (%d)", k)
default:
msg = fmt.Sprintf("Keychain Error (%d)", k)
}
return msg
}
type SecClass int
// Keychain Item Classes
var (
/*
kSecClassGenericPassword item attributes:
kSecAttrAccess (OS X only)
kSecAttrAccessGroup (iOS; also OS X if kSecAttrSynchronizable specified)
kSecAttrAccessible (iOS; also OS X if kSecAttrSynchronizable specified)
kSecAttrAccount
kSecAttrService
*/
SecClassGenericPassword SecClass = 1
)
var SecClassKey = attrKey(C.CFTypeRef(C.kSecClass))
var secClassTypeRef = map[SecClass]C.CFTypeRef{
SecClassGenericPassword: C.CFTypeRef(C.kSecClassGenericPassword),
}
var (
ServiceKey = attrKey(C.CFTypeRef(C.kSecAttrService))
LabelKey = attrKey(C.CFTypeRef(C.kSecAttrLabel))
AccountKey = attrKey(C.CFTypeRef(C.kSecAttrAccount))
AccessGroupKey = attrKey(C.CFTypeRef(C.kSecAttrAccessGroup))
DataKey = attrKey(C.CFTypeRef(C.kSecValueData))
)
type Synchronizable int
const (
SynchronizableDefault Synchronizable = 0
SynchronizableAny = 1
SynchronizableYes = 2
SynchronizableNo = 3
)
var SynchronizableKey = attrKey(C.CFTypeRef(C.kSecAttrSynchronizable))
var syncTypeRef = map[Synchronizable]C.CFTypeRef{
SynchronizableAny: C.CFTypeRef(C.kSecAttrSynchronizableAny),
SynchronizableYes: C.CFTypeRef(C.kCFBooleanTrue),
SynchronizableNo: C.CFTypeRef(C.kCFBooleanFalse),
}
type Accessible int
const (
AccessibleDefault Accessible = 0
AccessibleWhenUnlocked = 1
AccessibleAfterFirstUnlock = 2
AccessibleAlways = 3
AccessibleWhenPasscodeSetThisDeviceOnly = 4
AccessibleWhenUnlockedThisDeviceOnly = 5
AccessibleAfterFirstUnlockThisDeviceOnly = 6
AccessibleAccessibleAlwaysThisDeviceOnly = 7
)
type MatchLimit int
const (
MatchLimitDefault MatchLimit = 0
MatchLimitOne = 1
MatchLimitAll = 2
)
var MatchLimitKey = attrKey(C.CFTypeRef(C.kSecMatchLimit))
var matchTypeRef = map[MatchLimit]C.CFTypeRef{
MatchLimitOne: C.CFTypeRef(C.kSecMatchLimitOne),
MatchLimitAll: C.CFTypeRef(C.kSecMatchLimitAll),
}
var ReturnAttributesKey = attrKey(C.CFTypeRef(C.kSecReturnAttributes))
var ReturnDataKey = attrKey(C.CFTypeRef(C.kSecReturnData))
var ReturnRefKey = attrKey(C.CFTypeRef(C.kSecReturnRef))
// Item for adding, querying or deleting.
type Item struct {
// Values can be string, []byte, Convertable or CFTypeRef (constant).
attr map[string]interface{}
}
func (k *Item) SetSecClass(sc SecClass) {
k.attr[SecClassKey] = secClassTypeRef[sc]
}
func (k *Item) SetString(key string, s string) {
if s != "" {
k.attr[key] = s
} else {
delete(k.attr, key)
}
}
func (k *Item) SetService(s string) {
k.SetString(ServiceKey, s)
}
func (k *Item) SetAccount(a string) {
k.SetString(AccountKey, a)
}
func (k *Item) SetLabel(l string) {
k.SetString(LabelKey, l)
}
func (k *Item) SetData(b []byte) {
if b != nil {
k.attr[DataKey] = b
} else {
delete(k.attr, DataKey)
}
}
func (k *Item) SetAccessGroup(ag string) {
k.SetString(AccessGroupKey, ag)
}
func (k *Item) SetSynchronizable(sync Synchronizable) {
if sync != SynchronizableDefault {
k.attr[SynchronizableKey] = syncTypeRef[sync]
} else {
delete(k.attr, SynchronizableKey)
}
}
func (k *Item) SetAccessible(accessible Accessible) {
if accessible != AccessibleDefault {
k.attr[AccessibleKey] = accessibleTypeRef[accessible]
} else {
delete(k.attr, AccessibleKey)
}
}
func (k *Item) SetMatchLimit(matchLimit MatchLimit) {
if matchLimit != MatchLimitDefault {
k.attr[MatchLimitKey] = matchTypeRef[matchLimit]
} else {
delete(k.attr, MatchLimitKey)
}
}
func (k *Item) SetReturnAttributes(b bool) {
k.attr[ReturnAttributesKey] = b
}
func (k *Item) SetReturnData(b bool) {
k.attr[ReturnDataKey] = b
}
func (k *Item) SetReturnRef(b bool) {
k.attr[ReturnRefKey] = b
}
// NewItem is a new empty keychain item.
func NewItem() Item {
return Item{make(map[string]interface{})}
}
// NewGenericPassword creates a generic password item. This is a convenience method.
func NewGenericPassword(service string, account string, label string, data []byte, accessGroup string) Item {
item := NewItem()
item.SetSecClass(SecClassGenericPassword)
item.SetService(service)
item.SetAccount(account)
item.SetLabel(label)
item.SetData(data)
item.SetAccessGroup(accessGroup)
return item
}
// AddItem adds a Item
func AddItem(item Item) error {
cfDict, err := ConvertMapToCFDictionary(item.attr)
if err != nil {
return err
}
defer Release(C.CFTypeRef(cfDict))
errCode := C.SecItemAdd(cfDict, nil)
err = checkError(errCode)
return err
}
// QueryResult stores all possible results from queries.
// Not all fields are applicable all the time. Results depend on query.
type QueryResult struct {
Service string
Account string
AccessGroup string
Label string
Data []byte
}
// QueryItemRef returns query result as CFTypeRef. You must release it when you are done.
func QueryItemRef(item Item) (C.CFTypeRef, error) {
cfDict, err := ConvertMapToCFDictionary(item.attr)
if err != nil {
return nil, err
}
defer Release(C.CFTypeRef(cfDict))
var resultsRef C.CFTypeRef
errCode := C.SecItemCopyMatching(cfDict, &resultsRef)
if Error(errCode) == ErrorItemNotFound {
return nil, nil
}
err = checkError(errCode)
if err != nil {
return nil, err
}
return resultsRef, nil
}
// QueryItem returns a list of query results.
func QueryItem(item Item) ([]QueryResult, error) {
resultsRef, err := QueryItemRef(item)
if err != nil {
return nil, err
}
if resultsRef == nil {
return nil, nil
}
defer Release(resultsRef)
results := make([]QueryResult, 0, 1)
typeID := C.CFGetTypeID(resultsRef)
if typeID == C.CFArrayGetTypeID() {
arr := CFArrayToArray(C.CFArrayRef(resultsRef))
for _, ref := range arr {
typeID := C.CFGetTypeID(ref)
if typeID == C.CFDictionaryGetTypeID() {
item, err := convertResult(C.CFDictionaryRef(ref))
if err != nil {
return nil, err
}
results = append(results, *item)
} else {
return nil, fmt.Errorf("Invalid result type (If you SetReturnRef(true) you should use QueryItemRef directly).")
}
}
} else if typeID == C.CFDictionaryGetTypeID() {
item, err := convertResult(C.CFDictionaryRef(resultsRef))
if err != nil {
return nil, err
}
results = append(results, *item)
} else if typeID == C.CFDataGetTypeID() {
b, err := CFDataToBytes(C.CFDataRef(resultsRef))
if err != nil {
return nil, err
}
item := QueryResult{Data: b}
results = append(results, item)
} else {
return nil, fmt.Errorf("Invalid result type: %s", CFTypeDescription(resultsRef))
}
return results, nil
}
func attrKey(ref C.CFTypeRef) string {
return CFStringToString(C.CFStringRef(ref))
}
func convertResult(d C.CFDictionaryRef) (*QueryResult, error) {
m := CFDictionaryToMap(C.CFDictionaryRef(d))
result := QueryResult{}
for k, v := range m {
switch attrKey(k) {
case ServiceKey:
result.Service = CFStringToString(C.CFStringRef(v))
case AccountKey:
result.Account = CFStringToString(C.CFStringRef(v))
case AccessGroupKey:
result.AccessGroup = CFStringToString(C.CFStringRef(v))
case LabelKey:
result.Label = CFStringToString(C.CFStringRef(v))
case DataKey:
b, err := CFDataToBytes(C.CFDataRef(v))
if err != nil {
return nil, err
}
result.Data = b
// default:
// fmt.Printf("Unhandled key in conversion: %v = %v\n", cfTypeValue(k), cfTypeValue(v))
}
}
return &result, nil
}
// DeleteGenericPasswordItem removes a generic password item.
func DeleteGenericPasswordItem(service string, account string) error {
item := NewItem()
item.SetSecClass(SecClassGenericPassword)
item.SetService(service)
item.SetAccount(account)
return DeleteItem(item)
}
// DeleteItem removes a Item
func DeleteItem(item Item) error {
cfDict, err := ConvertMapToCFDictionary(item.attr)
if err != nil {
return err
}
defer Release(C.CFTypeRef(cfDict))
errCode := C.SecItemDelete(cfDict)
return checkError(errCode)
}
// Deprecated
func GetAccountsForService(service string) ([]string, error) {
return GetGenericPasswordAccounts(service)
}
// GetGenericPasswordAccounts returns generic password accounts for service. This is a convenience method.
func GetGenericPasswordAccounts(service string) ([]string, error) {
query := NewItem()
query.SetSecClass(SecClassGenericPassword)
query.SetService(service)
query.SetMatchLimit(MatchLimitAll)
query.SetReturnAttributes(true)
results, err := QueryItem(query)
if err != nil {
return nil, err
}
accounts := make([]string, 0, len(results))
for _, r := range results {
accounts = append(accounts, r.Account)
}
return accounts, nil
}
// GetGenericPassword returns password data for service and account. This is a convenience method.
// If item is not found returns nil, nil.
func GetGenericPassword(service string, account string, label string, accessGroup string) ([]byte, error) {
query := NewItem()
query.SetSecClass(SecClassGenericPassword)
query.SetService(service)
query.SetAccount(account)
query.SetLabel(label)
query.SetAccessGroup(accessGroup)
query.SetMatchLimit(MatchLimitOne)
query.SetReturnData(true)
results, err := QueryItem(query)
if err != nil {
return nil, err
}
if len(results) > 1 {
return nil, fmt.Errorf("Too many results")
}
if len(results) == 1 {
return results[0].Data, nil
}
return nil, nil
}
// DeleteItemRef deletes a keychain item reference.
func DeleteItemRef(ref C.CFTypeRef) error {
errCode := C.SecKeychainItemDelete(C.SecKeychainItemRef(ref))
return checkError(errCode)
}