File: mackms.go

package info (click to toggle)
golang-github-smallstep-crypto 0.63.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 3,800 kB
  • sloc: sh: 66; makefile: 50
file content (1254 lines) | stat: -rw-r--r-- 36,684 bytes parent folder | download
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
//go:build darwin && cgo && !nomackms

// 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

package mackms

import (
	"bytes"
	"context"
	"crypto"
	"crypto/ecdh"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/x509"
	"encoding/hex"
	"errors"
	"fmt"
	"math/big"
	"net/url"
	"strings"

	cf "go.step.sm/crypto/internal/darwin/corefoundation"
	"go.step.sm/crypto/internal/darwin/security"
	"go.step.sm/crypto/kms/apiv1"
	"go.step.sm/crypto/kms/uri"
)

// Scheme is the scheme used in uris, the string "mackms".
const Scheme = string(apiv1.MacKMS)

// DefaultTag is the default tag attribute (kSecAttrApplicationTag) added to all
// the keys.
var DefaultTag = "com.smallstep.crypto"

type keyAttributes struct {
	label            string
	tag              string
	hash             []byte
	retry            bool
	useSecureEnclave bool
	useBiometrics    bool
	sigAlgorithm     apiv1.SignatureAlgorithm
	keySize          int
}

// retryAttributes returns the original URI attributes used to get a private
// key, but only if they are different that the ones set. It will return nil, if
// they are the same. The only attribute that can change is the tag. This method
// would return the tag empty if it was set using the default value.
func (k *keyAttributes) retryAttributes() *keyAttributes {
	if !k.retry {
		return nil
	}
	return &keyAttributes{
		label: k.label,
		hash:  k.hash,
		retry: false,
	}
}

type keySearchAttributes struct {
	label            string
	tag              string
	hash             []byte
	secureEnclaveSet bool
	useSecureEnclave bool
}

type certAttributes struct {
	label        string
	serialNumber *big.Int
}

type algorithmAttributes struct {
	Type string
	Size int
}

var signatureAlgorithmMapping = map[apiv1.SignatureAlgorithm]algorithmAttributes{
	apiv1.UnspecifiedSignAlgorithm: {"EC", 256},
	apiv1.SHA256WithRSA:            {"RSA", 3072},
	apiv1.SHA384WithRSA:            {"RSA", 3072},
	apiv1.SHA512WithRSA:            {"RSA", 3072},
	apiv1.SHA256WithRSAPSS:         {"RSA", 3072},
	apiv1.SHA384WithRSAPSS:         {"RSA", 3072},
	apiv1.SHA512WithRSAPSS:         {"RSA", 3072},
	apiv1.ECDSAWithSHA256:          {"EC", 256},
	apiv1.ECDSAWithSHA384:          {"EC", 384},
	apiv1.ECDSAWithSHA512:          {"EC", 521},
}

// MacKMS is a key manager that uses keys stored in macOS Keychain or in the
// Secure Enclave.
//
// CreateKey methods can create keys with the following URIs:
//   - mackms:label=my-name
//   - mackms:label=my-name;tag=com.smallstep.crypto
//   - mackms;label=my-name;tag=
//   - mackms;label=my-name;se=true;bio=true
//
// GetPublicKey and CreateSigner accepts the above URIs as well as the following
// ones:
//   - my-name
//   - mackms:label=my-name;tag=com.smallstep.crypto;hash=ccb792f9d9a1262bfb814a339876f825bdba1261
//
// The above URIs support the following attributes:
//   - "label" corresponds with Apple's kSecAttrLabel. It is always required and
//     represents the key name. You will be able to see the keys in the Keychain,
//     looking for the value.
//   - "tag" corresponds with kSecAttrApplicationTag. It defaults to
//     com.smallstep.crypto. If tag is an empty string ("tag="), the attribute
//     will not be set.
//   - "se" is a boolean. If set to true, it will store the key in the
//     Secure Enclave. This option requires the application to be code-signed
//     with the appropriate entitlements.
//   - "bio" is a boolean value. If set to true, sign and verify operations
//     require Touch ID or Face ID. This options requires the key to be in the
//     Secure Enclave.
//   - "hash" corresponds with kSecAttrApplicationLabel. It is the SHA-1 of the
//     DER representation of an RSA public key using the PKCS #1 format or the
//     SHA-1 of the uncompressed ECDSA point according to SEC 1, Version 2.0,
//     Section 2.3.4.
type MacKMS struct{}

// New returns a new SoftKMS.
func New(context.Context, apiv1.Options) (*MacKMS, error) {
	return &MacKMS{}, nil
}

func init() {
	apiv1.Register(apiv1.MacKMS, func(ctx context.Context, opts apiv1.Options) (apiv1.KeyManager, error) {
		return New(ctx, opts)
	})
}

// Close is a noop that just returns nil.
func (k *MacKMS) Close() error {
	return nil
}

