Skip to content

Commit

Permalink
DAC/connection works
Browse files Browse the repository at this point in the history
  • Loading branch information
sharadb-amazon committed Jan 4, 2024
1 parent d577450 commit 55b738c
Show file tree
Hide file tree
Showing 11 changed files with 190 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

/* Begin PBXBuildFile section */
3C0474062B3F7E5F0012AE95 /* MTREndpointFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C0474052B3F7E5F0012AE95 /* MTREndpointFilter.h */; };
3C04740C2B4604CF0012AE95 /* MTRCryptoUtils.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C04740B2B4604CF0012AE95 /* MTRCryptoUtils.h */; };
3C04740E2B4605B40012AE95 /* MTRCryptoUtils.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3C04740D2B4605B40012AE95 /* MTRCryptoUtils.mm */; };
3C2346212B362B4F00FA276E /* MTRCastingPlayer.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C2346202B362B4F00FA276E /* MTRCastingPlayer.h */; };
3C2346232B362B9500FA276E /* MTRCastingPlayerDiscovery.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C2346222B362B9500FA276E /* MTRCastingPlayerDiscovery.h */; };
3C2346252B362BBB00FA276E /* MTRCastingPlayerDiscovery.mm in Sources */ = {isa = PBXBuildFile; fileRef = 3C2346242B362BBB00FA276E /* MTRCastingPlayerDiscovery.mm */; };
Expand Down Expand Up @@ -67,6 +69,8 @@

/* Begin PBXFileReference section */
3C0474052B3F7E5F0012AE95 /* MTREndpointFilter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTREndpointFilter.h; sourceTree = "<group>"; };
3C04740B2B4604CF0012AE95 /* MTRCryptoUtils.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRCryptoUtils.h; sourceTree = "<group>"; };
3C04740D2B4605B40012AE95 /* MTRCryptoUtils.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = MTRCryptoUtils.mm; sourceTree = "<group>"; };
3C0D9CDF2920A30C00D3332B /* CommissionableDataProviderImpl.hpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.h; path = CommissionableDataProviderImpl.hpp; sourceTree = "<group>"; };
3C2346202B362B4F00FA276E /* MTRCastingPlayer.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRCastingPlayer.h; sourceTree = "<group>"; };
3C2346222B362B9500FA276E /* MTRCastingPlayerDiscovery.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MTRCastingPlayerDiscovery.h; sourceTree = "<group>"; };
Expand Down Expand Up @@ -230,6 +234,8 @@
3CF8532628E37F1000F07B9F /* MatterError.mm */,
3C9437912B3B478E0096E5F4 /* MTRErrorUtils.h */,
3C9437932B3B47A10096E5F4 /* MTRErrorUtils.mm */,
3C04740B2B4604CF0012AE95 /* MTRCryptoUtils.h */,
3C04740D2B4605B40012AE95 /* MTRCryptoUtils.mm */,
3CCB873A286A593700771BAD /* CastingServerBridge.h */,
3CCB873D286A593700771BAD /* CastingServerBridge.mm */,
3C66FBFA2903279A00B63FE7 /* AppParameters.h */,
Expand Down Expand Up @@ -298,6 +304,7 @@
3CCB87212869085400771BAD /* MatterTvCastingBridge.h in Headers */,
3C2346352B362D7900FA276E /* MTRLaunchResponse.h in Headers */,
3C6920462AA1093300D0F613 /* MTRDeviceAttestationCredentialsProvider.h in Headers */,
3C04740C2B4604CF0012AE95 /* MTRCryptoUtils.h in Headers */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -409,6 +416,7 @@
3CCB8744286A593700771BAD /* ConversionUtils.mm in Sources */,
3CF71C0C2A992D25003A5CE5 /* MTRCastingApp.mm in Sources */,
3C4E53B028E4F28100F293E8 /* MediaPlaybackTypes.mm in Sources */,
3C04740E2B4605B40012AE95 /* MTRCryptoUtils.mm in Sources */,
3CD73F1E2A9E83C1009D82D1 /* MTRCommissionableDataProvider.mm in Sources */,
3CD73F222A9EA078009D82D1 /* MTRDeviceAttestationCredentials.mm in Sources */,
3C2346252B362BBB00FA276E /* MTRCastingPlayerDiscovery.mm in Sources */,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
*
* Copyright (c) 2023 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 <Foundation/Foundation.h>

