Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stop having Darwin CHIPTool depend on in-framework key generation. #18221

Merged
merged 1 commit into from
May 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,9 @@

constexpr const char * identities[] = { kIdentityAlpha, kIdentityBeta, kIdentityGamma };
for (size_t i = 0; i < ArraySize(identities); ++i) {
auto controllerParams = [[CHIPDeviceControllerStartupParams alloc] initWithKeypair:nocSigner];
auto controllerParams = [[CHIPDeviceControllerStartupParams alloc] initWithKeypair:nocSigner ipk:ipk];
controllerParams.vendorId = chip::VendorId::TestVendor1;
controllerParams.fabricId = i + 1;
controllerParams.ipk = ipk;

// We're not sure whether we're creating a new fabric or using an
// existing one, so just try both.
Expand Down
6 changes: 6 additions & 0 deletions src/darwin/CHIPTool/CHIPTool.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
2C21071525D1A8F200DDA4AD /* MultiAdminViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 2C21071325D1A8F200DDA4AD /* MultiAdminViewController.m */; };
2C460C2425D7594B000512D6 /* DeviceSelector.m in Sources */ = {isa = PBXBuildFile; fileRef = 2C460C2325D7594B000512D6 /* DeviceSelector.m */; };
2C460C3225D97CB3000512D6 /* UnpairDevicesViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 2C460C3025D97CB3000512D6 /* UnpairDevicesViewController.m */; };
51C8E3FB28261DCF00D47D00 /* FabricKeys.m in Sources */ = {isa = PBXBuildFile; fileRef = 51C8E3FA28261DCF00D47D00 /* FabricKeys.m */; };
991DC091247747F500C13860 /* EnumerateViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 991DC090247747F500C13860 /* EnumerateViewController.m */; };
997A639C253F93F7005C64E6 /* CHIP.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 997A639B253F93F7005C64E6 /* CHIP.framework */; };
997A639D253F93F7005C64E6 /* CHIP.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 997A639B253F93F7005C64E6 /* CHIP.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
Expand Down Expand Up @@ -62,6 +63,8 @@
2C460C2325D7594B000512D6 /* DeviceSelector.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DeviceSelector.m; sourceTree = "<group>"; };
2C460C3025D97CB3000512D6 /* UnpairDevicesViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = UnpairDevicesViewController.m; sourceTree = "<group>"; };
2C460C3125D97CB3000512D6 /* UnpairDevicesViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UnpairDevicesViewController.h; sourceTree = "<group>"; };
51C8E3F928261DCF00D47D00 /* FabricKeys.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FabricKeys.h; sourceTree = "<group>"; };
51C8E3FA28261DCF00D47D00 /* FabricKeys.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FabricKeys.m; sourceTree = "<group>"; };
991DC08F247747F500C13860 /* EnumerateViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = EnumerateViewController.h; sourceTree = "<group>"; };
991DC090247747F500C13860 /* EnumerateViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = EnumerateViewController.m; sourceTree = "<group>"; };
997A639B253F93F7005C64E6 /* CHIP.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; path = CHIP.framework; sourceTree = BUILT_PRODUCTS_DIR; };
Expand Down Expand Up @@ -245,6 +248,8 @@
B232D8C0251A0EE200792CB4 /* Framework Helpers */ = {
isa = PBXGroup;
children = (
51C8E3F928261DCF00D47D00 /* FabricKeys.h */,
51C8E3FA28261DCF00D47D00 /* FabricKeys.m */,
B2946A9924C9A7BF005C87D0 /* DefaultsUtils.h */,
B2946A9A24C9A7BF005C87D0 /* DefaultsUtils.m */,
);
Expand Down Expand Up @@ -401,6 +406,7 @@
B243A6692513A73600E56FEA /* RootViewController.m in Sources */,
B204A632244E1D0700C7C0E1 /* main.m in Sources */,
B204A624244E1D0600C7C0E1 /* SceneDelegate.m in Sources */,
51C8E3FB28261DCF00D47D00 /* FabricKeys.m in Sources */,
B2946A4224C99D53005C87D0 /* WiFiViewController.m in Sources */,
0CA0E0CF248599BB009087B9 /* OnOffViewController.m in Sources */,
);
Expand Down
16 changes: 14 additions & 2 deletions src/darwin/CHIPTool/CHIPTool/Framework Helpers/DefaultsUtils.m
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
*/

