Skip to content

Commit

Permalink
Integrate CASE session establishment with controller
Browse files Browse the repository at this point in the history
  • Loading branch information
pan-apple committed May 14, 2021
1 parent bb08a09 commit a15b4ec
Show file tree
Hide file tree
Showing 15 changed files with 272 additions and 75 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ bool emberAfOperationalCredentialsClusterAddOpCertCallback(chip::app::Command *
VerifyOrExit(admin->SetOperationalCert(ByteSpan(certBuf, NOC.size() + ICACertificate.size())) == CHIP_NO_ERROR,
status = EMBER_ZCL_STATUS_FAILURE);

VerifyOrExit(GetGlobalAdminPairingTable().Store(admin->GetAdminId()) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE);

exit:
emberAfSendImmediateDefaultResponse(status);
if (status == EMBER_ZCL_STATUS_FAILURE)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ bool emberAfTrustedRootCertificatesClusterAddTrustedRootCertificateCallback(chip
VerifyOrExit(admin != nullptr, status = EMBER_ZCL_STATUS_FAILURE);
VerifyOrExit(admin->SetRootCert(RootCertificate) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE);

VerifyOrExit(GetGlobalAdminPairingTable().Store(admin->GetAdminId()) == CHIP_NO_ERROR, status = EMBER_ZCL_STATUS_FAILURE);

exit:
emberAfSendImmediateDefaultResponse(status);
if (status == EMBER_ZCL_STATUS_FAILURE)
Expand Down
43 changes: 43 additions & 0 deletions src/controller/CHIPDevice.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,9 @@ CHIP_ERROR Device::Serialize(SerializedDevice & output)
serializable.mDevicePort = Encoding::LittleEndian::HostSwap16(mDeviceAddress.GetPort());
serializable.mAdminId = Encoding::LittleEndian::HostSwap16(mAdminId);

serializable.mCASESessionKeyId = Encoding::LittleEndian::HostSwap16(mCASESessionKeyId);
serializable.mDeviceProvisioningComplete = (mDeviceProvisioningComplete) ? 1 : 0;

static_assert(std::is_same<std::underlying_type<decltype(mDeviceAddress.GetTransportType())>::type, uint8_t>::value,
"The underlying type of Transport::Type is not uint8_t.");
serializable.mDeviceTransport = static_cast<uint8_t>(mDeviceAddress.GetTransportType());
Expand Down Expand Up @@ -217,6 +220,9 @@ CHIP_ERROR Device::Deserialize(const SerializedDevice & input)
port = Encoding::LittleEndian::HostSwap16(serializable.mDevicePort);
mAdminId = Encoding::LittleEndian::HostSwap16(serializable.mAdminId);

mCASESessionKeyId = Encoding::LittleEndian::HostSwap16(serializable.mCASESessionKeyId);
mDeviceProvisioningComplete = (serializable.mDeviceProvisioningComplete != 0);

// The InterfaceNameToId() API requires initialization of mInterface, and lock/unlock of
// LwIP stack.
interfaceId = INET_NULL_INTERFACEID;
Expand Down Expand Up @@ -370,6 +376,12 @@ CHIP_ERROR Device::LoadSecureSessionParameters(ResetTransport resetNeeded)
SecureSession::SessionRole::kInitiator, mAdminId);
SuccessOrExit(err);

if (IsProvisioningComplete())
{
err = EstablishCASESession();
SuccessOrExit(err);
}

exit:

if (err != CHIP_NO_ERROR)
Expand All @@ -389,6 +401,37 @@ bool Device::GetAddress(Inet::IPAddress & addr, uint16_t & port) const
return true;
}

