File: security_darwin.go

package info (click to toggle)
golang-github-smallstep-crypto 0.57.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, trixie
  • size: 3,284 kB
  • sloc: sh: 53; makefile: 36
file content (465 lines) | stat: -rw-r--r-- 16,773 bytes parent folder | download | duplicates (3)
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
// Copyright (c) Smallstep Labs, Inc.
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//
// Part of this code is based on
// https://github.com/facebookincubator/sks/blob/183e7561ecedc71992f23b2d37983d2948391f4c/macos/macos.go

//nolint:gocritic // open issue https://github.com/go-critic/go-critic/issues/845
package security

/*
#cgo LDFLAGS: -framework CoreFoundation -framework Security

#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
*/
import "C"
import (
	"errors"
	"fmt"
	"unsafe"

	cf "go.step.sm/crypto/internal/darwin/corefoundation"
)

const (
	nilSecKey           C.SecKeyRef           = 0
	nilSecAccessControl C.SecAccessControlRef = 0
	nilCFString         C.CFStringRef         = 0
	nilCFData           C.CFDataRef           = 0
)

var (
	ErrNotFound      = errors.New("not found")
	ErrAlreadyExists = errors.New("already exists")
	ErrInvalidData   = errors.New("invalid data")
)

var (
	KSecAttrAccessControl                            = cf.TypeRef(C.kSecAttrAccessControl)
	KSecAttrAccessGroup                              = cf.TypeRef(C.kSecAttrAccessGroup)
	KSecAttrAccessibleWhenUnlocked                   = cf.TypeRef(C.kSecAttrAccessibleWhenUnlocked)
	KSecAttrAccessibleWhenPasscodeSetThisDeviceOnly  = cf.TypeRef(C.kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly)
	KSecAttrAccessibleWhenUnlockedThisDeviceOnly     = cf.TypeRef(C.kSecAttrAccessibleWhenUnlockedThisDeviceOnly)
	KSecAttrAccessibleAfterFirstUnlock               = cf.TypeRef(C.kSecAttrAccessibleAfterFirstUnlock)
	KSecAttrAccessibleAfterFirstUnlockThisDeviceOnly = cf.TypeRef(C.kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly)
	KSecAttrApplicationLabel                         = cf.TypeRef(C.kSecAttrApplicationLabel)
	KSecAttrApplicationTag                           = cf.TypeRef(C.kSecAttrApplicationTag)
	KSecAttrIsPermanent                              = cf.TypeRef(C.kSecAttrIsPermanent)
	KSecAttrKeyClass                                 = cf.TypeRef(C.kSecAttrKeyClass)
	KSecAttrKeyClassPrivate                          = cf.TypeRef(C.kSecAttrKeyClassPrivate)
	KSecAttrKeyClassPublic                           = cf.TypeRef(C.kSecAttrKeyClassPublic)
	KSecAttrKeySizeInBits                            = cf.TypeRef(C.kSecAttrKeySizeInBits)
	KSecAttrKeyType                                  = cf.TypeRef(C.kSecAttrKeyType)
	KSecAttrKeyTypeECSECPrimeRandom                  = cf.TypeRef(C.kSecAttrKeyTypeECSECPrimeRandom)
	KSecAttrKeyTypeRSA                               = cf.TypeRef(C.kSecAttrKeyTypeRSA)
	KSecAttrLabel                                    = cf.TypeRef(C.kSecAttrLabel)
	KSecAttrTokenID                                  = cf.TypeRef(C.kSecAttrTokenID)
	KSecAttrTokenIDSecureEnclave                     = cf.TypeRef(C.kSecAttrTokenIDSecureEnclave)
	KSecAttrSerialNumber                             = cf.TypeRef(C.kSecAttrSerialNumber)
	KSecAttrSubjectKeyID                             = cf.TypeRef(C.kSecAttrSubjectKeyID)
	KSecAttrSubject                                  = cf.TypeRef(C.kSecAttrSubject)
	KSecAttrIssuer                                   = cf.TypeRef(C.kSecAttrIssuer)
	KSecAttrSynchronizable                           = cf.TypeRef(C.kSecAttrSynchronizable)
	KSecUseDataProtectionKeychain                    = cf.TypeRef(C.kSecUseDataProtectionKeychain)
	KSecClass                                        = cf.TypeRef(C.kSecClass)
	KSecClassKey                                     = cf.TypeRef(C.kSecClassKey)
	KSecClassCertificate                             = cf.TypeRef(C.kSecClassCertificate)
	KSecClassIdentity                                = cf.TypeRef(C.kSecClassIdentity)
	KSecMatchLimit                                   = cf.TypeRef(C.kSecMatchLimit)
	KSecMatchLimitOne                                = cf.TypeRef(C.kSecMatchLimitOne)
	KSecMatchLimitAll                                = cf.TypeRef(C.kSecMatchLimitAll)
	KSecPublicKeyAttrs                               = cf.TypeRef(C.kSecPublicKeyAttrs)
	KSecPrivateKeyAttrs                              = cf.TypeRef(C.kSecPrivateKeyAttrs)
	KSecReturnRef                                    = cf.TypeRef(C.kSecReturnRef)
	KSecReturnAttributes                             = cf.TypeRef(C.kSecReturnAttributes)
	KSecValueRef                                     = cf.TypeRef(C.kSecValueRef)
	KSecValueData                                    = cf.TypeRef(C.kSecValueData)
)