// GetPublicKey returns the public key from the given URI in the request name.
func (k *MacKMS) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
	if req.Name == "" {
		return nil, fmt.Errorf("getPublicKeyRequest 'name' cannot be empty")
	}

	u, err := parseURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("mackms GetPublicKey failed: %w", err)
	}

	key, err := getPrivateKey(u)
	if err != nil {
		return nil, fmt.Errorf("mackms GetPublicKey failed: %w", apiv1Error(err))
	}
	defer key.Release()

	pub, _, err := extractPublicKey(key)
	if err != nil {
		return nil, fmt.Errorf("mackms GetPublicKey failed: %w", err)
	}

	return pub, nil
}

// CreateKey generates a new key on the Keychain or Secure Enclave using the
// Apple Security framework.
func (k *MacKMS) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
	if req.Name == "" {
		return nil, fmt.Errorf("createKeyRequest 'name' cannot be empty")
	}

	u, err := parseURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
	}

	alg, ok := signatureAlgorithmMapping[req.SignatureAlgorithm]
	if !ok {
		return nil, fmt.Errorf("createKeyRequest 'signatureAlgorithm=%q' is not supported", req.SignatureAlgorithm)
	}
	if u.useSecureEnclave && req.SignatureAlgorithm != apiv1.UnspecifiedSignAlgorithm && req.SignatureAlgorithm != apiv1.ECDSAWithSHA256 {
		return nil, fmt.Errorf("createKeyRequest 'signatureAlgorithm=%q' is not supported on Secure Enclave", req.SignatureAlgorithm)
	}

	u.sigAlgorithm = req.SignatureAlgorithm
	if alg.Type == "RSA" && req.Bits > 0 {
		u.keySize = req.Bits
	} else {
		u.keySize = alg.Size
	}

	// Define key attributes
	cfLabel, err := cf.NewString(u.label)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
	}
	defer cfLabel.Release()

	keyAttributesDict := cf.Dictionary{
		security.KSecAttrIsPermanent: cf.True,
	}
	if u.tag != "" {
		cfTag, err := cf.NewData([]byte(u.tag))
		if err != nil {
			return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
		}
		defer cfTag.Release()
		keyAttributesDict[security.KSecAttrApplicationTag] = cfTag
	}
	if u.useSecureEnclave {
		// After the first unlock, the data remains accessible until the next
		// restart. This is recommended for items that need to be accessed by
		// background applications. Items with this attribute do not migrate to
		// a new device. Thus, after restoring from a backup of a different
		// device, these items will not be present.
		//
		// TODO: make this a configuration option
		flags := security.KSecAccessControlPrivateKeyUsage
		if u.useBiometrics {
			flags |= security.KSecAccessControlAnd
			flags |= security.KSecAccessControlBiometryCurrentSet
		}
		access, err := security.SecAccessControlCreateWithFlags(
			security.KSecAttrAccessibleWhenUnlockedThisDeviceOnly,
			flags,
		)
		if err != nil {
			return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
		}
		defer access.Release()
		keyAttributesDict[security.KSecAttrAccessControl] = access
	}

	keyAttributes, err := cf.NewDictionary(keyAttributesDict)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
	}
	defer keyAttributes.Release()

	bits := cf.NewNumber(u.keySize)
	defer bits.Release()

	// Define key attributes
	attrsDict := cf.Dictionary{
		security.KSecAttrLabel:         cfLabel,
		security.KSecAttrKeySizeInBits: bits,
		security.KSecPrivateKeyAttrs:   keyAttributes,
	}
	if u.useSecureEnclave {
		attrsDict[security.KSecAttrTokenID] = security.KSecAttrTokenIDSecureEnclave
	} else {
		attrsDict[security.KSecPublicKeyAttrs] = keyAttributes
	}

	switch u.sigAlgorithm {
	case apiv1.UnspecifiedSignAlgorithm:
		attrsDict[security.KSecAttrKeyType] = security.KSecAttrKeyTypeECSECPrimeRandom
	case apiv1.ECDSAWithSHA256, apiv1.ECDSAWithSHA384, apiv1.ECDSAWithSHA512:
		attrsDict[security.KSecAttrKeyType] = security.KSecAttrKeyTypeECSECPrimeRandom
	case apiv1.SHA256WithRSA, apiv1.SHA384WithRSA, apiv1.SHA512WithRSA:
		attrsDict[security.KSecAttrKeyType] = security.KSecAttrKeyTypeRSA
	case apiv1.SHA256WithRSAPSS, apiv1.SHA384WithRSAPSS, apiv1.SHA512WithRSAPSS:
		attrsDict[security.KSecAttrKeyType] = security.KSecAttrKeyTypeRSA
	default:
		return nil, fmt.Errorf("mackms CreateKey failed: unsupported signature algorithm %s", u.sigAlgorithm)
	}

	attrs, err := cf.NewDictionary(attrsDict)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
	}
	defer attrs.Release()

	secKeyRef, err := security.SecKeyCreateRandomKey(attrs)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateKey failed: %w", apiv1Error(err))
	}
	defer secKeyRef.Release()

	pub, hash, err := extractPublicKey(secKeyRef)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateKey failed: %w", err)
	}

	name := uri.New(Scheme, url.Values{
		"label": []string{u.label},
		"tag":   []string{u.tag},
		"hash":  []string{hex.EncodeToString(hash)},
	})
	if u.useSecureEnclave {
		name.Values.Set("se", "true")
	}
	if u.useBiometrics {
		name.Values.Set("bio", "true")
	}

	return &apiv1.CreateKeyResponse{
		Name:      name.String(),
		PublicKey: pub,
		CreateSignerRequest: apiv1.CreateSignerRequest{
			SigningKey: name.String(),
		},
	}, nil
}