#import "DefaultsUtils.h"
#import "FabricKeys.h"

NSString * const kCHIPToolDefaultsDomain = @"com.apple.chiptool";
NSString * const kNetworkSSIDDefaultsKey = @"networkSSID";
Expand Down Expand Up @@ -81,7 +82,12 @@ void CHIPSetNextAvailableDeviceID(uint64_t id)
return;
}

__auto_type * params = [[CHIPDeviceControllerStartupParams alloc] initWithKeypair:nil];
__auto_type * keys = [[FabricKeys alloc] init];
if (keys == nil) {
return;
}

__auto_type * params = [[CHIPDeviceControllerStartupParams alloc] initWithKeypair:keys ipk:keys.ipk];
params.vendorId = kTestVendorId;
params.fabricId = 1;

Expand All @@ -98,11 +104,17 @@ void CHIPSetNextAvailableDeviceID(uint64_t id)

CHIPDeviceController * CHIPRestartController(CHIPDeviceController * controller)
{
__auto_type * keys = [[FabricKeys alloc] init];
if (keys == nil) {
NSLog(@"No keys, can't restart controller");
return controller;
}

NSLog(@"Shutting down the stack");
[controller shutdown];

NSLog(@"Starting up the stack");
__auto_type * params = [[CHIPDeviceControllerStartupParams alloc] initWithKeypair:nil];
__auto_type * params = [[CHIPDeviceControllerStartupParams alloc] initWithKeypair:keys ipk:keys.ipk];
params.vendorId = kTestVendorId;
params.fabricId = 1;

Expand Down
35 changes: 35 additions & 0 deletions src/darwin/CHIPTool/CHIPTool/Framework Helpers/FabricKeys.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Copyright (c) 2022 Project CHIP Authors
*
* 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.
*/

#pragma once

#import <CHIP/CHIP.h>
#import <Foundation/Foundation.h>

/**
* Management of the CA key and IPK for our fabric.
*/

NS_ASSUME_NONNULL_BEGIN

@interface FabricKeys : NSObject <CHIPKeypair>

@property (readonly, nonatomic, strong) NSData * ipk;

- (instancetype)init;
@end

NS_ASSUME_NONNULL_END
237 changes: 237 additions & 0 deletions src/darwin/CHIPTool/CHIPTool/Framework Helpers/FabricKeys.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
/**
* Copyright (c) 2022 Project CHIP Authors
*
* 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.
*/

#import "FabricKeys.h"

#import <Security/SecKey.h>

@interface FabricKeys ()
@property (readonly) SecKeyRef privateKey;
@property (readonly) SecKeyRef publicKey;
@end

static const NSString * kCHIPIPKKeyChainLabel = @"matter-tool.nodeopcerts.IPK:0";
static const NSString * kCHIPCAKeyChainLabel = @"matter-tool.nodeopcerts.CA:0";

@implementation FabricKeys

+ (NSDictionary *)ipkParams
{
return @{
(__bridge NSString *) kSecClass : (__bridge NSString *) kSecClassKey,
(__bridge NSString *) kSecAttrApplicationLabel : kCHIPIPKKeyChainLabel,
(__bridge NSString *) kSecAttrKeyClass : (__bridge NSString *) kSecAttrKeyClassSymmetric,
};
}

+ (NSData *)loadIPK
{
NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys ipkParams]];
query[(__bridge NSString *) kSecReturnData] = @(YES);

// The CFDataRef we get from SecItemCopyMatching allocates its buffer in a
// way that zeroes it when deallocated.
CFDataRef keyDataRef;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, (CFTypeRef *) &keyDataRef);
if (status != errSecSuccess || keyDataRef == nil) {
NSLog(@"Did not find IPK in the keychain");
return nil;
}