type SecKeyAlgorithm = C.SecKeyAlgorithm

var (
	KSecKeyAlgorithmECDSASignatureDigestX962         = C.kSecKeyAlgorithmECDSASignatureDigestX962
	KSecKeyAlgorithmECDSASignatureDigestX962SHA256   = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA256
	KSecKeyAlgorithmECDSASignatureDigestX962SHA384   = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA384
	KSecKeyAlgorithmECDSASignatureDigestX962SHA512   = C.kSecKeyAlgorithmECDSASignatureDigestX962SHA512
	KSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256 = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA256
	KSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA384 = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA384
	KSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA512 = C.kSecKeyAlgorithmRSASignatureDigestPKCS1v15SHA512
	KSecKeyAlgorithmRSASignatureDigestPSSSHA256      = C.kSecKeyAlgorithmRSASignatureDigestPSSSHA256
	KSecKeyAlgorithmRSASignatureDigestPSSSHA384      = C.kSecKeyAlgorithmRSASignatureDigestPSSSHA384
	KSecKeyAlgorithmRSASignatureDigestPSSSHA512      = C.kSecKeyAlgorithmRSASignatureDigestPSSSHA512
	KSecKeyAlgorithmECDHKeyExchangeStandard          = C.kSecKeyAlgorithmECDHKeyExchangeStandard
)

type SecAccessControlCreateFlags = C.SecAccessControlCreateFlags

const (
	// Enable a private key to be used in signing a block of data or verifying a
	// signed block.
	KSecAccessControlPrivateKeyUsage = SecAccessControlCreateFlags(C.kSecAccessControlPrivateKeyUsage)

	// Option to use an application-provided password for data encryption key
	// generation.
	KSecAccessControlApplicationPassword = SecAccessControlCreateFlags(C.kSecAccessControlApplicationPassword)

	// Constraint to access an item with a passcode.
	KSecAccessControlDevicePasscode = SecAccessControlCreateFlags(C.kSecAccessControlDevicePasscode)

	// Constraint to access an item with Touch ID for any enrolled fingers, or
	// Face ID.
	KSecAccessControlBiometryAny = SecAccessControlCreateFlags(C.kSecAccessControlBiometryAny)

	// Constraint to access an item with Touch ID for currently enrolled
	// fingers, or from Face ID with the currently enrolled user.
	KSecAccessControlBiometryCurrentSet = SecAccessControlCreateFlags(C.kSecAccessControlBiometryCurrentSet)

	// Constraint to access an item with either biometry or passcode.
	KSecAccessControlUserPresence = SecAccessControlCreateFlags(C.kSecAccessControlUserPresence)

	// Constraint to access an item with a watch.
	KSecAccessControlWatch = SecAccessControlCreateFlags(C.kSecAccessControlWatch)

	// Indicates that all constraints must be satisfied.
	KSecAccessControlAnd = SecAccessControlCreateFlags(C.kSecAccessControlAnd)

	// Indicates that at least one constraint must be satisfied.
	KSecAccessControlOr = SecAccessControlCreateFlags(C.kSecAccessControlOr)
)