// CreateSigner returns a new [crypto.Signer] from the given URI in the request
// signing key.
func (k *MacKMS) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
	if req.SigningKey == "" {
		return nil, fmt.Errorf("createSignerRequest 'signingKey' cannot be empty")
	}

	u, err := parseURI(req.SigningKey)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateSigner failed: %w", err)
	}

	key, err := getPrivateKey(u)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateSigner failed: %w", apiv1Error(err))
	}
	defer key.Release()

	pub, _, err := extractPublicKey(key)
	if err != nil {
		return nil, fmt.Errorf("mackms CreateSigner failed: %w", err)
	}

	return &Signer{
		keyAttributes: u,
		pub:           pub,
	}, nil
}

// LoadCertificate returns an x509.Certificate by its label and/or serial
// number. By default Apple Keychain will use the certificate common name as the
// label.
//
// Valid names (URIs) are:
//   - mackms:label=test@example.com
//   - mackms:serial=2c273934eda8454d2595a94497e2395a
//   - mackms:label=test@example.com;serial=2c273934eda8454d2595a94497e2395a
func (k *MacKMS) LoadCertificate(req *apiv1.LoadCertificateRequest) (*x509.Certificate, error) {
	if req.Name == "" {
		return nil, fmt.Errorf("loadCertificateRequest 'name' cannot be empty")
	}

	// Require label or serial
	u, err := parseCertURI(req.Name, true)
	if err != nil {
		return nil, fmt.Errorf("mackms LoadCertificate failed: %w", err)
	}

	cert, err := loadCertificate(u.label, u.serialNumber, nil)
	if err != nil {
		return nil, fmt.Errorf("mackms LoadCertificate failed: %w", apiv1Error(err))
	}

	return cert, nil
}

// StoreCertificate stores a certificate in the Apple Keychain. There is no need
// to provide a label in the URI as Apple will use the CommonName as the default
// label, but if one is provided, the certificate in the Keychain will be
// updated with the given label:
//
// Valid names (URIs) are:
//   - "" will use the common name as the label
//   - "mackms:" will use the common name
//   - "mackms:label=my-label" will use "my-label"
//   - "mackms:my-label" will use the "my-label"
func (k *MacKMS) StoreCertificate(req *apiv1.StoreCertificateRequest) error {
	// There's not really need to require the name as macOS will use the common
	// name as default.
	if req.Certificate == nil {
		return fmt.Errorf("storeCertificateRequest 'certificate' cannot be empty")
	}

	// Do not require any parameter. Using mackms: is allowed as macOS will set
	// the commonName as label.
	u, err := parseCertURI(req.Name, false)
	if err != nil {
		return fmt.Errorf("mackms StoreCertificate failed: %w", err)
	}

	// Store the certificate and update the label if required
	if err := storeCertificate(u.label, req.Certificate); err != nil {
		return fmt.Errorf("mackms StoreCertificate failed: %w", apiv1Error(err))
	}

	return nil
}

// LoadCertificateChain returns the leaf certificate by label and/or serial
// number and its intermediate certificates. By default Apple Keychain will use
// the certificate common name as the label.
//
// Valid names (URIs) are:
//   - mackms:label=test@example.com
//   - mackms:serial=2c273934eda8454d2595a94497e2395a
//   - mackms:label=test@example.com;serial=2c273934eda8454d2595a94497e2395a
func (k *MacKMS) LoadCertificateChain(req *apiv1.LoadCertificateChainRequest) ([]*x509.Certificate, error) {
	if req.Name == "" {
		return nil, fmt.Errorf("loadCertificateChainRequest 'name' cannot be empty")
	}

	// Require label or serial
	u, err := parseCertURI(req.Name, true)
	if err != nil {
		return nil, fmt.Errorf("mackms LoadCertificateChain failed: %w", err)
	}

	cert, err := loadCertificate(u.label, u.serialNumber, nil)
	if err != nil {
		return nil, fmt.Errorf("mackms LoadCertificateChain failed: %w", apiv1Error(err))
	}

	chain := []*x509.Certificate{cert}
	if isSelfSigned(cert) {
		return chain, nil
	}

	// Look for the rest of intermediates skipping the root.
	for {
		// The Keychain stores the subject as an attribute, but it saves some of
		// the values in uppercase. We cannot use the cert.RawIssuer to restrict
		// more the search with KSecAttrSubjectKeyID and kSecAttrSubject. To do
		// it we will need to "normalize" the subject it in the same way.
		parent, err := loadCertificate("", nil, cert.AuthorityKeyId)
		if err != nil || isSelfSigned(parent) || cert.CheckSignatureFrom(parent) != nil {
			break
		}
		cert = parent
		chain = append(chain, cert)
	}

	//nolint:nilerr // return only the intermediates present in keychain
	return chain, nil
}