NSLog(@"Found an existing IPK in the keychain");
NSData * keyData = CFBridgingRelease(keyDataRef);

return [[NSData alloc] initWithBase64EncodedData:keyData options:0];
}

+ (NSData *)generateIPK
{
NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys ipkParams]];

// First, delete any existing item, since otherwise trying to add the new item
// later will fail. Ignore delete failure, since we might not have had the
// item at all.
SecItemDelete((__bridge CFDictionaryRef) query);

// Generate an IPK. For now, hardcoded to 16 bytes until the
// framework exposes this constant.
const size_t ipk_size = 16;
NSMutableData * ipkData = [NSMutableData dataWithLength:ipk_size];
if (ipkData == nil) {
return nil;
}

int status = SecRandomCopyBytes(kSecRandomDefault, ipk_size, [ipkData mutableBytes]);
if (status != errSecSuccess) {
NSLog(@"Failed to generate IPK : %d", status);
return nil;
}

query[(__bridge NSString *) kSecValueData] = [ipkData base64EncodedDataWithOptions:0];

OSStatus addStatus = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
if (addStatus != errSecSuccess) {
NSLog(@"Failed to store IPK : %d", addStatus);
return nil;
}

return ipkData;
}

+ (NSDictionary *)privateKeyParams
{
return @{
(__bridge NSString *) kSecClass : (__bridge NSString *) kSecClassKey,
(__bridge NSString *) kSecAttrApplicationLabel : kCHIPCAKeyChainLabel,
// We're storing a base-64 encoding of some opaque thing that represents
// our keypair. It's not really a public or private key; claim it's a
// symmetric key.
(__bridge NSString *) kSecAttrKeyClass : (__bridge NSString *) kSecAttrKeyClassSymmetric,
};
}

+ (NSDictionary *)privateKeyCreationParams
{
// For now harcoded to 256 bits until the framework exposes this constant.
const size_t keySizeInBits = 256;

return @{
(__bridge NSString *) kSecAttrKeyClass : (__bridge NSString *) kSecAttrKeyClassPrivate,
(__bridge NSString *) kSecAttrKeyType : (__bridge NSNumber *) kSecAttrKeyTypeECSECPrimeRandom,
(__bridge NSString *) kSecAttrKeySizeInBits : @(keySizeInBits),
(__bridge NSString *) kSecAttrIsPermanent : @(NO)
};
}

+ (SecKeyRef)loadCAPrivateKey
{
NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys privateKeyParams]];
query[(__bridge NSString *) kSecReturnData] = @(YES);

// The CFDataRef we get from SecItemCopyMatching allocates its buffer in a
// way that zeroes it when deallocated.
CFDataRef keyDataRef;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef) query, (CFTypeRef *) &keyDataRef);
if (status != errSecSuccess || keyDataRef == nil) {
NSLog(@"Did not find CA key in the keychain");
return NULL;
}

NSLog(@"Found an existing CA key in the keychain");
NSData * encodedKey = CFBridgingRelease(keyDataRef);

NSData * keyData = [[NSData alloc] initWithBase64EncodedData:encodedKey options:0];
if (keyData == nil) {
NSLog(@"Could not base64-decode CA key");
return NULL;
}

CFErrorRef error = NULL;
SecKeyRef key = SecKeyCreateWithData(
(__bridge CFDataRef) keyData, (__bridge CFDictionaryRef)[FabricKeys privateKeyCreationParams], &error);
if (error) {
NSLog(@"Could not reconstruct private key %@", (__bridge NSError *) error);
return NULL;
}

return key;
}

+ (SecKeyRef)generateCAPrivateKey
{
NSMutableDictionary * query = [[NSMutableDictionary alloc] initWithDictionary:[FabricKeys privateKeyParams]];

// First, delete any existing item, since otherwise trying to add the new item
// later will fail. Ignore delete failure, since we might not have had the
// item at all.
SecItemDelete((__bridge CFDictionaryRef) query);

CFErrorRef error = NULL;
SecKeyRef key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)[FabricKeys privateKeyCreationParams], &error);
if (error) {
NSLog(@"Could not generate private key: %@", (__bridge NSError *) error);
return NULL;
}