type SecKeychainItemRef struct {
	Value C.SecKeychainItemRef
}

func NewSecKeychainItemRef(ref cf.TypeRef) *SecKeychainItemRef {
	return &SecKeychainItemRef{
		Value: C.SecKeychainItemRef(ref),
	}
}

func (v *SecKeychainItemRef) Release()              { cf.Release(v) }
func (v *SecKeychainItemRef) TypeRef() cf.CFTypeRef { return cf.CFTypeRef(v.Value) }
func (v *SecKeychainItemRef) Retain()               { cf.Retain(v) }

type SecKeyRef struct {
	Value C.SecKeyRef
}

func NewSecKeyRef(ref cf.TypeRef) *SecKeyRef {
	return &SecKeyRef{
		Value: C.SecKeyRef(ref),
	}
}

func (v *SecKeyRef) Release()              { cf.Release(v) }
func (v *SecKeyRef) TypeRef() cf.CFTypeRef { return cf.CFTypeRef(v.Value) }
func (v *SecKeyRef) Retain()               { cf.Retain(v) }

type SecCertificateRef struct {
	Value C.SecCertificateRef
}

func NewSecCertificateRef(ref cf.TypeRef) *SecCertificateRef {
	return &SecCertificateRef{
		Value: C.SecCertificateRef(ref),
	}
}

func (v *SecCertificateRef) Release()              { cf.Release(v) }
func (v *SecCertificateRef) TypeRef() cf.CFTypeRef { return cf.CFTypeRef(v.Value) }

type SecAccessControlRef struct {
	ref C.SecAccessControlRef
}

func (v *SecAccessControlRef) Release()              { cf.Release(v) }
func (v *SecAccessControlRef) TypeRef() cf.CFTypeRef { return cf.CFTypeRef(v.ref) }

func SecItemAdd(attributes *cf.DictionaryRef, result *cf.TypeRef) error {
	status := C.SecItemAdd(C.CFDictionaryRef(attributes.Value), (*C.CFTypeRef)(result))
	return goOSStatus(status)
}

func SecItemUpdate(query *cf.DictionaryRef, attributesToUpdate *cf.DictionaryRef) error {
	status := C.SecItemUpdate(C.CFDictionaryRef(query.Value), C.CFDictionaryRef(attributesToUpdate.Value))
	return goOSStatus(status)
}

func SecItemDelete(query *cf.DictionaryRef) error {
	status := C.SecItemDelete(C.CFDictionaryRef(query.Value))
	return goOSStatus(status)
}

func SecItemCopyMatching(query *cf.DictionaryRef, result *cf.TypeRef) error {
	status := C.SecItemCopyMatching(C.CFDictionaryRef(query.Value), (*C.CFTypeRef)(result))
	return goOSStatus(status)
}

func SecKeyCreateRandomKey(parameters *cf.DictionaryRef) (*SecKeyRef, error) {
	var cerr C.CFErrorRef
	key := C.SecKeyCreateRandomKey(C.CFDictionaryRef(parameters.Value), &cerr)
	if err := goCFErrorRef(cerr); err != nil {
		return nil, err
	}
	return &SecKeyRef{
		Value: key,
	}, nil
}

func SecKeyCopyPublicKey(key *SecKeyRef) (*SecKeyRef, error) {
	publicKey := C.SecKeyCopyPublicKey(key.Value)
	if publicKey == nilSecKey {
		return nil, ErrNotFound
	}
	return &SecKeyRef{
		Value: publicKey,
	}, nil
}