// StoreCertificateChain stores a certificate chain in the Apple Keychain. There
// is no need to provide a label in the URI as Apple will use the CommonName as
// the default label, but if one is provided, the leaf certificate in the
// Keychain will be updated with the given label:
//
// Valid names (URIs) are:
//   - "" will use the common name as the label
//   - "mackms:" will use the common name
//   - "mackms:label=my-label" will use "my-label"
//   - "mackms:my-label" will use the "my-label"
func (k *MacKMS) StoreCertificateChain(req *apiv1.StoreCertificateChainRequest) error {
	// There's not really need to require the name as macOS will use the common
	// name as default.
	if len(req.CertificateChain) == 0 {
		return fmt.Errorf("storeCertificateChainRequest 'certificateChain' cannot be empty")
	}

	// Do not require any parameter. Using mackms: is allowed as macOS will set
	// the commonName as label.
	u, err := parseCertURI(req.Name, false)
	if err != nil {
		return fmt.Errorf("mackms StoreCertificateChain failed: %w", err)
	}

	// Store the certificate and update the label if required
	if err := storeCertificate(u.label, req.CertificateChain[0]); err != nil {
		return fmt.Errorf("mackms StoreCertificateChain failed: %w", apiv1Error(err))
	}

	// Store the rest of the chain but do not fail if already exists
	for _, cert := range req.CertificateChain[1:] {
		if err := storeCertificate("", cert); err != nil && !errors.Is(err, security.ErrAlreadyExists) {
			return fmt.Errorf("mackms StoreCertificateChain failed: %w", err)
		}
	}

	return nil
}

// DeleteKey deletes the key referenced by the URI in the request name.
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a later
// release.
func (*MacKMS) DeleteKey(req *apiv1.DeleteKeyRequest) error {
	if req.Name == "" {
		return fmt.Errorf("deleteKeyRequest 'name' cannot be empty")
	}

	u, err := parseURI(req.Name)
	if err != nil {
		return fmt.Errorf("mackms DeleteKey failed: %w", err)
	}

	cfLabel, err := cf.NewString(u.label)
	if err != nil {
		return fmt.Errorf("mackms DeleteKey failed: %w", err)
	}
	defer cfLabel.Release()

	for _, keyClass := range []cf.TypeRef{security.KSecAttrKeyClassPublic, security.KSecAttrKeyClassPrivate} {
		dict := cf.Dictionary{
			security.KSecClass:        security.KSecClassKey,
			security.KSecAttrLabel:    cfLabel,
			security.KSecAttrKeyClass: keyClass,
		}
		if u.tag != "" {
			cfTag, err := cf.NewData([]byte(u.tag))
			if err != nil {
				return fmt.Errorf("mackms DeleteKey failed: %w", err)
			}
			defer cfTag.Release() //nolint:gocritic // only two iterations
			dict[security.KSecAttrApplicationTag] = cfTag
		}
		// Extract logic to deleteItem to avoid defer on loops
		if err := deleteItem(dict, u.hash); err != nil {
			return fmt.Errorf("mackms DeleteKey failed: %w", apiv1Error(err))
		}
	}

	return nil
}

// DeleteCertificate deletes the certificate referenced by the URI in the
// request name.
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a later
// release.
func (*MacKMS) DeleteCertificate(req *apiv1.DeleteCertificateRequest) error {
	if req.Name == "" {
		return fmt.Errorf("deleteCertificateRequest 'name' cannot be empty")
	}

	u, err := parseCertURI(req.Name, true)
	if err != nil {
		return fmt.Errorf("mackms DeleteCertificate failed: %w", err)
	}

	query := cf.Dictionary{
		security.KSecClass: security.KSecClassCertificate,
	}
	if u.label != "" {
		cfLabel, err := cf.NewString(u.label)
		if err != nil {
			return fmt.Errorf("mackms DeleteCertificate failed: %w", err)
		}
		defer cfLabel.Release()
		query[security.KSecAttrLabel] = cfLabel
	}
	if u.serialNumber != nil {
		cfSerial, err := cf.NewData(encodeSerialNumber(u.serialNumber))
		if err != nil {
			return fmt.Errorf("mackms DeleteCertificate failed: %w", err)
		}
		defer cfSerial.Release()
		query[security.KSecAttrSerialNumber] = cfSerial
	}

	if err := deleteItem(query, nil); err != nil {
		return fmt.Errorf("mackms DeleteCertificate failed: %w", apiv1Error(err))
	}

	return nil
}