NSData * keyData = (__bridge_transfer NSData *) SecKeyCopyExternalRepresentation(key, &error);
if (error) {
NSLog(@"Could not get key external representation: %@", (__bridge NSError *) error);
CFRelease(key);
return NULL;
}

query[(__bridge NSString *) kSecValueData] = [keyData base64EncodedDataWithOptions:0];

OSStatus status = SecItemAdd((__bridge CFDictionaryRef) query, NULL);
if (status != errSecSuccess) {
NSLog(@"Failed to store private key : %d", status);
CFRelease(key);
return NULL;
}

return key;
}

- (instancetype)init
{
if (!(self = [super init])) {
return nil;
}

if (!(_ipk = [FabricKeys loadIPK])) {
if (!(_ipk = [FabricKeys generateIPK])) {
return nil;
}
}

if (!(_privateKey = [FabricKeys loadCAPrivateKey])) {
if (!(_privateKey = [FabricKeys generateCAPrivateKey])) {
return nil;
}
}

_publicKey = SecKeyCopyPublicKey(_privateKey);
return self;
}

- (NSData *)ECDSA_sign_hash:(NSData *)hash
{
CFErrorRef error = NULL;
CFDataRef outData
= SecKeyCreateSignature(_privateKey, kSecKeyAlgorithmECDSASignatureRFC4754, (__bridge CFDataRef) hash, &error);

if (error != noErr) {
NSLog(@"Failed to sign cert: %@", (__bridge NSError *) error);
}
return (__bridge_transfer NSData *) outData;
}

- (SecKeyRef)pubkey
{
return self.publicKey;
}

- (void)dealloc
{
if (_publicKey) {
CFRelease(_publicKey);
}

if (_privateKey) {
CFRelease(_privateKey);
}
}
@end
12 changes: 5 additions & 7 deletions src/darwin/Framework/CHIP/CHIPDeviceController.mm
Original file line number Diff line number Diff line change
Expand Up @@ -168,11 +168,9 @@ - (BOOL)startup:(CHIPDeviceControllerStartupParams *)startupParams
CHIP_ERROR errorCode = CHIP_ERROR_INCORRECT_STATE;

// create a CHIPP256KeypairBridge here and pass it to the operationalCredentialsDelegate
std::unique_ptr<chip::Crypto::CHIPP256KeypairNativeBridge> nativeBridge;
if (startupParams.rootCAKeypair != nil) {
_keypairBridge.Init(startupParams.rootCAKeypair);
nativeBridge.reset(new chip::Crypto::CHIPP256KeypairNativeBridge(_keypairBridge));
}
_keypairBridge.Init(startupParams.rootCAKeypair);
auto nativeBridge = std::make_unique<chip::Crypto::CHIPP256KeypairNativeBridge>(_keypairBridge);

errorCode
= _operationalCredentialsDelegate->init(_factory.storageDelegateBridge, std::move(nativeBridge), startupParams.ipk);
if ([self checkForStartError:(CHIP_NO_ERROR == errorCode) logMsg:kErrorOperationalCredentialsInit]) {
Expand Down Expand Up @@ -723,18 +721,18 @@ - (CHIP_ERROR)isRunningOnFabric:(chip::FabricInfo *)fabric isRunning:(BOOL *)isR

@implementation CHIPDeviceControllerStartupParams

- (instancetype)initWithKeypair:(_Nullable id<CHIPKeypair>)rootCAKeypair
- (instancetype)initWithKeypair:(id<CHIPKeypair>)rootCAKeypair ipk:(NSData *)ipk
{
if (!(self = [super init])) {
return nil;
}

_rootCAKeypair = rootCAKeypair;
_ipk = ipk;

// Set various invalid values.
_vendorId = chip::VendorId::Common;
_fabricId = chip::kUndefinedFabricId;
_ipk = nil;

return self;
}
Expand Down
Loading