func SecKeyCopyAttributes(key *SecKeyRef) *cf.DictionaryRef {
	attr := C.SecKeyCopyAttributes(key.Value)
	return &cf.DictionaryRef{
		Value: cf.CFDictionaryRef(attr),
	}
}

func SecKeyCopyExternalRepresentation(key *SecKeyRef) (*cf.DataRef, error) {
	var cerr C.CFErrorRef
	data := C.SecKeyCopyExternalRepresentation(key.Value, &cerr)
	if err := goCFErrorRef(cerr); err != nil {
		return nil, err
	}
	return &cf.DataRef{
		Value: cf.CFDataRef(data),
	}, nil
}

func SecAccessControlCreateWithFlags(protection cf.TypeRef, flags SecAccessControlCreateFlags) (*SecAccessControlRef, error) {
	var cerr C.CFErrorRef
	access := C.SecAccessControlCreateWithFlags(C.kCFAllocatorDefault, C.CFTypeRef(protection), flags, &cerr)
	if err := goCFErrorRef(cerr); err != nil {
		return nil, err
	}
	return &SecAccessControlRef{
		ref: access,
	}, nil
}

func SecKeyCreateSignature(key *SecKeyRef, algorithm SecKeyAlgorithm, dataToSign *cf.DataRef) (*cf.DataRef, error) {
	var cerr C.CFErrorRef
	signature := C.SecKeyCreateSignature(key.Value, algorithm, C.CFDataRef(dataToSign.Value), &cerr)
	if err := goCFErrorRef(cerr); err != nil {
		return nil, err
	}
	return &cf.DataRef{
		Value: cf.CFDataRef(signature),
	}, nil
}

func SecCertificateCopyData(cert *SecCertificateRef) (*cf.DataRef, error) {
	data := C.SecCertificateCopyData(cert.Value)
	if data == nilCFData {
		return nil, ErrInvalidData
	}
	return &cf.DataRef{
		Value: cf.CFDataRef(data),
	}, nil
}

func SecCertificateCreateWithData(certData *cf.DataRef) (*SecCertificateRef, error) {
	certRef := C.SecCertificateCreateWithData(C.kCFAllocatorDefault, C.CFDataRef(certData.Value))
	if certRef == 0 {
		return nil, ErrInvalidData
	}
	return &SecCertificateRef{
		Value: certRef,
	}, nil
}

func SecKeyCreateWithData(keyData *cf.DataRef, attributes *cf.DictionaryRef) (*SecKeyRef, error) {
	var cerr C.CFErrorRef
	keyRef := C.SecKeyCreateWithData(C.CFDataRef(keyData.Value), C.CFDictionaryRef(attributes.Value), &cerr)
	if err := goCFErrorRef(cerr); err != nil {
		return nil, err
	}
	return &SecKeyRef{
		Value: keyRef,
	}, nil
}

func SecKeyCopyKeyExchangeResult(privateKey *SecKeyRef, algorithm SecKeyAlgorithm, publicKey *SecKeyRef, parameters *cf.DictionaryRef) (*cf.DataRef, error) {
	var cerr C.CFErrorRef
	dataRef := C.SecKeyCopyKeyExchangeResult(privateKey.Value, algorithm, publicKey.Value, C.CFDictionaryRef(parameters.Value), &cerr)
	if err := goCFErrorRef(cerr); err != nil {
		return nil, err
	}
	return &cf.DataRef{
		Value: cf.CFDataRef(dataRef),
	}, nil
}

func SecCopyErrorMessageString(status C.OSStatus) *cf.StringRef {
	s := C.SecCopyErrorMessageString(status, nil)
	return &cf.StringRef{
		Value: cf.CFStringRef(s),
	}
}

func GetSecAttrApplicationLabel(v *cf.DictionaryRef) []byte {
	data := C.CFDataRef(C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecAttrApplicationLabel)))
	return goBytes(data)
}

func GetSecAttrApplicationTag(v *cf.DictionaryRef) string {
	data := C.CFDataRef(C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecAttrApplicationTag)))
	return string(goBytes(data))
}