// SearchKeys searches for keys according to the query URI in the request. By default,
// all keys managed by the KMS using the default tag, and both Secure Enclave as well as
// non-Secure Enclave keys will be returned.
//
//   - "" will return all keys managed by the KMS (using the default tag)
//   - "mackms:" will return all keys managed by the KMS  (using the default tag)
//   - "mackms:label=my-label" will return all keys using label "my-label" (and the default tag)
//   - "mackms:hash=the-hash" will return all keys having hash "hash" (and the default tag; generally one result)
//   - "mackms:tag=my-tag" will search for all keys with "my-tag"
//   - "mackms:se=true" will return all Secure Enclave keys managed by the KMS (using the default tag)
//   - "mackms:se=false" will return all non-Secure Enclave keys managed by the KMS (using the default tag)
//
// # Experimental
//
// Notice: This API is EXPERIMENTAL and may be changed or removed in a later
// release.
func (k *MacKMS) SearchKeys(req *apiv1.SearchKeysRequest) (*apiv1.SearchKeysResponse, error) {
	if req.Query == "" {
		return nil, fmt.Errorf("searchKeysRequest 'query' cannot be empty")
	}

	u, err := parseSearchURI(req.Query)
	if err != nil {
		return nil, fmt.Errorf("failed parsing query: %w", err)
	}

	keys, err := getPrivateKeys(u)
	if err != nil {
		return nil, fmt.Errorf("failed getting keys: %w", err)
	}

	results := make([]apiv1.SearchKeyResult, len(keys))
	for i, key := range keys {
		d := cf.NewDictionaryRef(cf.TypeRef(key.TypeRef()))
		var (
			hash    = security.GetSecAttrApplicationLabel(d)
			label   = security.GetSecAttrLabel(d)
			tag     = security.GetSecAttrApplicationTag(d)
			tokenID = security.GetSecAttrTokenID(d)
		)
		d.Release()

		name := uri.New(Scheme, url.Values{})
		name.Values.Set("hash", hex.EncodeToString(hash))
		name.Values.Set("label", label)
		name.Values.Set("tag", tag)

		keyInSecureEnclave := tokenID == "com.apple.setoken" //nolint:gosec // this is not a credential
		switch {
		case !u.secureEnclaveSet && keyInSecureEnclave:
			name.Values.Set("se", "true")
		case !u.secureEnclaveSet && !keyInSecureEnclave:
			name.Values.Set("se", "false")
		case u.useSecureEnclave && keyInSecureEnclave:
			name.Values.Set("se", "true")
		case !u.useSecureEnclave && !keyInSecureEnclave:
			name.Values.Set("se", "false")
		default:
			// skip in case the query doesn't match the actual property
			continue
		}

		// obtain the public key by requesting it, as the current
		// representation of the key includes just the attributes.
		pub, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
			Name: name.String(),
		})
		if err != nil {
			return nil, fmt.Errorf("failed getting public key: %w", err)
		}

		results[i] = apiv1.SearchKeyResult{
			Name:      name.String(),
			PublicKey: pub,
			CreateSignerRequest: apiv1.CreateSignerRequest{
				SigningKey: name.String(),
			},
		}
	}

	return &apiv1.SearchKeysResponse{
		Results: results,
	}, nil
}

var _ apiv1.SearchableKeyManager = (*MacKMS)(nil)

func deleteItem(dict cf.Dictionary, hash []byte) error {
	if len(hash) > 0 {
		d, err := cf.NewData(hash)
		if err != nil {
			return err
		}
		defer d.Release()
		dict[security.KSecAttrApplicationLabel] = d
	}

	query, err := cf.NewDictionary(dict)
	if err != nil {
		return err
	}
	defer query.Release()

	if err := security.SecItemDelete(query); err != nil {
		if dict[security.KSecAttrKeyClass] == security.KSecAttrKeyClassPublic && errors.Is(err, security.ErrNotFound) {
			return nil
		}
		return err
	}

	return nil
}

func getPrivateKey(u *keyAttributes) (*security.SecKeyRef, error) {
	cfLabel, err := cf.NewString(u.label)
	if err != nil {
		return nil, err
	}
	defer cfLabel.Release()

	dict := cf.Dictionary{
		security.KSecClass:        security.KSecClassKey,
		security.KSecAttrLabel:    cfLabel,
		security.KSecAttrKeyClass: security.KSecAttrKeyClassPrivate,
		security.KSecReturnRef:    cf.True,
		security.KSecMatchLimit:   security.KSecMatchLimitOne,
	}
	if u.tag != "" {
		cfTag, err := cf.NewData([]byte(u.tag))
		if err != nil {
			return nil, err
		}
		defer cfTag.Release()
		dict[security.KSecAttrApplicationTag] = cfTag
	}
	if len(u.hash) > 0 {
		d, err := cf.NewData(u.hash)
		if err != nil {
			return nil, err
		}
		defer d.Release()
		dict[security.KSecAttrApplicationLabel] = d
	}

	// Get the query from the keychain
	query, err := cf.NewDictionary(dict)
	if err != nil {
		return nil, err
	}
	defer query.Release()

	var key cf.TypeRef
	if err := security.SecItemCopyMatching(query, &key); err != nil {
		// If not found retry without the tag if it wasn't set.
		if errors.Is(err, security.ErrNotFound) {
			if ru := u.retryAttributes(); ru != nil {
				return getPrivateKey(ru)
			}
		}
		return nil, fmt.Errorf("macOS SecItemCopyMatching failed: %w", err)
	}
	return security.NewSecKeyRef(key), nil
}

