|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Project CHIP Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +#import "FabricKeys.h" |
| 18 | + |
| 19 | +#import <Security/SecKey.h> |
| 20 | + |
| 21 | +@interface FabricKeys () |
| 22 | +@property (readonly) SecKeyRef privateKey; |
| 23 | +@property (readonly) SecKeyRef publicKey; |
| 24 | +@end |
| 25 | + |
| 26 | +static const NSString * kCHIPIPKKeyChainLabel = @"matter-tool.nodeopcerts.IPK:0"; |
| 27 | +static const NSString * kCHIPCAKeyChainLabel = @"matter-tool.nodeopcerts.CA:0"; |
| 28 | + |
| 29 | +@implementation FabricKeys |
| 30 | + |
| 31 | ++ (NSDictionary *)ipkParams |
| 32 | +{ |
| 33 | + return @{ |
| 34 | + (__bridge NSString *) kSecClass : (__bridge NSString *) kSecClassKey, |
| 35 | + (__bridge NSString *) kSecAttrApplicationLabel : kCHIPIPKKeyChainLabel, |
| 36 | + (__bridge NSString *) kSecAttrKeyClass : (__bridge NSString *) kSecAttrKeyClassSymmetric, |
| 37 | + }; |
| 38 | +} |
| 39 | + |
| 40 | ++ (NSData *)loadIPK |
| 41 | +{ |
| 42 | + NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys ipkParams]]; |
| 43 | + query[(__bridge NSString *) kSecReturnData] = @(YES); |
| 44 | + |
| 45 | + // The CFDataRef we get from SecItemCopyMatching allocates its buffer in a |
| 46 | + // way that zeroes it when deallocated. |
| 47 | + CFDataRef keyDataRef; |
| 48 | + OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, (CFTypeRef *) &keyDataRef); |
| 49 | + if (status != errSecSuccess || keyDataRef == nil) { |
| 50 | + NSLog(@"Did not find IPK in the keychain"); |
| 51 | + return nil; |
| 52 | + } |
| 53 | + |
| 54 | + NSLog(@"Found an existing IPK in the keychain"); |
| 55 | + NSData * keyData = CFBridgingRelease(keyDataRef); |
| 56 | + |
| 57 | + return [[NSData alloc] initWithBase64EncodedData:keyData options:0]; |
| 58 | +} |
| 59 | + |
| 60 | ++ (NSData *)generateIPK |
| 61 | +{ |
| 62 | + NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys ipkParams]]; |
| 63 | + |
| 64 | + // First, delete any existing item, since otherwise trying to add the new item |
| 65 | + // later will fail. Ignore delete failure, since we might not have had the |
| 66 | + // item at all. |
| 67 | + SecItemDelete((__bridge CFDictionaryRef) query); |
| 68 | + |
| 69 | + // Generate an IPK. For now, hardcoded to 16 bytes until the |
| 70 | + // framework exposes this constant. |
| 71 | + const size_t ipk_size = 16; |
| 72 | + NSMutableData * ipkData = [NSMutableData dataWithLength:ipk_size]; |
| 73 | + if (ipkData == nil) { |
| 74 | + return nil; |
| 75 | + } |
| 76 | + |
| 77 | + int status = SecRandomCopyBytes(kSecRandomDefault, ipk_size, [ipkData mutableBytes]); |
| 78 | + if (status != errSecSuccess) { |
| 79 | + NSLog(@"Failed to generate IPK : %d", status); |
| 80 | + return nil; |
| 81 | + } |
| 82 | + |
| 83 | + query[(__bridge NSString *) kSecValueData] = [ipkData base64EncodedDataWithOptions:0]; |
| 84 | + |
| 85 | + OSStatus addStatus = SecItemAdd((__bridge CFDictionaryRef) query, NULL); |
| 86 | + if (addStatus != errSecSuccess) { |
| 87 | + NSLog(@"Failed to store IPK : %d", addStatus); |
| 88 | + return nil; |
| 89 | + } |
| 90 | + |
| 91 | + return ipkData; |
| 92 | +} |
| 93 | + |
| 94 | ++ (NSDictionary *)privateKeyParams |
| 95 | +{ |
| 96 | + return @{ |
| 97 | + (__bridge NSString *) kSecClass : (__bridge NSString *) kSecClassKey, |
| 98 | + (__bridge NSString *) kSecAttrApplicationLabel : kCHIPCAKeyChainLabel, |
| 99 | + // We're storing a base-64 encoding of some opaque thing that represents |
| 100 | + // our keypair. It's not really a public or private key; claim it's a |
| 101 | + // symmetric key. |
| 102 | + (__bridge NSString *) kSecAttrKeyClass : (__bridge NSString *) kSecAttrKeyClassSymmetric, |
| 103 | + }; |
| 104 | +} |
| 105 | + |
| 106 | ++ (NSDictionary *)privateKeyCreationParams |
| 107 | +{ |
| 108 | + // For now harcoded to 256 bits until the framework exposes this constant. |
| 109 | + const size_t keySizeInBits = 256; |
| 110 | + |
| 111 | + return @{ |
| 112 | + (__bridge NSString *) kSecAttrKeyClass : (__bridge NSString *) kSecAttrKeyClassPrivate, |
| 113 | + (__bridge NSString *) kSecAttrKeyType : (__bridge NSNumber *) kSecAttrKeyTypeECSECPrimeRandom, |
| 114 | + (__bridge NSString *) kSecAttrKeySizeInBits : @(keySizeInBits), |
| 115 | + (__bridge NSString *) kSecAttrIsPermanent : @(NO) |
| 116 | + }; |
| 117 | +} |
| 118 | + |
| 119 | ++ (SecKeyRef)loadCAPrivateKey |
| 120 | +{ |
| 121 | + NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys privateKeyParams]]; |
| 122 | + query[(__bridge NSString *) kSecReturnData] = @(YES); |
| 123 | + |
| 124 | + // The CFDataRef we get from SecItemCopyMatching allocates its buffer in a |
| 125 | + // way that zeroes it when deallocated. |
| 126 | + CFDataRef keyDataRef; |
| 127 | + OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, (CFTypeRef *) &keyDataRef); |
| 128 | + if (status != errSecSuccess || keyDataRef == nil) { |
| 129 | + NSLog(@"Did not find CA key in the keychain"); |
| 130 | + return NULL; |
| 131 | + } |
| 132 | + |
| 133 | + NSLog(@"Found an existing CA key in the keychain"); |
| 134 | + NSData * encodedKey = CFBridgingRelease(keyDataRef); |
| 135 | + |
| 136 | + NSData * keyData = [[NSData alloc] initWithBase64EncodedData:encodedKey options:0]; |
| 137 | + if (keyData == nil) { |
| 138 | + NSLog(@"Could not base64-decode CA key"); |
| 139 | + return NULL; |
| 140 | + } |
| 141 | + |
| 142 | + CFErrorRef error = NULL; |
| 143 | + SecKeyRef key = SecKeyCreateWithData( |
| 144 | + (__bridge CFDataRef) keyData, (__bridge CFDictionaryRef)[FabricKeys privateKeyCreationParams], &error); |
| 145 | + if (error) { |
| 146 | + NSLog(@"Could not reconstruct private key %@", (__bridge NSError *) error); |
| 147 | + return NULL; |
| 148 | + } |
| 149 | + |
| 150 | + return key; |
| 151 | +} |
| 152 | + |
| 153 | ++ (SecKeyRef)generateCAPrivateKey |
| 154 | +{ |
| 155 | + NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys privateKeyParams]]; |
| 156 | + |
| 157 | + // First, delete any existing item, since otherwise trying to add the new item |
| 158 | + // later will fail. Ignore delete failure, since we might not have had the |
| 159 | + // item at all. |
| 160 | + SecItemDelete((__bridge CFDictionaryRef) query); |
| 161 | + |
| 162 | + CFErrorRef error = NULL; |
| 163 | + SecKeyRef key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)[FabricKeys privateKeyCreationParams], &error); |
| 164 | + if (error) { |
| 165 | + NSLog(@"Could not generate private key: %@", (__bridge NSError *) error); |
| 166 | + return NULL; |
| 167 | + } |
| 168 | + |
| 169 | + NSData * keyData = (__bridge_transfer NSData *) SecKeyCopyExternalRepresentation(key, &error); |
| 170 | + if (error) { |
| 171 | + NSLog(@"Could not get key external representation: %@", (__bridge NSError *) error); |
| 172 | + CFRelease(key); |
| 173 | + return NULL; |
| 174 | + } |
| 175 | + |
| 176 | + query[(__bridge NSString *) kSecValueData] = [keyData base64EncodedDataWithOptions:0]; |
| 177 | + |
| 178 | + OSStatus status = SecItemAdd((__bridge CFDictionaryRef) query, NULL); |
| 179 | + if (status != errSecSuccess) { |
| 180 | + NSLog(@"Failed to store private key : %d", status); |
| 181 | + CFRelease(key); |
| 182 | + return NULL; |
| 183 | + } |
| 184 | + |
| 185 | + return key; |
| 186 | +} |
| 187 | + |
| 188 | +- (instancetype)init |
| 189 | +{ |
| 190 | + if (!(self = [super init])) { |
| 191 | + return nil; |
| 192 | + } |
| 193 | + |
| 194 | + if (!(_ipk = [FabricKeys loadIPK])) { |
| 195 | + if (!(_ipk = [FabricKeys generateIPK])) { |
| 196 | + return nil; |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + if (!(_privateKey = [FabricKeys loadCAPrivateKey])) { |
| 201 | + if (!(_privateKey = [FabricKeys generateCAPrivateKey])) { |
| 202 | + return nil; |
| 203 | + } |
| 204 | + } |
| 205 | + |
| 206 | + _publicKey = SecKeyCopyPublicKey(_privateKey); |
| 207 | + return self; |
| 208 | +} |
| 209 | + |
| 210 | +- (NSData *)ECDSA_sign_hash:(NSData *)hash |
| 211 | +{ |
| 212 | + CFErrorRef error = NULL; |
| 213 | + CFDataRef outData |
| 214 | + = SecKeyCreateSignature(_privateKey, kSecKeyAlgorithmECDSASignatureRFC4754, (__bridge CFDataRef) hash, &error); |
| 215 | + |
| 216 | + if (error != noErr) { |
| 217 | + NSLog(@"Failed to sign cert: %@", (__bridge NSError *) error); |
| 218 | + } |
| 219 | + return (__bridge_transfer NSData *) outData; |
| 220 | +} |
| 221 | + |
| 222 | +- (SecKeyRef)pubkey |
| 223 | +{ |
| 224 | + return self.publicKey; |
| 225 | +} |
| 226 | + |
| 227 | +- (void)dealloc |
| 228 | +{ |
| 229 | + if (_publicKey) { |
| 230 | + CFRelease(_publicKey); |
| 231 | + } |
| 232 | + |
| 233 | + if (_privateKey) { |
| 234 | + CFRelease(_privateKey); |
| 235 | + } |
| 236 | +} |
| 237 | +@end |
0 commit comments