#ifndef MTRCryptoUtils_h
#define MTRCryptoUtils_h

@interface MTRCryptoUtils : NSObject

/**
* @brief Convert an ASN.1 DER signature (per X9.62) as used by TLS libraries to SEC1 raw format
*
* Errors are:
* - CHIP_ERROR_INVALID_ARGUMENT on any argument being invalid (e.g. nullptr), wrong sizes,
* wrong or unsupported format,
* - CHIP_ERROR_BUFFER_TOO_SMALL on running out of space at runtime.
* - CHIP_ERROR_INTERNAL on any unexpected processing error.
*
* @param[in] feLengthBytes Field Element length in bytes (e.g. 32 for P256 curve)
* @param[in] asn1Signature ASN.1 DER signature input
* @param[out] outRawSignature Raw signature of <r,s> concatenated format output buffer. Size must be at
* least >= `2 * fe_length_bytes`. On success, the outRawSignature buffer will be re-assigned
* to have the correct size (2 * feLengthBytes).
* @return Returns an NSError on error, nil otherwise
*/
+ (NSError * _Nullable)ecdsaAsn1SignatureToRawWithFeLengthBytes:(NSUInteger)feLengthBytes asn1Signature:(CFDataRef _Nonnull)asn1Signature outRawSignature:(NSData *_Nullable* _Nullable)outRawSignature;

@end

#endif /* MTRCryptoUtils_h */
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
*
* Copyright (c) 2020-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 "MTRCryptoUtils.h"

#include <crypto/CHIPCryptoPAL.h>
#include <lib/support/logging/CHIPLogging.h>
#include <lib/support/Span.h>
#include <lib/core/CHIPError.h>

#include <Security/Security.h>

@implementation MTRCryptoUtils

+ (NSError *)ecdsaAsn1SignatureToRawWithFeLengthBytes:(NSUInteger)feLengthBytes asn1Signature:(CFDataRef)asn1Signature outRawSignature:(NSData **)outRawSignature
{
// convert asn1Signature from CFDataRef to MutableByteSpan (asn1SignatureByteSpan)
uint8_t mAsn1SignatureBytes[256];
chip::MutableByteSpan asn1SignatureByteSpan = chip::MutableByteSpan(mAsn1SignatureBytes, sizeof(mAsn1SignatureBytes));
size_t signatureLen = CFDataGetLength(asn1Signature);
CFDataGetBytes(asn1Signature, CFRangeMake(0, signatureLen), asn1SignatureByteSpan.data());
asn1SignatureByteSpan.reduce_size(signatureLen);

uint8_t *outRawSignatureBytes = new uint8_t[(*outRawSignature).length];
chip::MutableByteSpan outRawSignatureMutableByteSpan = chip::MutableByteSpan(outRawSignatureBytes, (*outRawSignature).length);

CHIP_ERROR conversionError = chip::Crypto::EcdsaAsn1SignatureToRaw(
feLengthBytes, chip::ByteSpan(asn1SignatureByteSpan.data(), asn1SignatureByteSpan.size()), outRawSignatureMutableByteSpan);
if (CHIP_NO_ERROR != conversionError) {
ChipLogError(AppServer,
"DeviceAttestationCredentialsProviderImpl::SignWithDeviceAttestationKey failed to convert to raw signature.");

//break;
}
*outRawSignature = [NSData dataWithBytes:outRawSignatureMutableByteSpan.data() length:outRawSignatureMutableByteSpan.size()];
return nil;
}

@end
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
- (MTRCommissionableData * _Nonnull)castingAppDidReceiveRequestForCommissionableData:(id _Nonnull)sender;
- (MTRDeviceAttestationCredentials * _Nonnull)castingAppDidReceiveRequestForDeviceAttestationCredentials:(id _Nonnull)sender;