func getPrivateKeys(u *keySearchAttributes) ([]*security.SecKeychainItemRef, error) {
	dict := cf.Dictionary{
		security.KSecClass:            security.KSecClassKey,
		security.KSecAttrKeyClass:     security.KSecAttrKeyClassPrivate,
		security.KSecReturnAttributes: cf.True, // return keychain attributes, i.e. tag and label
		security.KSecMatchLimit:       security.KSecMatchLimitAll,
	}

	if u.tag != "" {
		cfTag, err := cf.NewData([]byte(u.tag))
		if err != nil {
			return nil, err
		}
		defer cfTag.Release()
		dict[security.KSecAttrApplicationTag] = cfTag
	}
	if u.label != "" {
		cfLabel, err := cf.NewString(u.label)
		if err != nil {
			return nil, err
		}
		defer cfLabel.Release()
		dict[security.KSecAttrLabel] = cfLabel
	}
	if len(u.hash) > 0 {
		cfHash, err := cf.NewData(u.hash)
		if err != nil {
			return nil, err
		}
		defer cfHash.Release()
		dict[security.KSecAttrApplicationLabel] = cfHash
	}

	// construct the query
	query, err := cf.NewDictionary(dict)
	if err != nil {
		return nil, err
	}
	defer query.Release()

	// perform the query
	var result cf.TypeRef
	err = security.SecItemCopyMatching(query, &result)
	if err != nil {
		if errors.Is(err, security.ErrNotFound) {
			return []*security.SecKeychainItemRef{}, nil
		}
		return nil, fmt.Errorf("macOS SecItemCopyMatching failed: %w", err)
	}

	array := cf.NewArrayRef(result)
	defer array.Release()

	keys := make([]*security.SecKeychainItemRef, array.Len())
	for i := 0; i < array.Len(); i++ {
		item := array.Get(i)
		key := security.NewSecKeychainItemRef(item)
		key.Retain() // retain the key, so that it's not released early
		keys[i] = key
	}

	return keys, nil
}

func extractPublicKey(secKeyRef *security.SecKeyRef) (crypto.PublicKey, []byte, error) {
	// Get the hash of the public key. We can also calculate this from the
	// external representation below, but in case Apple decides to switch from
	// SHA-1, let's just use what macOS sets by default.
	attrs := security.SecKeyCopyAttributes(secKeyRef)
	defer attrs.Release()
	hash := security.GetSecAttrApplicationLabel(attrs)

	// Attempt to extract the public key, it will fail if the app that created
	// the private key didn’t also store the corresponding public key in the
	// keychain, or if the system can’t reconstruct the corresponding public
	// key.
	if publicKey, err := security.SecKeyCopyPublicKey(secKeyRef); err == nil {
		defer publicKey.Release()

		// For an unknown reason this sometimes fails with the error -25293
		// (errSecAuthFailed). If this happens attempt to extract the key from
		// the private key.
		if data, err := security.SecKeyCopyExternalRepresentation(publicKey); err == nil {
			defer data.Release()

			derBytes := data.Bytes()
			// ECDSA public keys are formatted as "04 || X || Y"
			if derBytes[0] == 0x04 {
				pub, err := parseECDSAPublicKey(derBytes)
				if err != nil {
					return nil, nil, fmt.Errorf("error parsing ECDSA key: %w", err)
				}
				return pub, hash, nil
			}

			// RSA public keys are formatted using PKCS #1
			pub, err := x509.ParsePKCS1PublicKey(derBytes)
			if err != nil {
				return nil, nil, fmt.Errorf("error parsing RSA key: %w", err)
			}

			return pub, hash, nil
		}
	}

	// At this point we only have the private key.
	data, err := security.SecKeyCopyExternalRepresentation(secKeyRef)
	if err != nil {
		return nil, nil, fmt.Errorf("macOS SecKeyCopyExternalRepresentation failed: %w", err)
	}
	defer data.Release()

	derBytes := data.Bytes()

	// ECDSA private keys are formatted as "04 || X || Y || K"
	if derBytes[0] == 0x04 {
		pub, err := parseECDSAPrivateKey(derBytes)
		if err != nil {
			return nil, nil, fmt.Errorf("error parsing ECDSA key: %w", err)
		}
		return pub, hash, nil
	}

	// RSA private keys are formatted using PKCS #1
	priv, err := x509.ParsePKCS1PrivateKey(derBytes)
	if err != nil {
		return nil, nil, fmt.Errorf("error parsing key: %w", err)
	}
	return priv.Public(), hash, nil
}

// isSelfSigned checks if a certificate is self signed. The algorithm looks like this:
//
//	If subject != issuer: false
//	ElseIf subjectKeyID != authorityKey: false
//	ElseIf checkSignature: true
//	Otherwise: false
func isSelfSigned(cert *x509.Certificate) bool {
	if bytes.Equal(cert.RawSubject, cert.RawIssuer) {
		if cert.SubjectKeyId != nil && cert.AuthorityKeyId != nil && !bytes.Equal(cert.SubjectKeyId, cert.AuthorityKeyId) {
			return false
		}

		return cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature) == nil
	}

	return false
}