CHIP_ERROR Device::EstablishCASESession()
{
Messaging::ExchangeContext * exchange = mExchangeMgr->NewContext(SecureSessionHandle(), &mCASESession);
VerifyOrReturnError(exchange != nullptr, CHIP_ERROR_INTERNAL);

ReturnErrorOnFailure(mCASESession.MessageDispatch().Init(mSessionManager->GetTransportManager()));
mCASESession.MessageDispatch().SetPeerAddress(mDeviceAddress);

ReturnErrorOnFailure(mCASESession.EstablishSession(mDeviceAddress, mCredentials, mDeviceId, 0, exchange, this));

return CHIP_NO_ERROR;
}

void Device::OnSessionEstablishmentError(CHIP_ERROR error) {}

void Device::OnSessionEstablished()
{
mCASESession.PeerConnection().SetPeerNodeId(mDeviceId);

// TODO - Enable keys derived from CASE Session
// CHIP_ERROR err = mSessionManager->NewPairing(Optional<Transport::PeerAddress>::Value(mDeviceAddress), mDeviceId,
// &mCASESession,
// SecureSession::SessionRole::kInitiator, mAdminId, nullptr);
// if (err != CHIP_NO_ERROR)
// {
// ChipLogError(Controller, "Failed in setting up CASE secure channel: err %s", ErrorStr(err));
// OnSessionEstablishmentError(err);
// return;
// }
}

void Device::AddResponseHandler(uint8_t seqNum, Callback::Cancelable * onSuccessCallback, Callback::Cancelable * onFailureCallback)
{
mCallbacksMgr.AddResponseCallback(mDeviceId, seqNum, onSuccessCallback, onFailureCallback);
Expand Down
37 changes: 33 additions & 4 deletions src/controller/CHIPDevice.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@
#include <app/util/basic-types.h>
#include <core/CHIPCallback.h>
#include <core/CHIPCore.h>
#include <credentials/CHIPOperationalCredentials.h>
#include <messaging/ExchangeContext.h>
#include <messaging/ExchangeDelegate.h>
#include <messaging/ExchangeMgr.h>
#include <protocols/secure_channel/CASESession.h>
#include <protocols/secure_channel/PASESession.h>
#include <setup_payload/SetupPayload.h>
#include <support/Base64.h>
Expand Down Expand Up @@ -75,12 +77,14 @@ struct ControllerDeviceInitParams
SecureSessionMgr * sessionMgr = nullptr;
Messaging::ExchangeManager * exchangeMgr = nullptr;
Inet::InetLayer * inetLayer = nullptr;

Credentials::OperationalCredentialSet * credentials = nullptr;
#if CONFIG_NETWORK_LAYER_BLE
Ble::BleLayer * bleLayer = nullptr;
#endif
};