func GetSecAttrLabel(v *cf.DictionaryRef) string {
	ref := C.CFStringRef(C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecAttrLabel)))
	return goString(ref)
}

func GetSecAttrTokenID(v *cf.DictionaryRef) string {
	ref := C.CFStringRef(C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecAttrTokenID)))
	return goString(ref)
}

func GetSecAttrAccessControl(v *cf.DictionaryRef) *SecAccessControlRef {
	var keyAttributes unsafe.Pointer
	tokenID := GetSecAttrTokenID(v)
	if tokenID == "com.apple.setoken" {
		keyAttributes = C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecPrivateKeyAttrs))
	} else {
		keyAttributes = C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecPublicKeyAttrs))
	}
	if keyAttributes == nil {
		return nil
	}

	dv := C.CFDictionaryGetValue(C.CFDictionaryRef(keyAttributes), unsafe.Pointer(C.kSecAttrAccessControl))
	if dv == nil {
		return nil
	}

	ref := &SecAccessControlRef{
		ref: C.SecAccessControlRef(dv),
	}

	return ref
}

func GetSecValueData(v *cf.DictionaryRef) []byte {
	data := C.CFDataRef(C.CFDictionaryGetValue(C.CFDictionaryRef(v.Value), unsafe.Pointer(C.kSecValueData)))
	return goBytes(data)
}

type osStatusError struct {
	code    int
	message string
}

func (e osStatusError) Error() string {
	if e.message == "" {
		return fmt.Sprintf("OSStatus %d: unknown error", e.code)
	}
	return fmt.Sprintf("OSStatus %d: %s", e.code, e.message)
}

func goOSStatus(status C.OSStatus) error {
	switch status {
	case 0:
		return nil
	case C.errSecItemNotFound: // -25300
		return ErrNotFound
	case C.errSecDuplicateItem: // -25299
		return ErrAlreadyExists
	}

	var message string
	if ref := SecCopyErrorMessageString(status); ref.Value != 0 {
		message = goString(C.CFStringRef(ref.Value))
		defer ref.Release()
	}
	return osStatusError{
		code:    int(status),
		message: message,
	}
}

func goBytes(data C.CFDataRef) []byte {
	if data == 0 {
		return nil
	}
	return C.GoBytes(
		unsafe.Pointer(C.CFDataGetBytePtr(data)),
		C.int(C.CFDataGetLength(data)),
	)
}

func goString(ref C.CFStringRef) string {
	if ref == 0 {
		return ""
	}

	// CFStringGetCStringPtr either returns the requested pointer immediately,
	// with no memory allocations and no copying, in constant time, or returns
	// NULL.
	if cstr := C.CFStringGetCStringPtr(ref, C.kCFStringEncodingUTF8); cstr != nil {
		return C.GoString(cstr)
	}

	// The documentation recommends using CFStringGetCString if the previous one
	// fails.
	length := C.CFStringGetLength(ref)
	buf := (*C.char)(C.malloc(C.size_t(length) + 1))
	defer C.free(unsafe.Pointer(buf))

	if C.CFStringGetCString(ref, buf, length+1, C.kCFStringEncodingUTF8) == 0 {
		return ""
	}

	return C.GoString(buf)
}

type cfError struct {
	code    int
	message string
}

func (e cfError) Error() string {
	if e.message == "" {
		return fmt.Sprintf("CFError %d: unknown error", e.code)
	}
	return fmt.Sprintf("CFError %d: %s", e.code, e.message)
}

func goCFErrorRef(ref C.CFErrorRef) error {
	if ref == 0 {
		return nil
	}
	var message string
	if desc := C.CFErrorCopyDescription(ref); desc != nilCFString {
		defer C.CFRelease(C.CFTypeRef(desc))
		if cstr := C.CFStringGetCStringPtr(desc, C.kCFStringEncodingUTF8); cstr != nil {
			message = C.GoString(cstr)
		}
	}
	return &cfError{
		code:    int(C.CFErrorGetCode(ref)),
		message: message,
	}
}