func loadCertificate(label string, serialNumber *big.Int, subjectKeyID []byte) (*x509.Certificate, error) {
	query := cf.Dictionary{
		security.KSecClass: security.KSecClassCertificate,
	}
	if label != "" {
		cfLabel, err := cf.NewString(label)
		if err != nil {
			return nil, err
		}
		defer cfLabel.Release()
		query[security.KSecAttrLabel] = cfLabel
	}
	if serialNumber != nil {
		cfSerial, err := cf.NewData(encodeSerialNumber(serialNumber))
		if err != nil {
			return nil, err
		}
		defer cfSerial.Release()
		query[security.KSecAttrSerialNumber] = cfSerial
	}
	if subjectKeyID != nil {
		cfSubjectKeyID, err := cf.NewData(subjectKeyID)
		if err != nil {
			return nil, err
		}
		defer cfSubjectKeyID.Release()
		query[security.KSecAttrSubjectKeyID] = cfSubjectKeyID
	}

	cfQuery, err := cf.NewDictionary(query)
	if err != nil {
		return nil, err
	}
	defer cfQuery.Release()

	var ref cf.TypeRef
	if err := security.SecItemCopyMatching(cfQuery, &ref); err != nil {
		return nil, err
	}
	defer ref.Release()

	data, err := security.SecCertificateCopyData(security.NewSecCertificateRef(ref))
	if err != nil {
		return nil, err
	}
	defer data.Release()

	cert, err := x509.ParseCertificate(data.Bytes())
	if err != nil {
		return nil, err
	}

	return cert, nil
}

func storeCertificate(label string, cert *x509.Certificate) error {
	cfData, err := cf.NewData(cert.Raw)
	if err != nil {
		return err
	}
	defer cfData.Release()

	certRef, err := security.SecCertificateCreateWithData(cfData)
	if err != nil {
		return err
	}
	defer certRef.Release()

	// Adding the label here doesn't have any effect. Apple Keychain always uses
	// the commonName.
	attributes, err := cf.NewDictionary(cf.Dictionary{
		security.KSecClass:    security.KSecClassCertificate,
		security.KSecValueRef: certRef,
	})
	if err != nil {
		return err
	}
	defer attributes.Release()

	// Store the certificate
	if err := security.SecItemAdd(attributes, nil); err != nil {
		return err
	}

	// Update the label if necessary
	if label != "" && label != cert.Subject.CommonName {
		cfLabel, err := cf.NewString(label)
		if err != nil {
			return err
		}
		defer cfLabel.Release()

		query, err := cf.NewDictionary(cf.Dictionary{
			security.KSecValueRef: certRef,
		})
		if err != nil {
			return err
		}
		defer query.Release()

		update, err := cf.NewDictionary(cf.Dictionary{
			security.KSecAttrLabel: cfLabel,
		})
		if err != nil {
			return err
		}
		defer update.Release()

		if err := security.SecItemUpdate(query, update); err != nil {
			return err
		}
	}

	return nil
}

func parseURI(rawuri string) (*keyAttributes, error) {
	// When rawuri is just the key name
	if !strings.HasPrefix(strings.ToLower(rawuri), Scheme) {
		return &keyAttributes{
			label: rawuri,
			tag:   DefaultTag,
			retry: true,
		}, nil
	}

	// When rawuri is a mackms uri.
	u, err := uri.ParseWithScheme(Scheme, rawuri)
	if err != nil {
		return nil, err
	}

	// Special case for mackms:label
	if len(u.Values) == 1 {
		for k, v := range u.Values {
			if (len(v) == 1 && v[0] == "") || len(v) == 0 {
				return &keyAttributes{
					label: k,
					tag:   DefaultTag,
					retry: true,
				}, nil
			}
		}
	}

	// With regular values, uris look like this:
	// mackms:label=my-key;tag=my-tag;hash=010a...;se=true;bio=true
	label := u.Get("label")
	if label == "" {
		return nil, fmt.Errorf("error parsing %q: label is required", rawuri)
	}
	tag := u.Get("tag")
	if tag == "" && !u.Has("tag") {
		tag = DefaultTag
	}
	return &keyAttributes{
		label:            label,
		tag:              tag,
		hash:             u.GetEncoded("hash"),
		retry:            !u.Has("tag"),
		useSecureEnclave: u.GetBool("se"),
		useBiometrics:    u.GetBool("bio"),
	}, nil
}

func parseCertURI(rawuri string, requireValue bool) (*certAttributes, error) {
	// When rawuri is just the label
	if !strings.HasPrefix(strings.ToLower(rawuri), Scheme) {
		return &certAttributes{
			label: rawuri,
		}, nil
	}

	// When rawuri is a mackms uri.
	u, err := uri.ParseWithScheme(Scheme, rawuri)
	if err != nil {
		return nil, err
	}

	// Special case for mackms:label
	if len(u.Values) == 1 {
		for k, v := range u.Values {
			if (len(v) == 1 && v[0] == "") || len(v) == 0 {
				return &certAttributes{
					label: k,
				}, nil
			}
		}
	}

	// With regular values, uris look like this:
	// mackms:label=my-cert;serial=01020A0B...
	label := u.Get("label")
	serial := u.GetEncoded("serial")
	if requireValue && label == "" && len(serial) == 0 {
		return nil, fmt.Errorf("error parsing %q: label or serial are required", rawuri)
	}

	var serialNumber *big.Int
	if len(serial) > 0 {
		serialNumber = new(big.Int).SetBytes(serial)
	}

	return &certAttributes{
		label:        label,
		serialNumber: serialNumber,
	}, nil
}