class DLL_EXPORT Device : public Messaging::ExchangeDelegate
class DLL_EXPORT Device : public Messaging::ExchangeDelegate, public SessionEstablishmentDelegate
{
public:
~Device()
Expand Down Expand Up @@ -183,6 +187,7 @@ class DLL_EXPORT Device : public Messaging::ExchangeDelegate
mInetLayer = params.inetLayer;
mListenPort = listenPort;
mAdminId = admin;
mCredentials = params.credentials;
#if CONFIG_NETWORK_LAYER_BLE
mBleLayer = params.bleLayer;
#endif
Expand All @@ -198,7 +203,7 @@ class DLL_EXPORT Device : public Messaging::ExchangeDelegate
* all device specifc parameters (address, port, interface etc).
*
* This is not done as part of constructor so that the controller can have a list of
* uninitialzed/unpaired device objects. The object is initialized only when the device
* uninitialized/unpaired device objects. The object is initialized only when the device
* is actually paired.
*
* @param[in] params Wrapper object for transport manager etc.
Expand Down Expand Up @@ -354,6 +359,19 @@ class DLL_EXPORT Device : public Messaging::ExchangeDelegate
void AddIMResponseHandler(Callback::Cancelable * onSuccessCallback, Callback::Cancelable * onFailureCallback);
void CancelIMResponseHandler();

void ProvisioningComplete(uint16_t caseKeyId)
{
mDeviceProvisioningComplete = true;
mCASESessionKeyId = caseKeyId;
}
bool IsProvisioningComplete() const { return mDeviceProvisioningComplete; }

//////////// SessionEstablishmentDelegate Implementation ///////////////
void OnSessionEstablishmentError(CHIP_ERROR error) override;
void OnSessionEstablished() override;

CASESession & GetCASESession() { return mCASESession; }

private:
enum class ConnectionState
{
Expand Down Expand Up @@ -428,9 +446,18 @@ class DLL_EXPORT Device : public Messaging::ExchangeDelegate
*/
void InitCommandSender();

CHIP_ERROR EstablishCASESession();

uint16_t mListenPort;

Transport::AdminId mAdminId = Transport::kUndefinedAdminId;

bool mDeviceProvisioningComplete = false;

CASESession mCASESession;
uint16_t mCASESessionKeyId = 0;

Credentials::OperationalCredentialSet * mCredentials = nullptr;
};

/**
Expand Down Expand Up @@ -479,9 +506,11 @@ typedef struct SerializableDevice
PASESessionSerializable mOpsCreds;
uint64_t mDeviceId; /* This field is serialized in LittleEndian byte order */
uint8_t mDeviceAddr[INET6_ADDRSTRLEN];
uint16_t mDevicePort; /* This field is serialized in LittleEndian byte order */
uint16_t mAdminId; /* This field is serialized in LittleEndian byte order */
uint16_t mDevicePort; /* This field is serialized in LittleEndian byte order */
uint16_t mAdminId; /* This field is serialized in LittleEndian byte order */
uint16_t mCASESessionKeyId; /* This field is serialized in LittleEndian byte order */
uint8_t mDeviceTransport;
uint8_t mDeviceProvisioningComplete;
uint8_t mInterfaceName[kMaxInterfaceName];
} SerializableDevice;

Expand Down
113 changes: 85 additions & 28 deletions src/controller/CHIPDeviceController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -184,9 +184,15 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par
);
SuccessOrExit(err);

err = mAdmins.Init(mStorageDelegate);
SuccessOrExit(err);

admin = mAdmins.AssignAdminId(mAdminId, localDeviceId);
VerifyOrExit(admin != nullptr, err = CHIP_ERROR_NO_MEMORY);

err = mAdmins.LoadFromStorage(mAdminId);
SuccessOrExit(err);

err = mSessionMgr->Init(localDeviceId, mSystemLayer, mTransportMgr, &mAdmins, mMessageCounterManager);
SuccessOrExit(err);

Expand Down Expand Up @@ -228,12 +234,68 @@ CHIP_ERROR DeviceController::Init(NodeId localDeviceId, ControllerInitParams par
mState = State::Initialized;
mLocalDeviceId = localDeviceId;

VerifyOrExit(params.operationalCredentialsDelegate != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);
mOperationalCredentialsDelegate = params.operationalCredentialsDelegate;

err = LoadLocalCredentials(admin);
SuccessOrExit(err);

ReleaseAllDevices();

exit:
return err;
}