- (NSData * _Nonnull)castingApp:(id _Nonnull)sender didReceiveRequestToSignCertificateRequest:(NSData * _Nonnull)csrData;
- (NSError * _Nullable)castingApp:(id _Nonnull)sender didReceiveRequestToSignCertificateRequest:(NSData * _Nonnull)csrData outRawSignature:(NSData ** _Nonnull)outRawSignature;

@end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,14 @@

namespace matter {
namespace casting {
namespace support {
namespace support {

CHIP_ERROR MTRDeviceAttestationCredentialsProvider::Initialize(id<MTRDataSource> dataSource)
{
VerifyOrReturnError(dataSource != nullptr, CHIP_ERROR_INVALID_ARGUMENT);
VerifyOrReturnError(mDataSource == nullptr, CHIP_ERROR_INCORRECT_STATE);

mDataSource = dataSource;
mDac = [mDataSource
castingAppDidReceiveRequestForDeviceAttestationCredentials:@"MTRDeviceAttestationCredentialsProvider.Initialize()"];

Expand Down Expand Up @@ -110,13 +111,18 @@
{
VerifyOrReturnError(mDataSource != nullptr, CHIP_ERROR_INCORRECT_STATE);

__block NSData * signedData = nil;
NSData * csrData = [NSData dataWithBytes:messageToSign.data() length:messageToSign.size()];
__block NSData * signedData = [NSData dataWithBytes:outSignatureBuffer.data() length:outSignatureBuffer.size()];
__block NSData * csrData = [NSData dataWithBytes:messageToSign.data() length:messageToSign.size()];
__block NSError *err = nil;
dispatch_sync(mDataSource.clientQueue, ^{
signedData = [mDataSource castingApp:@"MTRDeviceAttestationCredentialsProvider.SignWithDeviceAttestationKey()"
didReceiveRequestToSignCertificateRequest:csrData];
err = [mDataSource castingApp:@"MTRDeviceAttestationCredentialsProvider.SignWithDeviceAttestationKey()"
didReceiveRequestToSignCertificateRequest:csrData outRawSignature:&signedData];
});

if(err != nil) {
// TODO return correct error and log
return CHIP_ERROR_INCORRECT_STATE;
}
if (signedData != nil && outSignatureBuffer.size() >= signedData.length) {
memcpy(outSignatureBuffer.data(), signedData.bytes, signedData.length);
outSignatureBuffer.reduce_size(signedData.length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
// value of 0 means unspecified
@property (nonatomic, readonly) uint16_t vendorId;
@property (nonatomic, readonly) uint16_t productId;
//std::vector<chip::app::Clusters::Descriptor::Structs::DeviceTypeStruct::DecodableType> requiredDeviceTypes;
// std::vector<chip::app::Clusters::Descriptor::Structs::DeviceTypeStruct::DecodableType> requiredDeviceTypes;

@end
#endif /* MTREndpointFilter_h */
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ FOUNDATION_EXPORT const unsigned char MatterTvCastingBridgeVersionString[];
#import "MTRCluster.h"
#import "MTRCommissionableData.h"
#import "MTRContentLauncherCluster.h"
#import "MTRCryptoUtils.h"
#import "MTRCurrentState.h"
#import "MTRDataSource.h"
#import "MTRDeviceAttestationCredentials.h"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,8 @@
dependencies = (
);
name = TvCasting;
packageProductDependencies = (
);
productName = TvCasting;
productReference = 3CC0E8F62841DD3400EC6A18 /* TvCasting.app */;
productType = "com.apple.product-type.application";
Expand Down Expand Up @@ -227,6 +229,9 @@
Base,
);
mainGroup = 3CC0E8ED2841DD3400EC6A18;
packageReferences = (
3C2696F72B4628FE0026E771 /* XCRemoteSwiftPackageReference "swift-asn1" */,
);
productRefGroup = 3CC0E8F72841DD3400EC6A18 /* Products */;
projectDirPath = "";
projectRoot = "";
Expand Down Expand Up @@ -543,6 +548,17 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */

/* Begin XCRemoteSwiftPackageReference section */
3C2696F72B4628FE0026E771 /* XCRemoteSwiftPackageReference "swift-asn1" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/apple/swift-asn1.git";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.0.0;
};
};
/* End XCRemoteSwiftPackageReference section */
};
rootObject = 3CC0E8EE2841DD3400EC6A18 /* Project object */;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,14 @@
*/

import Foundation
import Security
import os.log

class MTRAppParametersDataSource : NSObject, MTRDataSource
{
let Log = Logger(subsystem: "com.matter.casting",
category: "MTRAppParametersDataSource")

func clientQueue() -> DispatchQueue {
return DispatchQueue.main;
}
Expand Down Expand Up @@ -57,21 +61,46 @@ class MTRAppParametersDataSource : NSObject, MTRDataSource
productAttestationIntermediateCert: KPAI_FFF1_8000_Cert_Array)
}

func castingApp(_ sender: Any, didReceiveRequestToSignCertificateRequest csrData: Data) -> Data {
var privateKey = Data()
privateKey.append(kDevelopmentDAC_PublicKey_FFF1_8001);
privateKey.append(kDevelopmentDAC_PrivateKey_FFF1_8001);

let privateKeyRef: SecKey = SecKeyCreateWithData(privateKey as NSData,
func castingApp(_ sender: Any, didReceiveRequestToSignCertificateRequest csrData: Data, outRawSignature: AutoreleasingUnsafeMutablePointer<NSData?>) -> Error? {
Log.info("castingApp didReceiveRequestToSignCertificateRequest")

// get the private SecKey
var privateKeyData = Data()
privateKeyData.append(kDevelopmentDAC_PublicKey_FFF1_8001);
privateKeyData.append(kDevelopmentDAC_PrivateKey_FFF1_8001);
let privateSecKey: SecKey = SecKeyCreateWithData(privateKeyData as NSData,
[
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits: 256
] as NSDictionary, nil)!

let _:Unmanaged<SecKey> = Unmanaged<SecKey>.passRetained(privateKeyRef);

return Data() // TODO: use SecKey above to sign csrData and return resulting value
// sign csrData to get asn1SignatureData
var error: Unmanaged<CFError>?
var asn1SignatureData: CFData? = SecKeyCreateSignature(privateSecKey, .ecdsaSignatureMessageX962SHA256, csrData as CFData, &error)
if error != nil || asn1SignatureData == nil {
Log.error("Failed to sign message. Error: \(String(describing: error))")
return nil // return error
}

// convert ASN.1 DER signature to SEC1 raw format
//var rawSignatureData: NSData?
/* let err = MTRCryptoUtils.ecdsaAsn1SignatureToRaw(withFeLengthBytes: 32,
asn1Signature: Data(bytes: CFDataGetBytePtr(asn1SignatureData!), count: CFDataGetLength(asn1SignatureData!)),
outRawSignature: &rawSignatureData)*/
let err = MTRCryptoUtils.ecdsaAsn1SignatureToRaw(withFeLengthBytes: 32,
asn1Signature: asn1SignatureData!,
outRawSignature: &outRawSignature.pointee)
if(err == nil && outRawSignature.pointee != nil)
{
return nil
//return Data(rawSignatureData!)
}
else
{
Log.error("Failed in ecdsaAsn1SignatureToRaw conversion while signing CSR data. Error: \(String(describing: error))")
return nil // return error
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "swift-asn1",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-asn1.git",
"state" : {
"revision" : "c7e239b5c1492ffc3ebd7fbcc7a92548ce4e78f0",
"version" : "1.1.0"
}
}
],
"version" : 2
}
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,11 @@ CHIP_ERROR CastingPlayer::SendUserDirectedCommissioningRequest()
VerifyOrReturnValue(ipAddressToUse != nullptr, CHIP_ERROR_INCORRECT_STATE,
ChipLogError(AppServer, "No IP Address found to send UDC request to"));

ReturnErrorOnFailure(support::ChipDeviceEventHandler::SetUdcStatus(true));

ReturnErrorOnFailure(chip::Server::GetInstance().SendUserDirectedCommissioningRequest(
chip::Transport::PeerAddress::UDP(*ipAddressToUse, mAttributes.port, mAttributes.interfaceId)));

ReturnErrorOnFailure(support::ChipDeviceEventHandler::SetUdcStatus(true));

return CHIP_NO_ERROR;
}

Expand Down

0 comments on commit 55b738c

Please sign in to comment.