func parseSearchURI(rawuri string) (*keySearchAttributes, error) {
	// When rawuri is just the key name
	if !strings.HasPrefix(strings.ToLower(rawuri), Scheme) {
		return &keySearchAttributes{
			label: rawuri,
			tag:   DefaultTag,
		}, nil
	}

	// When rawuri is a mackms uri.
	u, err := uri.Parse(rawuri)
	if err != nil {
		return nil, err
	}

	// Special case for mackms:label
	if len(u.Values) == 1 {
		for k, v := range u.Values {
			if (len(v) == 1 && v[0] == "") || len(v) == 0 {
				return &keySearchAttributes{
					label: k,
					tag:   DefaultTag,
				}, nil
			}
		}
	}

	// With regular values, uris look like this:
	// mackms:label=my-key;tag=my-tag;hash=010a...;se=true;bio=true
	label := u.Get("label") // when searching, the label can be empty
	tag := u.Get("tag")
	if tag == "" && !u.Has("tag") {
		tag = DefaultTag
	}
	return &keySearchAttributes{
		label:            label,
		tag:              tag,
		hash:             u.GetEncoded("hash"),
		secureEnclaveSet: u.Values.Has("se"),
		useSecureEnclave: u.GetBool("se"),
	}, nil
}

// encodeSerialNumber encodes the serial number of a certificate in ASN.1.
// Negative serial numbers are not allowed.
func encodeSerialNumber(s *big.Int) []byte {
	if s.Sign() == 0 {
		return []byte{0x00}
	}
	b := s.Bytes()
	if b[0]&0x80 != 0 {
		// Pad this with 0x00 in order to stop it looking like a negative number.
		return append([]byte{0x00}, b...)
	}
	return b
}

func parseECDSAPublicKey(raw []byte) (crypto.PublicKey, error) {
	switch len(raw) / 2 {
	case 32: // 65 bytes
		key, err := ecdh.P256().NewPublicKey(raw)
		if err != nil {
			return nil, err
		}
		return ecdhToECDSAPublicKey(key)
	case 48: // 97 bytes
		key, err := ecdh.P384().NewPublicKey(raw)
		if err != nil {
			return nil, err
		}
		return ecdhToECDSAPublicKey(key)
	case 66: // 133 bytes:
		key, err := ecdh.P521().NewPublicKey(raw)
		if err != nil {
			return nil, err
		}
		return ecdhToECDSAPublicKey(key)
	default:
		return nil, fmt.Errorf("unsupported ECDSA key with %d bytes", len(raw))
	}
}

func parseECDSAPrivateKey(raw []byte) (crypto.PublicKey, error) {
	switch len(raw) / 3 {
	case 32: // 97 bytes
		key, err := ecdh.P256().NewPrivateKey(raw[65:])
		if err != nil {
			return nil, err
		}
		return ecdhToECDSAPublicKey(key.PublicKey())
	case 48: // 145 bytes
		key, err := ecdh.P384().NewPrivateKey(raw[97:])
		if err != nil {
			return nil, err
		}
		return ecdhToECDSAPublicKey(key.PublicKey())
	case 66: // 199 bytes:
		key, err := ecdh.P521().NewPrivateKey(raw[133:])
		if err != nil {
			return nil, err
		}
		return ecdhToECDSAPublicKey(key.PublicKey())
	default:
		return nil, fmt.Errorf("unsupported ECDSA key with %d bytes", len(raw))
	}
}

func ecdhToECDSAPublicKey(key *ecdh.PublicKey) (*ecdsa.PublicKey, error) {
	rawKey := key.Bytes()
	switch key.Curve() {
	case ecdh.P256():
		return &ecdsa.PublicKey{
			Curve: elliptic.P256(),
			X:     big.NewInt(0).SetBytes(rawKey[1:33]),
			Y:     big.NewInt(0).SetBytes(rawKey[33:]),
		}, nil
	case ecdh.P384():
		return &ecdsa.PublicKey{
			Curve: elliptic.P384(),
			X:     big.NewInt(0).SetBytes(rawKey[1:49]),
			Y:     big.NewInt(0).SetBytes(rawKey[49:]),
		}, nil
	case ecdh.P521():
		return &ecdsa.PublicKey{
			Curve: elliptic.P521(),
			X:     big.NewInt(0).SetBytes(rawKey[1:67]),
			Y:     big.NewInt(0).SetBytes(rawKey[67:]),
		}, nil
	default:
		return nil, errors.New("failed to convert *ecdh.PublicKey to *ecdsa.PublicKey")
	}
}

func apiv1Error(err error) error {
	switch {
	case errors.Is(err, security.ErrNotFound):
		return apiv1.NotFoundError{
			Message: err.Error(),
		}
	case errors.Is(err, security.ErrAlreadyExists):
		return apiv1.AlreadyExistsError{
			Message: err.Error(),
		}
	default:
		return err
	}
}