CHIP_ERROR DeviceController::LoadLocalCredentials(Transport::AdminPairingInfo * admin)
{
ChipLogProgress(Controller, "Getting operational keys");
Crypto::P256Keypair * keypair = admin->GetOperationalKey();

ReturnErrorCodeIf(keypair == nullptr, CHIP_ERROR_NO_MEMORY);

if (!admin->AreCredentialsAvailable())
{
chip::Platform::ScopedMemoryBuffer<uint8_t> buffer1;
ReturnErrorCodeIf(!buffer1.Alloc(kMaxCHIPOpCertLength), CHIP_ERROR_NO_MEMORY);

chip::Platform::ScopedMemoryBuffer<uint8_t> buffer2;
ReturnErrorCodeIf(!buffer2.Alloc(kMaxCHIPOpCertLength), CHIP_ERROR_NO_MEMORY);

uint8_t * CSR = buffer1.Get();
size_t csrLength = kMaxCHIPOpCertLength;
ReturnErrorOnFailure(keypair->NewCertificateSigningRequest(CSR, csrLength));

uint8_t * cert = buffer2.Get();
uint32_t certLen = 0;

ChipLogProgress(Controller, "Generating operational certificate for the controller");
ReturnErrorOnFailure(mOperationalCredentialsDelegate->GenerateNodeOperationalCertificate(
PeerId().SetNodeId(mLocalDeviceId), ByteSpan(CSR, csrLength), 1, cert, kMaxCHIPOpCertLength, certLen));

uint8_t * chipCert = buffer1.Get();
uint32_t chipCertLen = 0;
ReturnErrorOnFailure(ConvertX509CertToChipCert(cert, certLen, chipCert, kMaxCHIPOpCertLength, chipCertLen));

ReturnErrorOnFailure(admin->SetOperationalCert(ByteSpan(chipCert, chipCertLen)));

ChipLogProgress(Controller, "Getting root certificate for the controller from the issuer");
ReturnErrorOnFailure(mOperationalCredentialsDelegate->GetRootCACertificate(0, cert, kMaxCHIPOpCertLength, certLen));

chipCertLen = 0;
ReturnErrorOnFailure(ConvertX509CertToChipCert(cert, certLen, chipCert, kMaxCHIPOpCertLength, chipCertLen));

ReturnErrorOnFailure(admin->SetRootCert(ByteSpan(chipCert, chipCertLen)));

ReturnErrorOnFailure(mAdmins.Store(admin->GetAdminId()));
}

ChipLogProgress(Controller, "Generating credentials");
ReturnErrorOnFailure(admin->GetCredentials(mCredentials, mCertificates, mRootKeyId));

ChipLogProgress(Controller, "Loaded credentials successfully");
return CHIP_NO_ERROR;
}

CHIP_ERROR DeviceController::Shutdown()
{
VerifyOrReturnError(mState == State::Initialized, CHIP_ERROR_INCORRECT_STATE);
Expand Down Expand Up @@ -406,6 +468,10 @@ CHIP_ERROR DeviceController::GetDevice(NodeId deviceId, Device ** out_device)

CHIP_ERROR DeviceController::UpdateDevice(Device * device, uint64_t fabricId)
{
// TODO - Detect when the device is fully provisioned, instead of relying on UpdateDevice()
device->ProvisioningComplete(mNextKeyId++);
PersistDevice(device);
PersistNextKeyId();
#if CHIP_DEVICE_CONFIG_ENABLE_MDNS
return Mdns::Resolver::Instance().ResolveNodeId(chip::PeerId().SetNodeId(device->GetDeviceId()).SetFabricId(fabricId),
chip::Inet::kIPAddressType_Any);
Expand Down Expand Up @@ -642,6 +708,14 @@ CHIP_ERROR DeviceController::SetPairedDeviceList(const char * serialized)
return err;
}

void DeviceController::PersistNextKeyId()
{
if (mStorageDelegate != nullptr && mState == State::Initialized)
{
mStorageDelegate->SyncSetKeyValue(kNextAvailableKeyID, &mNextKeyId, sizeof(mNextKeyId));
}
}

#if CHIP_DEVICE_CONFIG_ENABLE_MDNS
void DeviceController::OnNodeIdResolved(const chip::Mdns::ResolvedNodeData & nodeData)
{
Expand Down Expand Up @@ -704,9 +778,11 @@ void DeviceController::OnCommissionableNodeFound(const chip::Mdns::Commissionabl

ControllerDeviceInitParams DeviceController::GetControllerDeviceInitParams()
{
return ControllerDeviceInitParams{
.transportMgr = mTransportMgr, .sessionMgr = mSessionMgr, .exchangeMgr = mExchangeMgr, .inetLayer = mInetLayer
};
return ControllerDeviceInitParams{ .transportMgr = mTransportMgr,
.sessionMgr = mSessionMgr,
.exchangeMgr = mExchangeMgr,
.inetLayer = mInetLayer,
.credentials = &mCredentials };
}

DeviceCommissioner::DeviceCommissioner() :
Expand All @@ -722,8 +798,6 @@ DeviceCommissioner::DeviceCommissioner() :

CHIP_ERROR DeviceCommissioner::Init(NodeId localDeviceId, CommissionerInitParams params)
{
VerifyOrReturnError(params.operationalCredentialsDelegate != nullptr, CHIP_ERROR_INVALID_ARGUMENT);

ReturnErrorOnFailure(DeviceController::Init(localDeviceId, params));

uint16_t size = sizeof(mNextKeyId);
Expand All @@ -734,7 +808,6 @@ CHIP_ERROR DeviceCommissioner::Init(NodeId localDeviceId, CommissionerInitParams
}
mPairingDelegate = params.pairingDelegate;

mOperationalCredentialsDelegate = params.operationalCredentialsDelegate;
return CHIP_NO_ERROR;
}

Expand Down Expand Up @@ -1215,20 +1288,12 @@ CHIP_ERROR DeviceCommissioner::SendTrustedRootCertificate(Device * device)
{
VerifyOrReturnError(device != nullptr, CHIP_ERROR_INVALID_ARGUMENT);

chip::Platform::ScopedMemoryBuffer<uint8_t> signingCert;
ReturnErrorCodeIf(!signingCert.Alloc(kMaxCHIPOpCertLength), CHIP_ERROR_NO_MEMORY);
uint32_t signingCertLen = 0;

ChipLogProgress(Controller, "Getting root certificate from the issuer");
ReturnErrorOnFailure(
mOperationalCredentialsDelegate->GetRootCACertificate(0, signingCert.Get(), kMaxCHIPOpCertLength, signingCertLen));

chip::Platform::ScopedMemoryBuffer<uint8_t> chipCert;

ReturnErrorCodeIf(!chipCert.Alloc(kMaxCHIPOpCertLength), CHIP_ERROR_NO_MEMORY);
Transport::AdminPairingInfo * admin = mAdmins.FindAdminWithId(mAdminId);
VerifyOrReturnError(admin != nullptr, CHIP_ERROR_INCORRECT_STATE);

ReturnErrorOnFailure(
ConvertX509CertToChipCert(signingCert.Get(), signingCertLen, chipCert.Get(), kMaxCHIPOpCertLength, signingCertLen));
uint16_t signingCertLen = 0;
const uint8_t * signingCert = admin->GetTrustedRoot(signingCertLen);
VerifyOrReturnError(signingCert != nullptr, CHIP_ERROR_INCORRECT_STATE);

ChipLogProgress(Controller, "Sending root certificate to the device");

Expand All @@ -1239,7 +1304,7 @@ CHIP_ERROR DeviceCommissioner::SendTrustedRootCertificate(Device * device)
Callback::Cancelable * failureCallback = mOnRootCertFailureCallback.Cancel();

ReturnErrorOnFailure(
cluster.AddTrustedRootCertificate(successCallback, failureCallback, ByteSpan(chipCert.Get(), signingCertLen)));
cluster.AddTrustedRootCertificate(successCallback, failureCallback, ByteSpan(signingCert, signingCertLen)));

ChipLogProgress(Controller, "Sent root certificate to the device");

Expand Down Expand Up @@ -1334,14 +1399,6 @@ void DeviceCommissioner::PersistDeviceList()
}
}

void DeviceCommissioner::PersistNextKeyId()
{
if (mStorageDelegate != nullptr && mState == State::Initialized)
{
mStorageDelegate->SyncSetKeyValue(kNextAvailableKeyID, &mNextKeyId, sizeof(mNextKeyId));
}
}

void DeviceCommissioner::ReleaseDevice(Device * device)
{
PersistDeviceList();
Expand Down
Loading

0 comments on commit a15b4ec

Please sign in to comment.