From 11b57246d8830d62512fee654abc0d17e26faad4 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 13 Oct 2022 20:18:52 +0800 Subject: [PATCH 01/44] [Android] Added mechanism to override device attestation failure based on client/user; Commissioner attestation delegate should be able to override success --- .../DeviceProvisioningFragment.kt | 38 ++- .../java/AndroidDeviceControllerWrapper.h | 16 ++ src/controller/java/BUILD.gn | 8 +- .../java/CHIPDeviceController-JNI.cpp | 87 ++++++- .../java/DeviceAttestationDelegateBridge.cpp | 117 +++++++++ .../java/DeviceAttestationDelegateBridge.h | 56 +++++ .../devicecontroller/AttestationInfo.java | 9 + .../ChipDeviceController.java | 229 +++++++++++++++++- .../DeviceAttestationDelegate.java | 48 ++++ src/setup_payload/java/BUILD.gn | 5 +- 10 files changed, 597 insertions(+), 16 deletions(-) create mode 100644 src/controller/java/DeviceAttestationDelegateBridge.cpp create mode 100644 src/controller/java/DeviceAttestationDelegateBridge.h create mode 100644 src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt index f97647ce4ab18a..278c5edb29292e 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt @@ -19,14 +19,19 @@ package com.google.chip.chiptool.provisioning import android.bluetooth.BluetoothGatt +import android.content.DialogInterface import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast +import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope +import chip.devicecontroller.AttestationInfo +import chip.devicecontroller.DeviceAttestationDelegate.DeviceAttestationCompletionCallback +import chip.devicecontroller.DeviceAttestationDelegate.DeviceAttestationFailureCallback import chip.devicecontroller.NetworkCredentials import com.google.chip.chiptool.ChipClient import com.google.chip.chiptool.GenericChipDeviceListener @@ -37,6 +42,7 @@ import com.google.chip.chiptool.util.DeviceIdUtil import com.google.chip.chiptool.util.FragmentUtil import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.Runnable import kotlinx.coroutines.launch @ExperimentalCoroutinesApi @@ -120,7 +126,37 @@ class DeviceProvisioningFragment : Fragment() { val deviceId = DeviceIdUtil.getNextAvailableId(requireContext()) val connId = bluetoothManager.connectionId - deviceController.pairDevice(gatt, connId, deviceId, deviceInfo.setupPinCode, networkCredentials) + deviceController.pairDevice(gatt, connId, deviceId, deviceInfo.setupPinCode, null, networkCredentials, object: DeviceAttestationFailureCallback { + override fun onDeviceAttestationFailed( + deviceControllerPtr: Long, + devicePtr: Long, + errorCode: Int + ) { + requireActivity().runOnUiThread(Runnable { + val alertDialog: AlertDialog? = activity?.let { + val builder = AlertDialog.Builder(it) + builder.apply { + setPositiveButton("Continue", + DialogInterface.OnClickListener { dialog, id -> + deviceController.continueCommissioning(devicePtr, true) + }) + setNegativeButton("No", + DialogInterface.OnClickListener { dialog, id -> + deviceController.continueCommissioning(devicePtr, false) + }) + } + builder.setTitle("Device Attestation") + builder.setMessage("Device Attestation failed for device under commissioning. Do you wish to continue pairing?") + + // Create the AlertDialog + builder.create() + } + alertDialog?.show() + }) + } + + + }, 600) DeviceIdUtil.setNextAvailableId(requireContext(), deviceId + 1) } } diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index c1421863bbf29d..252b1bbf710c5e 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -33,6 +33,7 @@ #include #include "AndroidOperationalCredentialsIssuer.h" +#include "DeviceAttestationDelegateBridge.h" /** * This class contains all relevant information for the JNI view of CHIPDeviceController @@ -157,6 +158,19 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel return mOpCredsIssuer.get(); } + void SetDeviceAttestationDelegateBridge(DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge) { mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; } + + DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } + + void ClearDeviceAttestationDelegateBridge() + { + if(mDeviceAttestationDelegateBridge != nullptr) + { + delete mDeviceAttestationDelegateBridge; + mDeviceAttestationDelegateBridge = nullptr; + } + } + private: using ChipDeviceControllerPtr = std::unique_ptr; @@ -187,6 +201,8 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Credentials::PartialDACVerifier mPartialDACVerifier; + DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; + AndroidDeviceControllerWrapper(ChipDeviceControllerPtr controller, AndroidOperationalCredentialsIssuerPtr opCredsIssuer) : mController(std::move(controller)), mOpCredsIssuer(std::move(opCredsIssuer)) {} diff --git a/src/controller/java/BUILD.gn b/src/controller/java/BUILD.gn index 61244807707b8b..2c6ad4cbff3062 100644 --- a/src/controller/java/BUILD.gn +++ b/src/controller/java/BUILD.gn @@ -37,6 +37,8 @@ shared_library("jni") { "CHIPDefaultCallbacks.cpp", "CHIPDefaultCallbacks.h", "CHIPDeviceController-JNI.cpp", + "DeviceAttestationDelegateBridge.cpp", + "DeviceAttestationDelegateBridge.h", "zap-generated/CHIPAttributeTLVValueDecoder.cpp", "zap-generated/CHIPClustersWrite-JNI.cpp", "zap-generated/CHIPEventTLVValueDecoder.cpp", @@ -91,6 +93,7 @@ android_library("java") { "src/chip/devicecontroller/ChipDeviceController.java", "src/chip/devicecontroller/ChipDeviceControllerException.java", "src/chip/devicecontroller/ControllerParams.java", + "src/chip/devicecontroller/DeviceAttestationDelegate.java", "src/chip/devicecontroller/DiscoveredDevice.java", "src/chip/devicecontroller/GetConnectedDeviceCallbackJni.java", "src/chip/devicecontroller/KeypairDelegate.java", @@ -122,7 +125,10 @@ android_library("java") { "zap-generated/chip/devicecontroller/ClusterWriteMapping.java", ] - javac_flags = [ "-Xlint:deprecation" ] + javac_flags = [ + "-Xlint:deprecation", + "-parameters", # Store infomation about method parameters + ] # TODO: add classpath support (we likely need to add something like # ..../platforms/android-21/android.jar to access BLE items) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 6c047d8f9adf86..459808bf6aeca0 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -80,6 +80,8 @@ static CHIP_ERROR ParseAttributePath(jobject attributePath, EndpointId & outEndp static CHIP_ERROR ParseEventPathList(jobject eventPathList, std::vector & outEventPathParamsList); static CHIP_ERROR ParseEventPath(jobject eventPath, EndpointId & outEndpointId, ClusterId & outClusterId, EventId & outEventId); static CHIP_ERROR IsWildcardChipPathId(jobject chipPathId, bool & isWildcard); +static CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, + DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge); namespace { @@ -382,7 +384,8 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr } JNI_METHOD(void, commissionDevice) -(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jbyteArray csrNonce, jobject networkCredentials) +(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jbyteArray csrNonce, jobject networkCredentials, + jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -396,7 +399,16 @@ JNI_METHOD(void, commissionDevice) err = wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_ERROR_INVALID_ARGUMENT); } - + if (deviceAttestationDelegate != nullptr) + { + wrapper->ClearDeviceAttestationDelegateBridge(); + DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, + failSafeExpiryTimeout, &deviceAttestationDelegateBridge); + VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); + wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); + commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); + } if (csrNonce != nullptr) { JniByteArray jniCsrNonce(env, csrNonce); @@ -413,7 +425,7 @@ JNI_METHOD(void, commissionDevice) JNI_METHOD(void, pairDevice) (JNIEnv * env, jobject self, jlong handle, jlong deviceId, jint connObj, jlong pinCode, jbyteArray csrNonce, - jobject networkCredentials) + jobject networkCredentials, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -436,8 +448,18 @@ JNI_METHOD(void, pairDevice) JniByteArray jniCsrNonce(env, csrNonce); commissioningParams.SetCSRNonce(jniCsrNonce.byteSpan()); } + if (deviceAttestationDelegate != nullptr) + { + wrapper->ClearDeviceAttestationDelegateBridge(); + DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, + failSafeExpiryTimeout, &deviceAttestationDelegateBridge); + VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); + wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); + commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); + } err = wrapper->Controller()->PairDevice(deviceId, rendezvousParams, commissioningParams); - +exit: if (err != CHIP_NO_ERROR) { ChipLogError(Controller, "Failed to pair the device."); @@ -447,7 +469,7 @@ JNI_METHOD(void, pairDevice) JNI_METHOD(void, pairDeviceWithAddress) (JNIEnv * env, jobject self, jlong handle, jlong deviceId, jstring address, jint port, jint discriminator, jlong pinCode, - jbyteArray csrNonce) + jbyteArray csrNonce, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -469,8 +491,18 @@ JNI_METHOD(void, pairDeviceWithAddress) JniByteArray jniCsrNonce(env, csrNonce); commissioningParams.SetCSRNonce(jniCsrNonce.byteSpan()); } + if (deviceAttestationDelegate != nullptr) + { + wrapper->ClearDeviceAttestationDelegateBridge(); + DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, + failSafeExpiryTimeout, &deviceAttestationDelegateBridge); + VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); + wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); + commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); + } err = wrapper->Controller()->PairDevice(deviceId, rendezvousParams, commissioningParams); - +exit: if (err != CHIP_NO_ERROR) { ChipLogError(Controller, "Failed to pair the device."); @@ -521,6 +553,27 @@ JNI_METHOD(void, establishPaseConnectionByAddress) } } +JNI_METHOD(void, continueCommissioning) +(JNIEnv * env, jobject self, jlong handle, jlong devicePtr, jboolean ignoreAttestationFailure) +{ + chip::DeviceLayer::StackLock lock; + ChipLogProgress(Controller, "continueCommissioning() called."); + CHIP_ERROR err = CHIP_NO_ERROR; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = wrapper->GetDeviceAttestationDelegateBridge(); + auto lastAttestationResult = deviceAttestationDelegateBridge ? deviceAttestationDelegateBridge->attestationVerificationResult() + : chip::Credentials::AttestationVerificationResult::kSuccess; + chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); + err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to continue commissioning."); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } +} + JNI_METHOD(void, setUseJavaCallbackForNOCRequest) (JNIEnv * env, jobject self, jlong handle, jboolean useCallback) { @@ -1367,3 +1420,25 @@ CHIP_ERROR N2J_NetworkLocation(JNIEnv * env, jstring ipAddress, jint port, jint exit: return err; } + +CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, + DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeout)); + bool shouldWaitAfterDeviceAttestation = false; + jclass completionCallbackCls = nullptr; + jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); + VerifyOrExit(deviceAttestationDelegateRef != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT); + JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", + completionCallbackCls); + VerifyOrExit(completionCallbackCls != nullptr, err = CHIP_JNI_ERROR_TYPE_NOT_FOUND); + + if(env->IsInstanceOf(deviceAttestationDelegate, completionCallbackCls)) + { + shouldWaitAfterDeviceAttestation = true; + } + *deviceAttestationDelegateBridge = new DeviceAttestationDelegateBridge(handle, deviceAttestationDelegateRef, timeoutSecs, shouldWaitAfterDeviceAttestation); +exit: + return err; +} \ No newline at end of file diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp new file mode 100644 index 00000000000000..9510dac4c60cff --- /dev/null +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -0,0 +1,117 @@ +/** + * + * Copyright (c) 2020 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. + */ + +#include "DeviceAttestationDelegateBridge.h" +#include +#include +#include +#include +#include + +using namespace chip; + +CHIP_ERROR N2J_AttestationInfo(JNIEnv * env, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + jobject & outAttestationInfo) +{ + CHIP_ERROR err = CHIP_NO_ERROR; + jclass infoClass = nullptr; + jmethodID constructor = nullptr; + jbyteArray javaDAC = nullptr; + jbyteArray javaPAI = nullptr; + jbyteArray javaCD = nullptr; + const ByteSpan DAC = info.dacDerBuffer(); + const ByteSpan PAI = info.paiDerBuffer(); + const Optional certificationDeclarationSpan = info.cdBuffer(); + + err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/AttestationInfo", infoClass); + JniClass attestationInfoClass(infoClass); + SuccessOrExit(err); + + env->ExceptionClear(); + constructor = env->GetMethodID(infoClass, "", "([B[B[B)V"); + VerifyOrExit(constructor != nullptr, err = CHIP_JNI_ERROR_METHOD_NOT_FOUND); + + err = JniReferences::GetInstance().N2J_ByteArray(env, DAC.data(), DAC.size(), javaDAC); + SuccessOrExit(err); + err = JniReferences::GetInstance().N2J_ByteArray(env, PAI.data(), PAI.size(), javaPAI); + SuccessOrExit(err); + if(certificationDeclarationSpan.HasValue()) + { + err = JniReferences::GetInstance().N2J_ByteArray(env, certificationDeclarationSpan.Value().data(), certificationDeclarationSpan.Value().size(), + javaCD); + SuccessOrExit(err); + } + outAttestationInfo = (jobject) env->NewObject(infoClass, constructor, javaDAC, javaPAI, javaCD); + VerifyOrExit(!env->ExceptionCheck(), err = CHIP_JNI_ERROR_EXCEPTION_THROWN); +exit: + return err; +} + +void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, + chip::DeviceProxy * device, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) +{ + ChipLogProgress(Controller, "OnDeviceAttestationCompleted with result: %hu", attestationResult); + + mResult = attestationResult; + if(mDeviceAttestationDelegate != nullptr) + { + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jclass completionCallbackCls = nullptr; + JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", + completionCallbackCls); + VerifyOrReturn(completionCallbackCls != nullptr, + ChipLogError(Controller, "Could not find device attestation completion callback class.")); + jclass failureCallbackCls = nullptr; + JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationFailureCallback", + failureCallbackCls); + VerifyOrReturn(failureCallbackCls != nullptr, + ChipLogError(Controller, "Could not find device attestation failure callback class.")); + + if(env->IsInstanceOf(mDeviceAttestationDelegate, completionCallbackCls)) + { + jmethodID onDeviceAttestationCompletedMethod; + JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationCompleted", "(JJLchip/devicecontroller/AttestationInfo;I)V", &onDeviceAttestationCompletedMethod); + VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation completed method")); + jobject javaAttestationInfo; + CHIP_ERROR err = N2J_AttestationInfo(env, info, javaAttestationInfo); + VerifyOrReturn(err == CHIP_NO_ERROR, + ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, mDeviceController, reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); + } + else if((attestationResult != chip::Credentials::AttestationVerificationResult::kSuccess) && + env->IsInstanceOf(mDeviceAttestationDelegate, failureCallbackCls)) + { + jmethodID onDeviceAttestationFailedMethod; + JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationFailed", "(JJI)V", &onDeviceAttestationFailedMethod); + VerifyOrReturn(onDeviceAttestationFailedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation failed method")); + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationFailedMethod, mDeviceController, reinterpret_cast(device), static_cast(attestationResult)); + } + } + +} + +DeviceAttestationDelegateBridge::~DeviceAttestationDelegateBridge() +{ + if(mDeviceAttestationDelegate != nullptr) + { + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + env->DeleteGlobalRef(mDeviceAttestationDelegate); + mDeviceAttestationDelegate = nullptr; + } +} \ No newline at end of file diff --git a/src/controller/java/DeviceAttestationDelegateBridge.h b/src/controller/java/DeviceAttestationDelegateBridge.h new file mode 100644 index 00000000000000..ada1dec48126d2 --- /dev/null +++ b/src/controller/java/DeviceAttestationDelegateBridge.h @@ -0,0 +1,56 @@ +/** + * + * Copyright (c) 2020 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. + */ + +#include +#include +#include + +#include + +class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestationDelegate { +public: + DeviceAttestationDelegateBridge(jlong deviceController, + jobject deviceAttestationDelegate, + chip::Optional expiryTimeoutSecs, + bool shouldWaitAfterDeviceAttestation) + : mResult(chip::Credentials::AttestationVerificationResult::kSuccess) + , mDeviceController(deviceController) + , mDeviceAttestationDelegate(deviceAttestationDelegate) + , mExpiryTimeoutSecs(expiryTimeoutSecs) + , mShouldWaitAfterDeviceAttestation(shouldWaitAfterDeviceAttestation) + { + } + + ~DeviceAttestationDelegateBridge(); + + chip::Optional FailSafeExpiryTimeoutSecs() const override { return mExpiryTimeoutSecs; } + + void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, + chip::DeviceProxy * device, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) override; + + bool ShouldWaitAfterDeviceAttestation() override { return mShouldWaitAfterDeviceAttestation; } + + chip::Credentials::AttestationVerificationResult attestationVerificationResult() const { return mResult; } + +private: + chip::Credentials::AttestationVerificationResult mResult; + jlong mDeviceController; + jobject mDeviceAttestationDelegate = nullptr; + chip::Optional mExpiryTimeoutSecs; + const bool mShouldWaitAfterDeviceAttestation; +}; \ No newline at end of file diff --git a/src/controller/java/src/chip/devicecontroller/AttestationInfo.java b/src/controller/java/src/chip/devicecontroller/AttestationInfo.java index cfa4e115ef28cd..3979d67f88f865 100644 --- a/src/controller/java/src/chip/devicecontroller/AttestationInfo.java +++ b/src/controller/java/src/chip/devicecontroller/AttestationInfo.java @@ -12,6 +12,15 @@ public final class AttestationInfo { private byte[] certificationDeclaration; private byte[] firmwareInfo; + public AttestationInfo( + byte[] dac, + byte[] pai, + byte[] certificationDeclaration) { + this.dac = dac; + this.pai = pai; + this.certificationDeclaration = certificationDeclaration; + } + public AttestationInfo( byte[] challenge, byte[] nonce, diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 62ed67132871d1..78d32f0378715f 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -20,6 +20,7 @@ import android.bluetooth.BluetoothGatt; import android.util.Log; import androidx.annotation.Nullable; +import chip.devicecontroller.DeviceAttestationDelegate.DeviceAttestationCompletionCallback; import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback; import chip.devicecontroller.model.ChipAttributePath; import chip.devicecontroller.model.ChipEventPath; @@ -122,7 +123,116 @@ public void pairDevice( Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); Log.d(TAG, "Pairing device with ID: " + deviceId); pairDevice( - deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials); + deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials, null, 0); + } else { + Log.e(TAG, "Bluetooth connection already in use."); + completionListener.onError(new Exception("Bluetooth connection already in use.")); + } + } + + /** + * Pair a device connected through BLE. + * + * If the completionCallback non-null, when + * {@link DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, long, AttestationInfo, int)} + * is received, {@link #continueCommissioning(long, boolean)} must be called. + * + * @param bleServer the BluetoothGatt representing the BLE + * connection to the + * device + * @param connId the BluetoothGatt Id representing the BLE + * connection to + * the device + * @param deviceId the node ID to assign to the device + * @param setupPincode the pincode for the device + * @param csrNonce the 32-byte CSR nonce to use, or null if we want + * to use an internally randomlygenerated CSR + * nonce. + * @param networkCredentials the credentials (Wi-Fi or Thread) to be + * provisioned + * @param completionCallback the callback will be invoked when + * deviceattestation completed with device + * info for additional verification. + * @param failSafeExpiryTimeout the value to set for the fail-safe timer before + * onDeviceAttestationCompleted is invoked. + */ + public void pairDevice( + BluetoothGatt bleServer, + int connId, + long deviceId, + long setupPincode, + @Nullable byte[] csrNonce, + NetworkCredentials networkCredentials, + @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, + int failSafeExpiryTimeout) { + if (connectionId == 0) { + connectionId = connId; + + if (connectionId == 0) { + Log.e(TAG, "Failed to add Bluetooth connection."); + completionListener.onError(new Exception("Failed to add Bluetooth connection.")); + return; + } + + Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); + Log.d(TAG, "Pairing device with ID: " + deviceId); + pairDevice( + deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials, + completionCallback, failSafeExpiryTimeout); + } else { + Log.e(TAG, "Bluetooth connection already in use."); + completionListener.onError(new Exception("Bluetooth connection already in use.")); + } + } + + /** + * Pair a device connected through BLE. + * + * If the failureCallback non-null, when + * {@link DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, long, int)} + * is received, {@link #continueCommissioning(long, boolean)} must be called. + * + * @param bleServer the BluetoothGatt representing the BLE + * connection to the + * device + * @param connId the BluetoothGatt Id representing the BLE + * connection to + * the device + * @param deviceId the node ID to assign to the device + * @param setupPincode the pincode for the device + * @param csrNonce the 32-byte CSR nonce to use, or null if we want + * to use an internally randomly generated CSR + * nonce. + * @param networkCredentials the credentials (Wi-Fi or Thread) to be + * provisioned + * @param failureCallback the callback will be invoked when device + * attestation failed. + * @param failSafeExpiryTimeout the value to set for the fail-safe timer before + * onDeviceAttestationFailed is invoked. + */ + public void pairDevice( + BluetoothGatt bleServer, + int connId, + long deviceId, + long setupPincode, + @Nullable byte[] csrNonce, + NetworkCredentials networkCredentials, + @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, + int failSafeExpiryTimeout) { + if (connectionId == 0) { + connectionId = connId; + + if (connectionId == 0) { + Log.e(TAG, "Failed to add Bluetooth connection."); + completionListener.onError(new Exception("Failed to add Bluetooth connection.")); + return; + } + + Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); + Log.d(TAG, "Pairing device with ID: " + deviceId); + pairDevice( + deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials, + failureCallback, failSafeExpiryTimeout); } else { Log.e(TAG, "Bluetooth connection already in use."); completionListener.onError(new Exception("Bluetooth connection already in use.")); @@ -137,7 +247,36 @@ public void pairDeviceWithAddress( long pinCode, @Nullable byte[] csrNonce) { pairDeviceWithAddress( - deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce); + deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce, null, 0); + } + + public void pairDeviceWithAddress( + long deviceId, + String address, + int port, + int discriminator, + long pinCode, + @Nullable byte[] csrNonce, + @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, + int failSafeExpiryTimeout) { + pairDeviceWithAddress( + deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce, completionCallback, + failSafeExpiryTimeout); + } + + public void pairDeviceWithAddress( + long deviceId, + String address, + int port, + int discriminator, + long pinCode, + @Nullable byte[] csrNonce, + @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, + int failSafeExpiryTimeout) { + pairDeviceWithAddress( + deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce, + failureCallback, + failSafeExpiryTimeout); } public void establishPaseConnection(long deviceId, int connId, long setupPincode) { @@ -181,7 +320,7 @@ public void establishPaseConnection(long deviceId, String address, int port, lon * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice(long deviceId, @Nullable NetworkCredentials networkCredentials) { - commissionDevice(deviceControllerPtr, deviceId, /* csrNonce= */ null, networkCredentials); + commissionDevice(deviceControllerPtr, deviceId, /* csrNonce= */ null, networkCredentials, null, 0); } /** @@ -195,9 +334,76 @@ public void commissionDevice(long deviceId, @Nullable NetworkCredentials network */ public void commissionDevice( long deviceId, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials) { - commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials); + commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials, null, 0); + } + + /** + * Initiates the automatic commissioning flow using the specified network + * credentials. It is + * expected that a secure session has already been established via {@link + * #establishPaseConnection(long, int, long)}. + * + * If the completionCallback non-null, when + * {@link DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, long, AttestationInfo, int)} + * is received, {@link #continueCommissioning(long, boolean)} must be called. + * + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request + * @param networkCredentials the credentials (Wi-Fi or Thread) to be + * provisioned + * @param completionCallback the callback will be invoked when device + * attestation completed with device + * info for additional verification. + * @param failSafeExpiryTimeout the value to set for the fail-safe timer before + * onDeviceAttestationCompleted is invoked. + */ + public void commissionDevice( + long deviceId, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials, + @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, + int failSafeExpiryTimeout) { + commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials, completionCallback, + failSafeExpiryTimeout); + } + + /** + * Initiates the automatic commissioning flow using the specified network + * credentials. It is + * expected that a secure session has already been established via {@link + * #establishPaseConnection(long, int, long)}. + * + * If the failureCallback non-null, when + * {@link DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, long, int)} + * is received, {@link #continueCommissioning(long, boolean)} must be called. + * + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request + * @param networkCredentials the credentials (Wi-Fi or Thread) to be + * provisioned + * @param failureCallback the callback will be invoked when device + * attestation failed. + * @param failSafeExpiryTimeout the value to set for the fail-safe timer before + * onDeviceAttestationFailed is invoked. + */ + public void commissionDevice( + long deviceId, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials, + @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, + int failSafeExpiryTimeout) { + commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials, + failureCallback, + failSafeExpiryTimeout); } + /** + * This function instructs the commissioner to proceed to the next stage of + * commissioning after attestation is reported. + * + * @param devicePtr a pointer to the device which is being + * commissioned. + * @param ignoreAttestationFailure whether to ignore device attestation failure. + */ + public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailure) { + continueCommissioning(deviceControllerPtr, devicePtr, ignoreAttestationFailure); + } /** * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be * called when the NOC CSR needs to be signed. This allows for custom credentials issuer @@ -618,7 +824,9 @@ private native void pairDevice( int connectionId, long pinCode, @Nullable byte[] csrNonce, - NetworkCredentials networkCredentials); + NetworkCredentials networkCredentials, + @Nullable DeviceAttestationDelegate delegate, + int failSafeExpiryTimeout); private native void pairDeviceWithAddress( long deviceControllerPtr, @@ -627,7 +835,9 @@ private native void pairDeviceWithAddress( int port, int discriminator, long pinCode, - @Nullable byte[] csrNonce); + @Nullable byte[] csrNonce, + @Nullable DeviceAttestationDelegate delegate, + int failSafeExpiryTimeout); private native void establishPaseConnection( long deviceControllerPtr, long deviceId, int connId, long setupPincode); @@ -639,7 +849,12 @@ private native void commissionDevice( long deviceControllerPtr, long deviceId, @Nullable byte[] csrNonce, - @Nullable NetworkCredentials networkCredentials); + @Nullable NetworkCredentials networkCredentials, + @Nullable DeviceAttestationDelegate delegate, + int failSafeExpiryTimeout); + + private native void continueCommissioning( + long deviceControllerPtr, long devicePtr, boolean ignoreAttestationFailure); private native void unpairDevice(long deviceControllerPtr, long deviceId); diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java new file mode 100644 index 00000000000000..2dfe68d10dbb43 --- /dev/null +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -0,0 +1,48 @@ +package chip.devicecontroller; + +/** + * Only one of the following delegate callbacks should be implemented. + *

+ * If DeviceAttestationFailureCallback is implemented, then it will be called + * when device + * attestation fails, and the client can decide to continue or stop the + * commissioning. + *

+ * If DeviceAttestationFailureCallback is implemented, then it + * will always be called when device attestation completes. + */ +public interface DeviceAttestationDelegate { + + public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { + /** + * The callback will be invoked when device attestation completed with device + * info for additional verification. + * If this callback is implemented, continueCommissioningDevice on + * {@link ChipDeviceController} is expected + * to be called if commissioning should continue. + *

+ * This allows the callback to stop commissioning after examining the device + * info (DAC, PAI, CD). + * + * @param deviceControllerPtr Controller corresponding to the commissioning + * process + * @param devicePtr Handle of device being commissioned + * @param attestationInfo Attestation information for the device + * @param errorCode Error code on attestation failure. 0 if success. + */ + void onDeviceAttestationCompleted(long deviceControllerPtr, long devicePtr, AttestationInfo attestationInfo, + int errorCode); + } + + public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { + /** + * The callback will be invoked when device attestation failed. + * + * @param deviceControllerPtr Controller corresponding to the commissioning + * process + * @param devicePtr Handle of device being commissioned + * @param errorCode Error code for the failure. + */ + void onDeviceAttestationFailed(long deviceControllerPtr, long devicePtr, int errorCode); + } +} diff --git a/src/setup_payload/java/BUILD.gn b/src/setup_payload/java/BUILD.gn index f2b922a2a34b2d..1188190c6eb8aa 100644 --- a/src/setup_payload/java/BUILD.gn +++ b/src/setup_payload/java/BUILD.gn @@ -46,7 +46,10 @@ android_library("java") { "src/chip/setuppayload/SetupPayloadParser.java", ] - javac_flags = [ "-Xlint:deprecation" ] + javac_flags = [ + "-Xlint:deprecation", + "-parameters" # Store infomation about method parameters + ] # TODO: add classpath support (we likely need to add something like # ..../platforms/android-21/android.jar to access BLE items) From d36248ab1c013fbfaf4468802773a7f278e0de33 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 14 Oct 2022 11:09:19 +0800 Subject: [PATCH 02/44] platform jar keep name of method parameters --- src/platform/android/BUILD.gn | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/platform/android/BUILD.gn b/src/platform/android/BUILD.gn index be0da30f597b29..80957191e3b906 100644 --- a/src/platform/android/BUILD.gn +++ b/src/platform/android/BUILD.gn @@ -99,7 +99,10 @@ android_library("java") { "java/chip/platform/ServiceResolver.java", ] - javac_flags = [ "-Xlint:deprecation" ] + javac_flags = [ + "-Xlint:deprecation", + "-parameters", # Store infomation about method parameters + ] } java_prebuilt("android_sdk") { From 1c38401184870122f2b2191d42b1639e7017bfe3 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 14 Oct 2022 03:09:43 +0000 Subject: [PATCH 03/44] Restyled by whitespace --- .../java/CHIPDeviceController-JNI.cpp | 18 +++++++++--------- .../java/DeviceAttestationDelegateBridge.cpp | 6 +++--- .../java/DeviceAttestationDelegateBridge.h | 6 +++--- .../devicecontroller/ChipDeviceController.java | 10 +++++----- 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 459808bf6aeca0..8763f71988bd57 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -80,7 +80,7 @@ static CHIP_ERROR ParseAttributePath(jobject attributePath, EndpointId & outEndp static CHIP_ERROR ParseEventPathList(jobject eventPathList, std::vector & outEventPathParamsList); static CHIP_ERROR ParseEventPath(jobject eventPath, EndpointId & outEndpointId, ClusterId & outClusterId, EventId & outEventId); static CHIP_ERROR IsWildcardChipPathId(jobject chipPathId, bool & isWildcard); -static CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, +static CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge); namespace { @@ -403,7 +403,7 @@ JNI_METHOD(void, commissionDevice) { wrapper->ClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); @@ -452,7 +452,7 @@ JNI_METHOD(void, pairDevice) { wrapper->ClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); @@ -495,7 +495,7 @@ JNI_METHOD(void, pairDeviceWithAddress) { wrapper->ClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); @@ -1421,19 +1421,19 @@ CHIP_ERROR N2J_NetworkLocation(JNIEnv * env, jstring ipAddress, jint port, jint return err; } -CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, +CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge) { CHIP_ERROR err = CHIP_NO_ERROR; chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeout)); bool shouldWaitAfterDeviceAttestation = false; jclass completionCallbackCls = nullptr; - jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); + jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); VerifyOrExit(deviceAttestationDelegateRef != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT); JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", - completionCallbackCls); + completionCallbackCls); VerifyOrExit(completionCallbackCls != nullptr, err = CHIP_JNI_ERROR_TYPE_NOT_FOUND); - + if(env->IsInstanceOf(deviceAttestationDelegate, completionCallbackCls)) { shouldWaitAfterDeviceAttestation = true; @@ -1441,4 +1441,4 @@ CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, job *deviceAttestationDelegateBridge = new DeviceAttestationDelegateBridge(handle, deviceAttestationDelegateRef, timeoutSecs, shouldWaitAfterDeviceAttestation); exit: return err; -} \ No newline at end of file +} diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index 9510dac4c60cff..c69e408b0ae96d 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -89,7 +89,7 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted(chip::Control VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation completed method")); jobject javaAttestationInfo; CHIP_ERROR err = N2J_AttestationInfo(env, info, javaAttestationInfo); - VerifyOrReturn(err == CHIP_NO_ERROR, + VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, mDeviceController, reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); } @@ -102,7 +102,7 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted(chip::Control env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationFailedMethod, mDeviceController, reinterpret_cast(device), static_cast(attestationResult)); } } - + } DeviceAttestationDelegateBridge::~DeviceAttestationDelegateBridge() @@ -114,4 +114,4 @@ DeviceAttestationDelegateBridge::~DeviceAttestationDelegateBridge() env->DeleteGlobalRef(mDeviceAttestationDelegate); mDeviceAttestationDelegate = nullptr; } -} \ No newline at end of file +} diff --git a/src/controller/java/DeviceAttestationDelegateBridge.h b/src/controller/java/DeviceAttestationDelegateBridge.h index ada1dec48126d2..30bb8e30745d5c 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.h +++ b/src/controller/java/DeviceAttestationDelegateBridge.h @@ -25,7 +25,7 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestat public: DeviceAttestationDelegateBridge(jlong deviceController, jobject deviceAttestationDelegate, - chip::Optional expiryTimeoutSecs, + chip::Optional expiryTimeoutSecs, bool shouldWaitAfterDeviceAttestation) : mResult(chip::Credentials::AttestationVerificationResult::kSuccess) , mDeviceController(deviceController) @@ -39,7 +39,7 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestat chip::Optional FailSafeExpiryTimeoutSecs() const override { return mExpiryTimeoutSecs; } - void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, + void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, chip::Credentials::AttestationVerificationResult attestationResult) override; @@ -53,4 +53,4 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestat jobject mDeviceAttestationDelegate = nullptr; chip::Optional mExpiryTimeoutSecs; const bool mShouldWaitAfterDeviceAttestation; -}; \ No newline at end of file +}; diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 78d32f0378715f..1c2d544c8d7dae 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -132,7 +132,7 @@ public void pairDevice( /** * Pair a device connected through BLE. - * + * * If the completionCallback non-null, when * {@link DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, long, AttestationInfo, int)} * is received, {@link #continueCommissioning(long, boolean)} must be called. @@ -187,7 +187,7 @@ public void pairDevice( /** * Pair a device connected through BLE. - * + * * If the failureCallback non-null, when * {@link DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, long, int)} * is received, {@link #continueCommissioning(long, boolean)} must be called. @@ -342,7 +342,7 @@ public void commissionDevice( * credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. - * + * * If the completionCallback non-null, when * {@link DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, long, AttestationInfo, int)} * is received, {@link #continueCommissioning(long, boolean)} must be called. @@ -370,7 +370,7 @@ public void commissionDevice( * credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. - * + * * If the failureCallback non-null, when * {@link DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, long, int)} * is received, {@link #continueCommissioning(long, boolean)} must be called. @@ -396,7 +396,7 @@ public void commissionDevice( /** * This function instructs the commissioner to proceed to the next stage of * commissioning after attestation is reported. - * + * * @param devicePtr a pointer to the device which is being * commissioned. * @param ignoreAttestationFailure whether to ignore device attestation failure. From 587ac5f3bc1bea2469d9a098279030494d71d76a Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 14 Oct 2022 03:09:46 +0000 Subject: [PATCH 04/44] Restyled by google-java-format --- .../devicecontroller/AttestationInfo.java | 5 +- .../ChipDeviceController.java | 188 ++++++++++-------- .../DeviceAttestationDelegate.java | 72 +++---- 3 files changed, 141 insertions(+), 124 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/AttestationInfo.java b/src/controller/java/src/chip/devicecontroller/AttestationInfo.java index 3979d67f88f865..097d6b8ecaf369 100644 --- a/src/controller/java/src/chip/devicecontroller/AttestationInfo.java +++ b/src/controller/java/src/chip/devicecontroller/AttestationInfo.java @@ -12,10 +12,7 @@ public final class AttestationInfo { private byte[] certificationDeclaration; private byte[] firmwareInfo; - public AttestationInfo( - byte[] dac, - byte[] pai, - byte[] certificationDeclaration) { + public AttestationInfo(byte[] dac, byte[] pai, byte[] certificationDeclaration) { this.dac = dac; this.pai = pai; this.certificationDeclaration = certificationDeclaration; diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 1c2d544c8d7dae..31c2e2f163bbab 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -20,7 +20,6 @@ import android.bluetooth.BluetoothGatt; import android.util.Log; import androidx.annotation.Nullable; -import chip.devicecontroller.DeviceAttestationDelegate.DeviceAttestationCompletionCallback; import chip.devicecontroller.GetConnectedDeviceCallbackJni.GetConnectedDeviceCallback; import chip.devicecontroller.model.ChipAttributePath; import chip.devicecontroller.model.ChipEventPath; @@ -123,7 +122,14 @@ public void pairDevice( Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); Log.d(TAG, "Pairing device with ID: " + deviceId); pairDevice( - deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials, null, 0); + deviceControllerPtr, + deviceId, + connectionId, + setupPincode, + csrNonce, + networkCredentials, + null, + 0); } else { Log.e(TAG, "Bluetooth connection already in use."); completionListener.onError(new Exception("Bluetooth connection already in use.")); @@ -133,28 +139,22 @@ public void pairDevice( /** * Pair a device connected through BLE. * - * If the completionCallback non-null, when - * {@link DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, long, AttestationInfo, int)} - * is received, {@link #continueCommissioning(long, boolean)} must be called. + *

If the completionCallback non-null, when {@link + * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, + * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be + * called. * - * @param bleServer the BluetoothGatt representing the BLE - * connection to the - * device - * @param connId the BluetoothGatt Id representing the BLE - * connection to - * the device - * @param deviceId the node ID to assign to the device - * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want - * to use an internally randomlygenerated CSR - * nonce. - * @param networkCredentials the credentials (Wi-Fi or Thread) to be - * provisioned - * @param completionCallback the callback will be invoked when - * deviceattestation completed with device - * info for additional verification. + * @param bleServer the BluetoothGatt representing the BLE connection to the device + * @param connId the BluetoothGatt Id representing the BLE connection to the device + * @param deviceId the node ID to assign to the device + * @param setupPincode the pincode for the device + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally + * randomlygenerated CSR nonce. + * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned + * @param completionCallback the callback will be invoked when deviceattestation completed with + * device info for additional verification. * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationCompleted is invoked. + * onDeviceAttestationCompleted is invoked. */ public void pairDevice( BluetoothGatt bleServer, @@ -177,8 +177,14 @@ public void pairDevice( Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); Log.d(TAG, "Pairing device with ID: " + deviceId); pairDevice( - deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials, - completionCallback, failSafeExpiryTimeout); + deviceControllerPtr, + deviceId, + connectionId, + setupPincode, + csrNonce, + networkCredentials, + completionCallback, + failSafeExpiryTimeout); } else { Log.e(TAG, "Bluetooth connection already in use."); completionListener.onError(new Exception("Bluetooth connection already in use.")); @@ -188,27 +194,20 @@ public void pairDevice( /** * Pair a device connected through BLE. * - * If the failureCallback non-null, when - * {@link DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, long, int)} - * is received, {@link #continueCommissioning(long, boolean)} must be called. + *

If the failureCallback non-null, when {@link + * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, + * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. * - * @param bleServer the BluetoothGatt representing the BLE - * connection to the - * device - * @param connId the BluetoothGatt Id representing the BLE - * connection to - * the device - * @param deviceId the node ID to assign to the device - * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want - * to use an internally randomly generated CSR - * nonce. - * @param networkCredentials the credentials (Wi-Fi or Thread) to be - * provisioned - * @param failureCallback the callback will be invoked when device - * attestation failed. + * @param bleServer the BluetoothGatt representing the BLE connection to the device + * @param connId the BluetoothGatt Id representing the BLE connection to the device + * @param deviceId the node ID to assign to the device + * @param setupPincode the pincode for the device + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly + * generated CSR nonce. + * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned + * @param failureCallback the callback will be invoked when device attestation failed. * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationFailed is invoked. + * onDeviceAttestationFailed is invoked. */ public void pairDevice( BluetoothGatt bleServer, @@ -231,8 +230,14 @@ public void pairDevice( Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); Log.d(TAG, "Pairing device with ID: " + deviceId); pairDevice( - deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials, - failureCallback, failSafeExpiryTimeout); + deviceControllerPtr, + deviceId, + connectionId, + setupPincode, + csrNonce, + networkCredentials, + failureCallback, + failSafeExpiryTimeout); } else { Log.e(TAG, "Bluetooth connection already in use."); completionListener.onError(new Exception("Bluetooth connection already in use.")); @@ -260,7 +265,14 @@ public void pairDeviceWithAddress( @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, int failSafeExpiryTimeout) { pairDeviceWithAddress( - deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce, completionCallback, + deviceControllerPtr, + deviceId, + address, + port, + discriminator, + pinCode, + csrNonce, + completionCallback, failSafeExpiryTimeout); } @@ -274,7 +286,13 @@ public void pairDeviceWithAddress( @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, int failSafeExpiryTimeout) { pairDeviceWithAddress( - deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce, + deviceControllerPtr, + deviceId, + address, + port, + discriminator, + pinCode, + csrNonce, failureCallback, failSafeExpiryTimeout); } @@ -320,7 +338,8 @@ public void establishPaseConnection(long deviceId, String address, int port, lon * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice(long deviceId, @Nullable NetworkCredentials networkCredentials) { - commissionDevice(deviceControllerPtr, deviceId, /* csrNonce= */ null, networkCredentials, null, 0); + commissionDevice( + deviceControllerPtr, deviceId, /* csrNonce= */ null, networkCredentials, null, 0); } /** @@ -338,67 +357,74 @@ public void commissionDevice( } /** - * Initiates the automatic commissioning flow using the specified network - * credentials. It is + * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * If the completionCallback non-null, when - * {@link DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, long, AttestationInfo, int)} - * is received, {@link #continueCommissioning(long, boolean)} must be called. + *

If the completionCallback non-null, when {@link + * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, + * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be + * called. * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request - * @param networkCredentials the credentials (Wi-Fi or Thread) to be - * provisioned - * @param completionCallback the callback will be invoked when device - * attestation completed with device - * info for additional verification. + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request + * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned + * @param completionCallback the callback will be invoked when device attestation completed with + * device info for additional verification. * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationCompleted is invoked. + * onDeviceAttestationCompleted is invoked. */ public void commissionDevice( - long deviceId, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials, + long deviceId, + @Nullable byte[] csrNonce, + @Nullable NetworkCredentials networkCredentials, @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, int failSafeExpiryTimeout) { - commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials, completionCallback, + commissionDevice( + deviceControllerPtr, + deviceId, + csrNonce, + networkCredentials, + completionCallback, failSafeExpiryTimeout); } /** - * Initiates the automatic commissioning flow using the specified network - * credentials. It is + * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * If the failureCallback non-null, when - * {@link DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, long, int)} - * is received, {@link #continueCommissioning(long, boolean)} must be called. + *

If the failureCallback non-null, when {@link + * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, + * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request - * @param networkCredentials the credentials (Wi-Fi or Thread) to be - * provisioned - * @param failureCallback the callback will be invoked when device - * attestation failed. + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request + * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned + * @param failureCallback the callback will be invoked when device attestation failed. * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationFailed is invoked. + * onDeviceAttestationFailed is invoked. */ public void commissionDevice( - long deviceId, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials, + long deviceId, + @Nullable byte[] csrNonce, + @Nullable NetworkCredentials networkCredentials, @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, int failSafeExpiryTimeout) { - commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials, + commissionDevice( + deviceControllerPtr, + deviceId, + csrNonce, + networkCredentials, failureCallback, failSafeExpiryTimeout); } /** - * This function instructs the commissioner to proceed to the next stage of - * commissioning after attestation is reported. + * This function instructs the commissioner to proceed to the next stage of commissioning after + * attestation is reported. * - * @param devicePtr a pointer to the device which is being - * commissioned. + * @param devicePtr a pointer to the device which is being commissioned. * @param ignoreAttestationFailure whether to ignore device attestation failure. */ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailure) { diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 2dfe68d10dbb43..6b3b804f6e8ea3 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -2,47 +2,41 @@ /** * Only one of the following delegate callbacks should be implemented. - *

- * If DeviceAttestationFailureCallback is implemented, then it will be called - * when device - * attestation fails, and the client can decide to continue or stop the - * commissioning. - *

- * If DeviceAttestationFailureCallback is implemented, then it - * will always be called when device attestation completes. + * + *

If DeviceAttestationFailureCallback is implemented, then it will be called when device + * attestation fails, and the client can decide to continue or stop the commissioning. + * + *

If DeviceAttestationFailureCallback is implemented, then it will always be called when device + * attestation completes. */ public interface DeviceAttestationDelegate { - public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { - /** - * The callback will be invoked when device attestation completed with device - * info for additional verification. - * If this callback is implemented, continueCommissioningDevice on - * {@link ChipDeviceController} is expected - * to be called if commissioning should continue. - *

- * This allows the callback to stop commissioning after examining the device - * info (DAC, PAI, CD). - * - * @param deviceControllerPtr Controller corresponding to the commissioning - * process - * @param devicePtr Handle of device being commissioned - * @param attestationInfo Attestation information for the device - * @param errorCode Error code on attestation failure. 0 if success. - */ - void onDeviceAttestationCompleted(long deviceControllerPtr, long devicePtr, AttestationInfo attestationInfo, - int errorCode); - } + public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { + /** + * The callback will be invoked when device attestation completed with device info for + * additional verification. If this callback is implemented, continueCommissioningDevice on + * {@link ChipDeviceController} is expected to be called if commissioning should continue. + * + *

This allows the callback to stop commissioning after examining the device info (DAC, PAI, + * CD). + * + * @param deviceControllerPtr Controller corresponding to the commissioning process + * @param devicePtr Handle of device being commissioned + * @param attestationInfo Attestation information for the device + * @param errorCode Error code on attestation failure. 0 if success. + */ + void onDeviceAttestationCompleted( + long deviceControllerPtr, long devicePtr, AttestationInfo attestationInfo, int errorCode); + } - public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { - /** - * The callback will be invoked when device attestation failed. - * - * @param deviceControllerPtr Controller corresponding to the commissioning - * process - * @param devicePtr Handle of device being commissioned - * @param errorCode Error code for the failure. - */ - void onDeviceAttestationFailed(long deviceControllerPtr, long devicePtr, int errorCode); - } + public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { + /** + * The callback will be invoked when device attestation failed. + * + * @param deviceControllerPtr Controller corresponding to the commissioning process + * @param devicePtr Handle of device being commissioned + * @param errorCode Error code for the failure. + */ + void onDeviceAttestationFailed(long deviceControllerPtr, long devicePtr, int errorCode); + } } From 66bedd674591f8929c6112f68462ec855c87e7ba Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 14 Oct 2022 03:09:47 +0000 Subject: [PATCH 05/44] Restyled by clang-format --- .../java/AndroidDeviceControllerWrapper.h | 7 +- .../java/CHIPDeviceController-JNI.cpp | 47 +++++------ .../java/DeviceAttestationDelegateBridge.cpp | 79 ++++++++++--------- .../java/DeviceAttestationDelegateBridge.h | 28 +++---- 4 files changed, 85 insertions(+), 76 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 252b1bbf710c5e..12cd6450d80f89 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -158,13 +158,16 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel return mOpCredsIssuer.get(); } - void SetDeviceAttestationDelegateBridge(DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge) { mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; } + void SetDeviceAttestationDelegateBridge(DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge) + { + mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; + } DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } void ClearDeviceAttestationDelegateBridge() { - if(mDeviceAttestationDelegateBridge != nullptr) + if (mDeviceAttestationDelegateBridge != nullptr) { delete mDeviceAttestationDelegateBridge; mDeviceAttestationDelegateBridge = nullptr; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 8763f71988bd57..d1d2a7d75b1f2f 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -80,8 +80,9 @@ static CHIP_ERROR ParseAttributePath(jobject attributePath, EndpointId & outEndp static CHIP_ERROR ParseEventPathList(jobject eventPathList, std::vector & outEventPathParamsList); static CHIP_ERROR ParseEventPath(jobject eventPath, EndpointId & outEndpointId, ClusterId & outClusterId, EventId & outEventId); static CHIP_ERROR IsWildcardChipPathId(jobject chipPathId, bool & isWildcard); -static CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, - DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge); +static CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, + jint failSafeExpiryTimeout, + DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge); namespace { @@ -403,8 +404,8 @@ JNI_METHOD(void, commissionDevice) { wrapper->ClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, - failSafeExpiryTimeout, &deviceAttestationDelegateBridge); + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, + &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); @@ -452,8 +453,8 @@ JNI_METHOD(void, pairDevice) { wrapper->ClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, - failSafeExpiryTimeout, &deviceAttestationDelegateBridge); + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, + &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); @@ -495,8 +496,8 @@ JNI_METHOD(void, pairDeviceWithAddress) { wrapper->ClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, - failSafeExpiryTimeout, &deviceAttestationDelegateBridge); + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, + &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); @@ -558,14 +559,14 @@ JNI_METHOD(void, continueCommissioning) { chip::DeviceLayer::StackLock lock; ChipLogProgress(Controller, "continueCommissioning() called."); - CHIP_ERROR err = CHIP_NO_ERROR; - AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + CHIP_ERROR err = CHIP_NO_ERROR; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = wrapper->GetDeviceAttestationDelegateBridge(); auto lastAttestationResult = deviceAttestationDelegateBridge ? deviceAttestationDelegateBridge->attestationVerificationResult() : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); - err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { @@ -1421,24 +1422,26 @@ CHIP_ERROR N2J_NetworkLocation(JNIEnv * env, jstring ipAddress, jint port, jint return err; } -CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout, - DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge) +CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, + jint failSafeExpiryTimeout, + DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge) { - CHIP_ERROR err = CHIP_NO_ERROR; - chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeout)); + CHIP_ERROR err = CHIP_NO_ERROR; + chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeout)); bool shouldWaitAfterDeviceAttestation = false; - jclass completionCallbackCls = nullptr; - jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); + jclass completionCallbackCls = nullptr; + jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); VerifyOrExit(deviceAttestationDelegateRef != nullptr, err = CHIP_JNI_ERROR_NULL_OBJECT); - JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", - completionCallbackCls); + JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", completionCallbackCls); VerifyOrExit(completionCallbackCls != nullptr, err = CHIP_JNI_ERROR_TYPE_NOT_FOUND); - if(env->IsInstanceOf(deviceAttestationDelegate, completionCallbackCls)) + if (env->IsInstanceOf(deviceAttestationDelegate, completionCallbackCls)) { shouldWaitAfterDeviceAttestation = true; } - *deviceAttestationDelegateBridge = new DeviceAttestationDelegateBridge(handle, deviceAttestationDelegateRef, timeoutSecs, shouldWaitAfterDeviceAttestation); + *deviceAttestationDelegateBridge = + new DeviceAttestationDelegateBridge(handle, deviceAttestationDelegateRef, timeoutSecs, shouldWaitAfterDeviceAttestation); exit: return err; } diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index c69e408b0ae96d..8cd1f3f7ac3149 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -16,25 +16,25 @@ */ #include "DeviceAttestationDelegateBridge.h" -#include -#include -#include #include #include +#include +#include +#include using namespace chip; CHIP_ERROR N2J_AttestationInfo(JNIEnv * env, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, jobject & outAttestationInfo) { - CHIP_ERROR err = CHIP_NO_ERROR; - jclass infoClass = nullptr; - jmethodID constructor = nullptr; - jbyteArray javaDAC = nullptr; - jbyteArray javaPAI = nullptr; - jbyteArray javaCD = nullptr; - const ByteSpan DAC = info.dacDerBuffer(); - const ByteSpan PAI = info.paiDerBuffer(); + CHIP_ERROR err = CHIP_NO_ERROR; + jclass infoClass = nullptr; + jmethodID constructor = nullptr; + jbyteArray javaDAC = nullptr; + jbyteArray javaPAI = nullptr; + jbyteArray javaCD = nullptr; + const ByteSpan DAC = info.dacDerBuffer(); + const ByteSpan PAI = info.paiDerBuffer(); const Optional certificationDeclarationSpan = info.cdBuffer(); err = JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/AttestationInfo", infoClass); @@ -49,10 +49,10 @@ CHIP_ERROR N2J_AttestationInfo(JNIEnv * env, const chip::Credentials::DeviceAtte SuccessOrExit(err); err = JniReferences::GetInstance().N2J_ByteArray(env, PAI.data(), PAI.size(), javaPAI); SuccessOrExit(err); - if(certificationDeclarationSpan.HasValue()) + if (certificationDeclarationSpan.HasValue()) { - err = JniReferences::GetInstance().N2J_ByteArray(env, certificationDeclarationSpan.Value().data(), certificationDeclarationSpan.Value().size(), - javaCD); + err = JniReferences::GetInstance().N2J_ByteArray(env, certificationDeclarationSpan.Value().data(), + certificationDeclarationSpan.Value().size(), javaCD); SuccessOrExit(err); } outAttestationInfo = (jobject) env->NewObject(infoClass, constructor, javaDAC, javaPAI, javaCD); @@ -61,53 +61,60 @@ CHIP_ERROR N2J_AttestationInfo(JNIEnv * env, const chip::Credentials::DeviceAtte return err; } -void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, - chip::DeviceProxy * device, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, +void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( + chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, + const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, chip::Credentials::AttestationVerificationResult attestationResult) { ChipLogProgress(Controller, "OnDeviceAttestationCompleted with result: %hu", attestationResult); mResult = attestationResult; - if(mDeviceAttestationDelegate != nullptr) + if (mDeviceAttestationDelegate != nullptr) { - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jclass completionCallbackCls = nullptr; - JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", - completionCallbackCls); + JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", completionCallbackCls); VerifyOrReturn(completionCallbackCls != nullptr, - ChipLogError(Controller, "Could not find device attestation completion callback class.")); + ChipLogError(Controller, "Could not find device attestation completion callback class.")); jclass failureCallbackCls = nullptr; - JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationFailureCallback", - failureCallbackCls); + JniReferences::GetInstance().GetClassRef( + env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationFailureCallback", failureCallbackCls); VerifyOrReturn(failureCallbackCls != nullptr, - ChipLogError(Controller, "Could not find device attestation failure callback class.")); + ChipLogError(Controller, "Could not find device attestation failure callback class.")); - if(env->IsInstanceOf(mDeviceAttestationDelegate, completionCallbackCls)) + if (env->IsInstanceOf(mDeviceAttestationDelegate, completionCallbackCls)) { jmethodID onDeviceAttestationCompletedMethod; - JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationCompleted", "(JJLchip/devicecontroller/AttestationInfo;I)V", &onDeviceAttestationCompletedMethod); - VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation completed method")); + JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationCompleted", + "(JJLchip/devicecontroller/AttestationInfo;I)V", + &onDeviceAttestationCompletedMethod); + VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, + ChipLogError(Controller, "Could not find deviceAttestation completed method")); jobject javaAttestationInfo; CHIP_ERROR err = N2J_AttestationInfo(env, info, javaAttestationInfo); VerifyOrReturn(err == CHIP_NO_ERROR, - ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); - env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, mDeviceController, reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); + ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, mDeviceController, + reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); } - else if((attestationResult != chip::Credentials::AttestationVerificationResult::kSuccess) && - env->IsInstanceOf(mDeviceAttestationDelegate, failureCallbackCls)) + else if ((attestationResult != chip::Credentials::AttestationVerificationResult::kSuccess) && + env->IsInstanceOf(mDeviceAttestationDelegate, failureCallbackCls)) { jmethodID onDeviceAttestationFailedMethod; - JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationFailed", "(JJI)V", &onDeviceAttestationFailedMethod); - VerifyOrReturn(onDeviceAttestationFailedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation failed method")); - env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationFailedMethod, mDeviceController, reinterpret_cast(device), static_cast(attestationResult)); + JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationFailed", "(JJI)V", + &onDeviceAttestationFailedMethod); + VerifyOrReturn(onDeviceAttestationFailedMethod != nullptr, + ChipLogError(Controller, "Could not find deviceAttestation failed method")); + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationFailedMethod, mDeviceController, + reinterpret_cast(device), static_cast(attestationResult)); } } - } DeviceAttestationDelegateBridge::~DeviceAttestationDelegateBridge() { - if(mDeviceAttestationDelegate != nullptr) + if (mDeviceAttestationDelegate != nullptr) { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); diff --git a/src/controller/java/DeviceAttestationDelegateBridge.h b/src/controller/java/DeviceAttestationDelegateBridge.h index 30bb8e30745d5c..3cfa02bccc0a48 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.h +++ b/src/controller/java/DeviceAttestationDelegateBridge.h @@ -15,33 +15,29 @@ * limitations under the License. */ +#include #include #include -#include #include -class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestationDelegate { +class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestationDelegate +{ public: - DeviceAttestationDelegateBridge(jlong deviceController, - jobject deviceAttestationDelegate, - chip::Optional expiryTimeoutSecs, - bool shouldWaitAfterDeviceAttestation) - : mResult(chip::Credentials::AttestationVerificationResult::kSuccess) - , mDeviceController(deviceController) - , mDeviceAttestationDelegate(deviceAttestationDelegate) - , mExpiryTimeoutSecs(expiryTimeoutSecs) - , mShouldWaitAfterDeviceAttestation(shouldWaitAfterDeviceAttestation) - { - } + DeviceAttestationDelegateBridge(jlong deviceController, jobject deviceAttestationDelegate, + chip::Optional expiryTimeoutSecs, bool shouldWaitAfterDeviceAttestation) : + mResult(chip::Credentials::AttestationVerificationResult::kSuccess), + mDeviceController(deviceController), mDeviceAttestationDelegate(deviceAttestationDelegate), + mExpiryTimeoutSecs(expiryTimeoutSecs), mShouldWaitAfterDeviceAttestation(shouldWaitAfterDeviceAttestation) + {} ~DeviceAttestationDelegateBridge(); chip::Optional FailSafeExpiryTimeoutSecs() const override { return mExpiryTimeoutSecs; } - void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, - chip::DeviceProxy * device, const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, - chip::Credentials::AttestationVerificationResult attestationResult) override; + void OnDeviceAttestationCompleted(chip::Controller::DeviceCommissioner * deviceCommissioner, chip::DeviceProxy * device, + const chip::Credentials::DeviceAttestationVerifier::AttestationDeviceInfo & info, + chip::Credentials::AttestationVerificationResult attestationResult) override; bool ShouldWaitAfterDeviceAttestation() override { return mShouldWaitAfterDeviceAttestation; } From d9be2baacb92d680d48e0a1756ae5ece19353549 Mon Sep 17 00:00:00 2001 From: "Restyled.io" Date: Fri, 14 Oct 2022 03:09:48 +0000 Subject: [PATCH 06/44] Restyled by gn --- src/setup_payload/java/BUILD.gn | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/setup_payload/java/BUILD.gn b/src/setup_payload/java/BUILD.gn index 1188190c6eb8aa..e0225193948155 100644 --- a/src/setup_payload/java/BUILD.gn +++ b/src/setup_payload/java/BUILD.gn @@ -46,9 +46,9 @@ android_library("java") { "src/chip/setuppayload/SetupPayloadParser.java", ] - javac_flags = [ + javac_flags = [ "-Xlint:deprecation", - "-parameters" # Store infomation about method parameters + "-parameters", # Store infomation about method parameters ] # TODO: add classpath support (we likely need to add something like From 48ce640858a01010cd94d13e3cfa4b02ed719883 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 20 Oct 2022 19:05:33 +0800 Subject: [PATCH 07/44] fix copyright --- src/controller/java/DeviceAttestationDelegateBridge.cpp | 2 +- src/controller/java/DeviceAttestationDelegateBridge.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index 8cd1f3f7ac3149..28bacf5b45764f 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -1,6 +1,6 @@ /** * - * Copyright (c) 2020 Project CHIP Authors + * 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. diff --git a/src/controller/java/DeviceAttestationDelegateBridge.h b/src/controller/java/DeviceAttestationDelegateBridge.h index 3cfa02bccc0a48..78ed6b8e1ee93d 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.h +++ b/src/controller/java/DeviceAttestationDelegateBridge.h @@ -1,6 +1,6 @@ /** * - * Copyright (c) 2020 Project CHIP Authors + * 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. From 5e8723b8db1b71ec3a7bdd553cb5a9293cc15311 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 20 Oct 2022 19:11:55 +0800 Subject: [PATCH 08/44] fix and modify comments --- .../DeviceAttestationDelegate.java | 47 +++++++++++-------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 6b3b804f6e8ea3..cfcc835630b273 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -2,28 +2,34 @@ /** * Only one of the following delegate callbacks should be implemented. - * - *

If DeviceAttestationFailureCallback is implemented, then it will be called when device - * attestation fails, and the client can decide to continue or stop the commissioning. - * - *

If DeviceAttestationFailureCallback is implemented, then it will always be called when device - * attestation completes. + *

+ * If one of the following callbacks is implemented, + * {@link ChipDeviceController#continueCommissioning(long, boolean)} is expected + * to be called if commissioning should continue. + *

+ * If DeviceAttestationCompletionCallback is implemented, then it will always be + * called when device attestation completes. + *

+ * If DeviceAttestationFailureCallback is implemented, then it will be called + * when device attestation fails, and the client can decide to continue or stop + * the commissioning. */ public interface DeviceAttestationDelegate { public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { /** - * The callback will be invoked when device attestation completed with device info for - * additional verification. If this callback is implemented, continueCommissioningDevice on - * {@link ChipDeviceController} is expected to be called if commissioning should continue. + * The callback will be invoked when device attestation completed with device + * info for additional verification. * - *

This allows the callback to stop commissioning after examining the device info (DAC, PAI, - * CD). + *

+ * This allows the callback to stop commissioning after examining the device + * info (DAC, PAI, CD). * - * @param deviceControllerPtr Controller corresponding to the commissioning process - * @param devicePtr Handle of device being commissioned - * @param attestationInfo Attestation information for the device - * @param errorCode Error code on attestation failure. 0 if success. + * @param deviceControllerPtr Controller corresponding to the commissioning + * process + * @param devicePtr Handle of device being commissioned + * @param attestationInfo Attestation information for the device + * @param errorCode Error code on attestation failure. 0 if success. */ void onDeviceAttestationCompleted( long deviceControllerPtr, long devicePtr, AttestationInfo attestationInfo, int errorCode); @@ -31,11 +37,12 @@ void onDeviceAttestationCompleted( public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { /** - * The callback will be invoked when device attestation failed. - * - * @param deviceControllerPtr Controller corresponding to the commissioning process - * @param devicePtr Handle of device being commissioned - * @param errorCode Error code for the failure. + * The callback will be invoked when device attestation failed + * + * @param deviceControllerPtr Controller corresponding to the commissioning + * process + * @param devicePtr Handle of device being commissioned + * @param errorCode Error code for the failure. */ void onDeviceAttestationFailed(long deviceControllerPtr, long devicePtr, int errorCode); } From 47f079ec557964fe76b4d4aac26dcb10f33be9c5 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 28 Oct 2022 17:41:07 +0800 Subject: [PATCH 09/44] Use setters instead of adding parameters to methods --- .../java/CHIPDeviceController-JNI.cpp | 62 ++- .../java/DeviceAttestationDelegateBridge.cpp | 6 +- .../ChipDeviceController.java | 525 +++++++----------- 3 files changed, 245 insertions(+), 348 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 88858503cf25fe..72cc578982ad81 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -384,9 +384,33 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr return result; } +JNI_METHOD(void, setDeviceAttestationDelegate) +(JNIEnv * env, jobject self, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) +{ + chip::DeviceLayer::StackLock lock; + CHIP_ERROR err = CHIP_NO_ERROR; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + ChipLogProgress(Controller, "setDeviceAttestationDelegate() called"); + if (deviceAttestationDelegate != nullptr) + { + wrapper->ClearDeviceAttestationDelegateBridge(); + DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, + &deviceAttestationDelegateBridge); + VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); + wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); + } +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to set device attestation delegate."); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } +} + JNI_METHOD(void, commissionDevice) -(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jbyteArray csrNonce, jobject networkCredentials, - jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) +(JNIEnv * env, jobject self, jlong handle, jlong deviceId, jbyteArray csrNonce, jobject networkCredentials) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -400,14 +424,8 @@ JNI_METHOD(void, commissionDevice) err = wrapper->ApplyNetworkCredentials(commissioningParams, networkCredentials); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_ERROR_INVALID_ARGUMENT); } - if (deviceAttestationDelegate != nullptr) + if (wrapper->GetDeviceAttestationDelegateBridge() != nullptr) { - wrapper->ClearDeviceAttestationDelegateBridge(); - DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, - &deviceAttestationDelegateBridge); - VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); - wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); } if (csrNonce != nullptr) @@ -426,7 +444,7 @@ JNI_METHOD(void, commissionDevice) JNI_METHOD(void, pairDevice) (JNIEnv * env, jobject self, jlong handle, jlong deviceId, jint connObj, jlong pinCode, jbyteArray csrNonce, - jobject networkCredentials, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) + jobject networkCredentials) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -455,18 +473,12 @@ JNI_METHOD(void, pairDevice) JniByteArray jniCsrNonce(env, csrNonce); commissioningParams.SetCSRNonce(jniCsrNonce.byteSpan()); } - if (deviceAttestationDelegate != nullptr) + if (wrapper->GetDeviceAttestationDelegateBridge() != nullptr) { - wrapper->ClearDeviceAttestationDelegateBridge(); - DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, - &deviceAttestationDelegateBridge); - VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); - wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); } err = wrapper->Controller()->PairDevice(deviceId, rendezvousParams, commissioningParams); -exit: + if (err != CHIP_NO_ERROR) { ChipLogError(Controller, "Failed to pair the device."); @@ -476,7 +488,7 @@ JNI_METHOD(void, pairDevice) JNI_METHOD(void, pairDeviceWithAddress) (JNIEnv * env, jobject self, jlong handle, jlong deviceId, jstring address, jint port, jint discriminator, jlong pinCode, - jbyteArray csrNonce, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) + jbyteArray csrNonce) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -504,18 +516,12 @@ JNI_METHOD(void, pairDeviceWithAddress) JniByteArray jniCsrNonce(env, csrNonce); commissioningParams.SetCSRNonce(jniCsrNonce.byteSpan()); } - if (deviceAttestationDelegate != nullptr) + if (wrapper->GetDeviceAttestationDelegateBridge() != nullptr) { - wrapper->ClearDeviceAttestationDelegateBridge(); - DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, - &deviceAttestationDelegateBridge); - VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); - wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); commissioningParams.SetDeviceAttestationDelegate(wrapper->GetDeviceAttestationDelegateBridge()); } err = wrapper->Controller()->PairDevice(deviceId, rendezvousParams, commissioningParams); -exit: + if (err != CHIP_NO_ERROR) { ChipLogError(Controller, "Failed to pair the device."); @@ -592,7 +598,7 @@ JNI_METHOD(void, continueCommissioning) : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index 28bacf5b45764f..52467c0ce2100e 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -45,14 +45,14 @@ CHIP_ERROR N2J_AttestationInfo(JNIEnv * env, const chip::Credentials::DeviceAtte constructor = env->GetMethodID(infoClass, "", "([B[B[B)V"); VerifyOrExit(constructor != nullptr, err = CHIP_JNI_ERROR_METHOD_NOT_FOUND); - err = JniReferences::GetInstance().N2J_ByteArray(env, DAC.data(), DAC.size(), javaDAC); + err = JniReferences::GetInstance().N2J_ByteArray(env, DAC.data(), static_cast(DAC.size()), javaDAC); SuccessOrExit(err); - err = JniReferences::GetInstance().N2J_ByteArray(env, PAI.data(), PAI.size(), javaPAI); + err = JniReferences::GetInstance().N2J_ByteArray(env, PAI.data(), static_cast(PAI.size()), javaPAI); SuccessOrExit(err); if (certificationDeclarationSpan.HasValue()) { err = JniReferences::GetInstance().N2J_ByteArray(env, certificationDeclarationSpan.Value().data(), - certificationDeclarationSpan.Value().size(), javaCD); + static_cast(certificationDeclarationSpan.Value().size()), javaCD); SuccessOrExit(err); } outAttestationInfo = (jobject) env->NewObject(infoClass, constructor, javaDAC, javaPAI, javaCD); diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 095e58bb232f65..ebc0f98cc46365 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -37,7 +37,8 @@ public class ChipDeviceController { private NOCChainIssuer nocChainIssuer; /** - * To load class and jni, we need to new AndroidChipPlatform after jni load but before new + * To load class and jni, we need to new AndroidChipPlatform after jni load but + * before new * ChipDeviceController */ public static void loadJni() { @@ -45,8 +46,10 @@ public static void loadJni() { } /** - * Returns a new {@link ChipDeviceController} with the specified parameters. you must set a vendor - * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() 0xFFF4 is a test vendor + * Returns a new {@link ChipDeviceController} with the specified parameters. you + * must set a vendor + * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() + * 0xFFF4 is a test vendor * ID */ public ChipDeviceController(ControllerParams params) { @@ -65,16 +68,24 @@ public void setScanNetworksListener(ScanNetworksListener listener) { } /** - * Sets this DeviceController to use the given issuer for issuing operational certs and verifying - * the DAC. By default, the DeviceController uses an internal, OperationalCredentialsDelegate (see + * Sets this DeviceController to use the given issuer for issuing operational + * certs and verifying + * the DAC. By default, the DeviceController uses an internal, + * OperationalCredentialsDelegate (see * AndroidOperationalCredentialsIssuer). * - *

When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed and DAC verified. This allows for custom credentials - * issuer and DAC verifier implementations, for example, when a proprietary cloud API will perform + *

+ * When a NOCChainIssuer is set for this controller, then + * onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed and DAC verified. This allows for + * custom credentials + * issuer and DAC verifier implementations, for example, when a proprietary + * cloud API will perform * DAC verification and the CSR signing. * - *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used rather + *

+ * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will + * be used rather * than the DefaultDACVerifier. * * @param issuer @@ -84,130 +95,69 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { nocChainIssuer = issuer; } - public void pairDevice( - BluetoothGatt bleServer, - int connId, - long deviceId, - long setupPincode, - NetworkCredentials networkCredentials) { - pairDevice(bleServer, connId, deviceId, setupPincode, null, networkCredentials); - } - /** - * Pair a device connected through BLE. - * - * @param bleServer the BluetoothGatt representing the BLE connection to the device - * @param connId the BluetoothGatt Id representing the BLE connection to the device - * @param deviceId the node ID to assign to the device - * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly - * generated CSR nonce. + * If DeviceAttestationCompletionCallback is setted, then it will always be + * called when device attestation completes. + * + * When {@link + * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, + * long, AttestationInfo, int)} is received, + * {@link #continueCommissioning(long, boolean)} must be called. + * + * @param failSafeExpiryTimeout the value to set for the fail-safe timer before + * onDeviceAttestationCompleted is invoked. + * @param completionCallback the callback will be invoked when + * deviceattestation + * completed with device info for additional + * verification. */ - public void pairDevice( - BluetoothGatt bleServer, - int connId, - long deviceId, - long setupPincode, - @Nullable byte[] csrNonce, - NetworkCredentials networkCredentials) { - if (connectionId == 0) { - connectionId = connId; - - if (connectionId == 0) { - Log.e(TAG, "Failed to add Bluetooth connection."); - completionListener.onError(new Exception("Failed to add Bluetooth connection.")); - return; - } - - Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); - Log.d(TAG, "Pairing device with ID: " + deviceId); - pairDevice( - deviceControllerPtr, - deviceId, - connectionId, - setupPincode, - csrNonce, - networkCredentials, - null, - 0); - } else { - Log.e(TAG, "Bluetooth connection already in use."); - completionListener.onError(new Exception("Bluetooth connection already in use.")); - } + public void setDeviceAttestationCompletionCallback(int failSafeExpiryTimeout, + DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback) { + setDeviceAttestationDelegate(failSafeExpiryTimeout, completionCallback); } /** - * Pair a device connected through BLE. - * - *

If the completionCallback non-null, when {@link - * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, - * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be - * called. - * - * @param bleServer the BluetoothGatt representing the BLE connection to the device - * @param connId the BluetoothGatt Id representing the BLE connection to the device - * @param deviceId the node ID to assign to the device - * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally - * randomlygenerated CSR nonce. - * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned - * @param completionCallback the callback will be invoked when deviceattestation completed with - * device info for additional verification. + * If DeviceAttestationFailureCallback is setted, then it will be called + * when device attestation fails, and the client can decide to continue or stop + * the commissioning. + * + * When {@link + * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, + * long, int)} is received, {@link #continueCommissioning(long, boolean)} must + * be called. + * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationCompleted is invoked. + * onDeviceAttestationFailed is invoked. + * @param failureCallback the callback will be invoked when device + * attestation + * failed. */ + public void setDeviceAttestationFailureCallback(int failSafeExpiryTimeout, + DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback) { + setDeviceAttestationDelegate(failSafeExpiryTimeout, failureCallback); + } + public void pairDevice( BluetoothGatt bleServer, int connId, long deviceId, long setupPincode, - @Nullable byte[] csrNonce, - NetworkCredentials networkCredentials, - @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, - int failSafeExpiryTimeout) { - if (connectionId == 0) { - connectionId = connId; - - if (connectionId == 0) { - Log.e(TAG, "Failed to add Bluetooth connection."); - completionListener.onError(new Exception("Failed to add Bluetooth connection.")); - return; - } - - Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); - Log.d(TAG, "Pairing device with ID: " + deviceId); - pairDevice( - deviceControllerPtr, - deviceId, - connectionId, - setupPincode, - csrNonce, - networkCredentials, - completionCallback, - failSafeExpiryTimeout); - } else { - Log.e(TAG, "Bluetooth connection already in use."); - completionListener.onError(new Exception("Bluetooth connection already in use.")); - } + NetworkCredentials networkCredentials) { + pairDevice(bleServer, connId, deviceId, setupPincode, null, networkCredentials); } /** * Pair a device connected through BLE. * - *

If the failureCallback non-null, when {@link - * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, - * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. - * - * @param bleServer the BluetoothGatt representing the BLE connection to the device - * @param connId the BluetoothGatt Id representing the BLE connection to the device - * @param deviceId the node ID to assign to the device + * @param bleServer the BluetoothGatt representing the BLE connection to the + * device + * @param connId the BluetoothGatt Id representing the BLE connection to + * the device + * @param deviceId the node ID to assign to the device * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly - * generated CSR nonce. - * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned - * @param failureCallback the callback will be invoked when device attestation failed. - * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationFailed is invoked. + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use + * an internally randomly + * generated CSR nonce. */ public void pairDevice( BluetoothGatt bleServer, @@ -215,9 +165,7 @@ public void pairDevice( long deviceId, long setupPincode, @Nullable byte[] csrNonce, - NetworkCredentials networkCredentials, - @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, - int failSafeExpiryTimeout) { + NetworkCredentials networkCredentials) { if (connectionId == 0) { connectionId = connId; @@ -230,14 +178,7 @@ public void pairDevice( Log.d(TAG, "Bluetooth connection added with ID: " + connectionId); Log.d(TAG, "Pairing device with ID: " + deviceId); pairDevice( - deviceControllerPtr, - deviceId, - connectionId, - setupPincode, - csrNonce, - networkCredentials, - failureCallback, - failSafeExpiryTimeout); + deviceControllerPtr, deviceId, connectionId, setupPincode, csrNonce, networkCredentials); } else { Log.e(TAG, "Bluetooth connection already in use."); completionListener.onError(new Exception("Bluetooth connection already in use.")); @@ -252,49 +193,7 @@ public void pairDeviceWithAddress( long pinCode, @Nullable byte[] csrNonce) { pairDeviceWithAddress( - deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce, null, 0); - } - - public void pairDeviceWithAddress( - long deviceId, - String address, - int port, - int discriminator, - long pinCode, - @Nullable byte[] csrNonce, - @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, - int failSafeExpiryTimeout) { - pairDeviceWithAddress( - deviceControllerPtr, - deviceId, - address, - port, - discriminator, - pinCode, - csrNonce, - completionCallback, - failSafeExpiryTimeout); - } - - public void pairDeviceWithAddress( - long deviceId, - String address, - int port, - int discriminator, - long pinCode, - @Nullable byte[] csrNonce, - @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, - int failSafeExpiryTimeout) { - pairDeviceWithAddress( - deviceControllerPtr, - deviceId, - address, - port, - discriminator, - pinCode, - csrNonce, - failureCallback, - failSafeExpiryTimeout); + deviceControllerPtr, deviceId, address, port, discriminator, pinCode, csrNonce); } public void establishPaseConnection(long deviceId, int connId, long setupPincode) { @@ -319,9 +218,9 @@ public void establishPaseConnection(long deviceId, int connId, long setupPincode /** * Establish a secure PASE connection to the given device via IP address. * - * @param deviceId the ID of the node to connect to - * @param address the IP address at which the node is located - * @param port the port at which the node is located + * @param deviceId the ID of the node to connect to + * @param address the IP address at which the node is located + * @param port the port at which the node is located * @param setupPincode the pincode for this node */ public void establishPaseConnection(long deviceId, String address, int port, long setupPincode) { @@ -330,119 +229,69 @@ public void establishPaseConnection(long deviceId, String address, int port, lon } /** - * Initiates the automatic commissioning flow using the specified network credentials. It is + * Initiates the automatic commissioning flow using the specified network + * credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned + * @param deviceId the ID of the node to be commissioned * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice(long deviceId, @Nullable NetworkCredentials networkCredentials) { - commissionDevice( - deviceControllerPtr, deviceId, /* csrNonce= */ null, networkCredentials, null, 0); + commissionDevice(deviceControllerPtr, deviceId, /* csrNonce= */ null, networkCredentials); } /** - * Initiates the automatic commissioning flow using the specified network credentials. It is + * Initiates the automatic commissioning flow using the specified network + * credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice( long deviceId, @Nullable byte[] csrNonce, @Nullable NetworkCredentials networkCredentials) { - commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials, null, 0); + commissionDevice(deviceControllerPtr, deviceId, csrNonce, networkCredentials); } /** - * Initiates the automatic commissioning flow using the specified network credentials. It is - * expected that a secure session has already been established via {@link - * #establishPaseConnection(long, int, long)}. - * - *

If the completionCallback non-null, when {@link - * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, - * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be - * called. - * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request - * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned - * @param completionCallback the callback will be invoked when device attestation completed with - * device info for additional verification. - * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationCompleted is invoked. - */ - public void commissionDevice( - long deviceId, - @Nullable byte[] csrNonce, - @Nullable NetworkCredentials networkCredentials, - @Nullable DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback, - int failSafeExpiryTimeout) { - commissionDevice( - deviceControllerPtr, - deviceId, - csrNonce, - networkCredentials, - completionCallback, - failSafeExpiryTimeout); - } - - /** - * Initiates the automatic commissioning flow using the specified network credentials. It is - * expected that a secure session has already been established via {@link - * #establishPaseConnection(long, int, long)}. - * - *

If the failureCallback non-null, when {@link - * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, - * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. - * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request - * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned - * @param failureCallback the callback will be invoked when device attestation failed. - * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationFailed is invoked. - */ - public void commissionDevice( - long deviceId, - @Nullable byte[] csrNonce, - @Nullable NetworkCredentials networkCredentials, - @Nullable DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback, - int failSafeExpiryTimeout) { - commissionDevice( - deviceControllerPtr, - deviceId, - csrNonce, - networkCredentials, - failureCallback, - failSafeExpiryTimeout); - } - - /** - * This function instructs the commissioner to proceed to the next stage of commissioning after + * This function instructs the commissioner to proceed to the next stage of + * commissioning after * attestation is reported. * - * @param devicePtr a pointer to the device which is being commissioned. + * @param devicePtr a pointer to the device which is being + * commissioned. * @param ignoreAttestationFailure whether to ignore device attestation failure. */ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailure) { continueCommissioning(deviceControllerPtr, devicePtr, ignoreAttestationFailure); } + /** - * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed. This allows for custom credentials issuer - * implementations, for example, when a proprietary cloud API will perform the CSR signing. + * When a NOCChainIssuer is set for this controller, then + * onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed. This allows for custom + * credentials issuer + * implementations, for example, when a proprietary cloud API will perform the + * CSR signing. * - *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and resume + *

+ * The commissioning workflow will stop upon the onNOCChainGenerationNeeded + * callback and resume * once onNOCChainGeneration is called. * - *

The following fields on the ControllerParams object MUST be populated: rootCertificate, + *

+ * The following fields on the ControllerParams object MUST be populated: + * rootCertificate, * intermediateCertificate, operationalCertificate * - *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in - * the AddNOC command set to the commissionee. If they are not populated, then the values provided + *

+ * If ipk and adminSubject are set on the ControllerParams object, then they + * will be used in + * the AddNOC command set to the commissionee. If they are not populated, then + * the values provided * in the ChipDeviceController initialization will be used. * * @param params @@ -453,14 +302,19 @@ public int onNOCChainGeneration(ControllerParams params) { } /** - * Update the network credentials held by the commissioner for the current commissioning session. - * The updated values will be used by the commissioner if the network credentials haven't already + * Update the network credentials held by the commissioner for the current + * commissioning session. + * The updated values will be used by the commissioner if the network + * credentials haven't already * been sent to the device. * - *

Its expected that this method will be called in response to the NetworkScan or the + *

+ * Its expected that this method will be called in response to the NetworkScan + * or the * ReadCommissioningInfo callbacks. * - * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning + * @param networkCredentials the credentials (Wi-Fi or Thread) to use in + * commissioning */ public void updateCommissioningNetworkCredentials(NetworkCredentials networkCredentials) { updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); @@ -471,7 +325,8 @@ public void unpairDevice(long deviceId) { } /** - * Returns a pointer to a device currently being commissioned. This should be used before the + * Returns a pointer to a device currently being commissioned. This should be + * used before the * device is operationally available. */ public long getDeviceBeingCommissionedPointer(long nodeId) { @@ -479,12 +334,18 @@ public long getDeviceBeingCommissionedPointer(long nodeId) { } /** - * Through GetConnectedDeviceCallback, returns a pointer to a connected device or an error. + * Through GetConnectedDeviceCallback, returns a pointer to a connected device + * or an error. * - *

The native code invoked by this method creates a strong reference to the provided callback, - * which is released only when GetConnectedDeviceCallback has returned success or failure. + *

+ * The native code invoked by this method creates a strong reference to the + * provided callback, + * which is released only when GetConnectedDeviceCallback has returned success + * or failure. * - *

TODO(#8443): This method could benefit from a ChipDevice abstraction to hide the pointer + *

+ * TODO(#8443): This method could benefit from a ChipDevice abstraction to hide + * the pointer * passing. */ public void getConnectedDevicePointer(long nodeId, GetConnectedDeviceCallback callback) { @@ -541,10 +402,8 @@ public void onScanNetworksFailure(int errorCode) { public void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> - wiFiScanResults, - Optional> - threadScanResults) { + Optional> wiFiScanResults, + Optional> threadScanResults) { if (scanNetworksListener != null) { scanNetworksListener.onScanNetworksSuccess( networkingStatus, debugText, wiFiScanResults, threadScanResults); @@ -609,10 +468,12 @@ public String getIpAddress(long deviceId) { } /** - * Returns the {@link NetworkLocation} at which the given {@code deviceId} has been found. + * Returns the {@link NetworkLocation} at which the given {@code deviceId} has + * been found. * * @param deviceId the 64-bit node ID of the device - * @throws ChipDeviceControllerException if the device location could not be resolved + * @throws ChipDeviceControllerException if the device location could not be + * resolved */ public NetworkLocation getNetworkLocation(long deviceId) { return getNetworkLocation(deviceControllerPtr, deviceId); @@ -623,17 +484,19 @@ public long getCompressedFabricId() { } /** - * Returns the compressed fabric ID based on the given root certificate and node operational + * Returns the compressed fabric ID based on the given root certificate and node + * operational * credentials. * * @param rcac the root certificate (in Matter cert form) - * @param noc the NOC (in Matter cert form) + * @param noc the NOC (in Matter cert form) * @see #convertX509CertToMatterCert(byte[]) */ public native long generateCompressedFabricId(byte[] rcac, byte[] noc); /** - * Get commmissionible Node. Commmissionible Node results are able to get using {@link + * Get commmissionible Node. Commmissionible Node results are able to get using + * {@link * ChipDeviceController.getDiscoveredDevice}. */ public void discoverCommissionableNodes() { @@ -676,11 +539,13 @@ public void shutdownSubscriptions(long devicePtr) { } /** - * Returns an attestation challenge for the given device, for which there must be an existing + * Returns an attestation challenge for the given device, for which there must + * be an existing * secure session. * * @param devicePtr a pointer to the device from which to retrieve the challenge - * @throws ChipDeviceControllerException if there is no secure session for the given device + * @throws ChipDeviceControllerException if there is no secure session for the + * given device */ public byte[] getAttestationChallenge(long devicePtr) { return getAttestationChallenge(deviceControllerPtr, devicePtr); @@ -694,8 +559,7 @@ public void subscribeToAttributePath( List attributePaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = - new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -716,8 +580,7 @@ public void subscribeToEventPath( List eventPaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = - new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -730,7 +593,10 @@ public void subscribeToEventPath( false); } - /** Subscribe to the given attribute/event path with keepSubscriptions and isFabricFiltered. */ + /** + * Subscribe to the given attribute/event path with keepSubscriptions and + * isFabricFiltered. + */ public void subscribeToPath( SubscriptionEstablishedCallback subscriptionEstablishedCallback, ResubscriptionAttemptCallback resubscriptionAttemptCallback, @@ -742,10 +608,10 @@ public void subscribeToPath( int maxInterval, boolean keepSubscriptions, boolean isFabricFiltered) { - // TODO: pass resubscriptionAttemptCallback to ReportCallbackJni since jni layer is not ready + // TODO: pass resubscriptionAttemptCallback to ReportCallbackJni since jni layer + // is not ready // for auto-resubscribe - ReportCallbackJni jniCallback = - new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -798,18 +664,20 @@ public void readPath( /** * Converts a given X.509v3 certificate into a Matter certificate. * - * @throws ChipDeviceControllerException if there was an issue during encoding (e.g. out of - * memory, invalid certificate format) + * @throws ChipDeviceControllerException if there was an issue during encoding + * (e.g. out of + * memory, invalid certificate format) */ public native byte[] convertX509CertToMatterCert(byte[] x509Cert); /** * Generates a new PASE verifier for the given setup PIN code. * - * @param devicePtr a pointer to the device object for which to generate the PASE verifier + * @param devicePtr a pointer to the device object for which to generate the + * PASE verifier * @param setupPincode the PIN code to use - * @param iterations the number of iterations for computing the verifier - * @param salt the 16-byte salt + * @param iterations the number of iterations for computing the verifier + * @param salt the 16-byte salt */ public PaseVerifierParams computePaseVerifier( long devicePtr, long setupPincode, long iterations, byte[] salt) { @@ -844,15 +712,17 @@ private native void read( private native long newDeviceController(ControllerParams params); + private native void setDeviceAttestationDelegate( + int failSafeExpiryTimeout, + DeviceAttestationDelegate delegate); + private native void pairDevice( long deviceControllerPtr, long deviceId, int connectionId, long pinCode, @Nullable byte[] csrNonce, - NetworkCredentials networkCredentials, - @Nullable DeviceAttestationDelegate delegate, - int failSafeExpiryTimeout); + NetworkCredentials networkCredentials); private native void pairDeviceWithAddress( long deviceControllerPtr, @@ -861,9 +731,7 @@ private native void pairDeviceWithAddress( int port, int discriminator, long pinCode, - @Nullable byte[] csrNonce, - @Nullable DeviceAttestationDelegate delegate, - int failSafeExpiryTimeout); + @Nullable byte[] csrNonce); private native void establishPaseConnection( long deviceControllerPtr, long deviceId, int connId, long setupPincode); @@ -875,9 +743,7 @@ private native void commissionDevice( long deviceControllerPtr, long deviceId, @Nullable byte[] csrNonce, - @Nullable NetworkCredentials networkCredentials, - @Nullable DeviceAttestationDelegate delegate, - int failSafeExpiryTimeout); + @Nullable NetworkCredentials networkCredentials); private native void continueCommissioning( long deviceControllerPtr, long devicePtr, boolean ignoreAttestationFailure); @@ -953,28 +819,46 @@ protected void finalize() throws Throwable { } } - /** Interface to implement custom operational credentials issuer (NOC chain generation). */ + /** + * Interface to implement custom operational credentials issuer (NOC chain + * generation). + */ public interface NOCChainIssuer { /** - * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be - * called when the DAC chain must be verified and NOC chain needs to be issued from a CSR. This - * allows for custom credentials issuer and DAC verifier implementations, for example, when a - * proprietary cloud API will perform DAC verification and the NOC chain issuance from CSR. + * When a NOCChainIssuer is set for this controller, then + * onNOCChainGenerationNeeded will be + * called when the DAC chain must be verified and NOC chain needs to be issued + * from a CSR. This + * allows for custom credentials issuer and DAC verifier implementations, for + * example, when a + * proprietary cloud API will perform DAC verification and the NOC chain + * issuance from CSR. * - *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used + *

+ * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will + * be used * rather than the DefaultDACVerifier. * - *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and + *

+ * The commissioning workflow will stop upon the onNOCChainGenerationNeeded + * callback and * resume once onNOCChainGeneration is called. * - *

The following fields on the ControllerParams object passed to onNOCChainGeneration MUST be + *

+ * The following fields on the ControllerParams object passed to + * onNOCChainGeneration MUST be * populated: rootCertificate, intermediateCertificate, operationalCertificate * - *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in - * the AddNOC command set to the commissionee. If they are not populated, then the values + *

+ * If ipk and adminSubject are set on the ControllerParams object, then they + * will be used in + * the AddNOC command set to the commissionee. If they are not populated, then + * the values * provided in the ChipDeviceController initialization will be used. * - *

All csr and attestation fields are provided to allow for custom attestestation checks. + *

+ * All csr and attestation fields are provided to allow for custom + * attestestation checks. */ void onNOCChainGenerationNeeded(CSRInfo csrInfo, AttestationInfo attestationInfo); } @@ -982,13 +866,20 @@ public interface NOCChainIssuer { /** * Interface to listen for scan networks callbacks from CHIPDeviceController. * - *

Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the enable/disable - * WiFi or Thread network scan during commissioning in the the default CommissioningDelegate used + *

+ * Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the + * enable/disable + * WiFi or Thread network scan during commissioning in the the default + * CommissioningDelegate used * by the ChipDeviceCommissioner. * - *

When the callbacks onScanNetworksFailure or onScanNetworksSuccess are invoked, the - * commissioning flow has reached the kNeedsNetworkCreds and will wait to advance until this - * device controller's updateCommissioningNetworkCredentials method is called with the desired + *

+ * When the callbacks onScanNetworksFailure or onScanNetworksSuccess are + * invoked, the + * commissioning flow has reached the kNeedsNetworkCreds and will wait to + * advance until this + * device controller's updateCommissioningNetworkCredentials method is called + * with the desired * network credentials set. */ public interface ScanNetworksListener { @@ -998,10 +889,8 @@ public interface ScanNetworksListener { void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> - wiFiScanResults, - Optional> - threadScanResults); + Optional> wiFiScanResults, + Optional> threadScanResults); } /** Interface to listen for callbacks from CHIPDeviceController. */ @@ -1038,7 +927,9 @@ void onReadCommissioningInfo( /** Notifies the listener of the error. */ void onError(Throwable error); - /** Notifies the Commissioner when the OpCSR for the Comissionee is generated. */ + /** + * Notifies the Commissioner when the OpCSR for the Comissionee is generated. + */ void onOpCSRGenerationComplete(byte[] csr); } -} +} \ No newline at end of file From 27a3862a194a109d333a01c711ba91651b3f2874 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 28 Oct 2022 18:34:54 +0800 Subject: [PATCH 10/44] fix NetworkCredentials NPE --- .../provisioning/DeviceProvisioningFragment.kt | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt index 60c578e981850f..03e66cd2fb9b76 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt @@ -127,19 +127,16 @@ class DeviceProvisioningFragment : Fragment() { val deviceId = DeviceIdUtil.getNextAvailableId(requireContext()) val connId = bluetoothManager.connectionId - val network = NetworkCredentials() + var network: NetworkCredentials? = null var networkParcelable = checkNotNull(networkCredentialsParcelable) - val wifi = networkParcelable.getWiFiCredentials() - if (wifi != null) - { - network.setWiFiCredentials(wifi.getSsid(), wifi.getPassword()) + val wifi = networkParcelable.wiFiCredentials + if (wifi != null) { + network = NetworkCredentials.forWiFi(NetworkCredentials.WiFiCredentials(wifi.ssid, wifi.password)) } - - val thread = networkParcelable.getThreadCredentials() - if (thread != null) - { - network.setThreadCredentials(thread.getOperationalDataset()) + val thread = networkParcelable.threadCredentials + if (thread != null) { + network = NetworkCredentials.forThread(NetworkCredentials.ThreadCredentials(thread.operationalDataset)) } deviceController.pairDevice(gatt, connId, deviceId, deviceInfo.setupPinCode, network) From beb066a8e99a4de044a5a69498292a4f73b679e1 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 28 Oct 2022 19:01:20 +0800 Subject: [PATCH 11/44] Do not expose deviceController raw pointer --- .../java/CHIPDeviceController-JNI.cpp | 4 ++-- .../java/DeviceAttestationDelegateBridge.cpp | 12 ++++++------ .../java/DeviceAttestationDelegateBridge.h | 9 ++++----- .../ChipDeviceController.java | 12 +++++++----- .../DeviceAttestationDelegate.java | 19 +++++++------------ 5 files changed, 26 insertions(+), 30 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 72cc578982ad81..57018b557d5453 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -385,7 +385,7 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr } JNI_METHOD(void, setDeviceAttestationDelegate) -(JNIEnv * env, jobject self, jlong handle, jobject deviceAttestationDelegate, jint failSafeExpiryTimeout) +(JNIEnv * env, jobject self, jlong handle, jint failSafeExpiryTimeout, jobject deviceAttestationDelegate) { chip::DeviceLayer::StackLock lock; CHIP_ERROR err = CHIP_NO_ERROR; @@ -1484,7 +1484,7 @@ CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, job shouldWaitAfterDeviceAttestation = true; } *deviceAttestationDelegateBridge = - new DeviceAttestationDelegateBridge(handle, deviceAttestationDelegateRef, timeoutSecs, shouldWaitAfterDeviceAttestation); + new DeviceAttestationDelegateBridge(deviceAttestationDelegateRef, timeoutSecs, shouldWaitAfterDeviceAttestation); exit: return err; } diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index 52467c0ce2100e..89bd2eebc41f39 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -87,7 +87,7 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( { jmethodID onDeviceAttestationCompletedMethod; JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationCompleted", - "(JJLchip/devicecontroller/AttestationInfo;I)V", + "(JLchip/devicecontroller/AttestationInfo;I)V", &onDeviceAttestationCompletedMethod); VerifyOrReturn(onDeviceAttestationCompletedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation completed method")); @@ -95,19 +95,19 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( CHIP_ERROR err = N2J_AttestationInfo(env, info, javaAttestationInfo); VerifyOrReturn(err == CHIP_NO_ERROR, ChipLogError(Controller, "Failed to create AttestationInfo, error: %s", err.AsString())); - env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, mDeviceController, - reinterpret_cast(device), javaAttestationInfo, static_cast(attestationResult)); + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationCompletedMethod, reinterpret_cast(device), + javaAttestationInfo, static_cast(attestationResult)); } else if ((attestationResult != chip::Credentials::AttestationVerificationResult::kSuccess) && env->IsInstanceOf(mDeviceAttestationDelegate, failureCallbackCls)) { jmethodID onDeviceAttestationFailedMethod; - JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationFailed", "(JJI)V", + JniReferences::GetInstance().FindMethod(env, mDeviceAttestationDelegate, "onDeviceAttestationFailed", "(JI)V", &onDeviceAttestationFailedMethod); VerifyOrReturn(onDeviceAttestationFailedMethod != nullptr, ChipLogError(Controller, "Could not find deviceAttestation failed method")); - env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationFailedMethod, mDeviceController, - reinterpret_cast(device), static_cast(attestationResult)); + env->CallVoidMethod(mDeviceAttestationDelegate, onDeviceAttestationFailedMethod, reinterpret_cast(device), + static_cast(attestationResult)); } } } diff --git a/src/controller/java/DeviceAttestationDelegateBridge.h b/src/controller/java/DeviceAttestationDelegateBridge.h index 78ed6b8e1ee93d..258a53528eb4e3 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.h +++ b/src/controller/java/DeviceAttestationDelegateBridge.h @@ -24,11 +24,11 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestationDelegate { public: - DeviceAttestationDelegateBridge(jlong deviceController, jobject deviceAttestationDelegate, - chip::Optional expiryTimeoutSecs, bool shouldWaitAfterDeviceAttestation) : + DeviceAttestationDelegateBridge(jobject deviceAttestationDelegate, chip::Optional expiryTimeoutSecs, + bool shouldWaitAfterDeviceAttestation) : mResult(chip::Credentials::AttestationVerificationResult::kSuccess), - mDeviceController(deviceController), mDeviceAttestationDelegate(deviceAttestationDelegate), - mExpiryTimeoutSecs(expiryTimeoutSecs), mShouldWaitAfterDeviceAttestation(shouldWaitAfterDeviceAttestation) + mDeviceAttestationDelegate(deviceAttestationDelegate), mExpiryTimeoutSecs(expiryTimeoutSecs), + mShouldWaitAfterDeviceAttestation(shouldWaitAfterDeviceAttestation) {} ~DeviceAttestationDelegateBridge(); @@ -45,7 +45,6 @@ class DeviceAttestationDelegateBridge : public chip::Credentials::DeviceAttestat private: chip::Credentials::AttestationVerificationResult mResult; - jlong mDeviceController; jobject mDeviceAttestationDelegate = nullptr; chip::Optional mExpiryTimeoutSecs; const bool mShouldWaitAfterDeviceAttestation; diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index ebc0f98cc46365..3aad6774bfa144 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -102,7 +102,8 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { * When {@link * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, * long, AttestationInfo, int)} is received, - * {@link #continueCommissioning(long, boolean)} must be called. + * {@link #continueCommissioning(long, boolean)} + * must be called. * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before * onDeviceAttestationCompleted is invoked. @@ -113,7 +114,7 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { */ public void setDeviceAttestationCompletionCallback(int failSafeExpiryTimeout, DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback) { - setDeviceAttestationDelegate(failSafeExpiryTimeout, completionCallback); + setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeout, completionCallback); } /** @@ -123,8 +124,8 @@ public void setDeviceAttestationCompletionCallback(int failSafeExpiryTimeout, * * When {@link * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, - * long, int)} is received, {@link #continueCommissioning(long, boolean)} must - * be called. + * long, int)} is received, + * {@link #continueCommissioning(long, boolean)} must be called. * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before * onDeviceAttestationFailed is invoked. @@ -134,7 +135,7 @@ public void setDeviceAttestationCompletionCallback(int failSafeExpiryTimeout, */ public void setDeviceAttestationFailureCallback(int failSafeExpiryTimeout, DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback) { - setDeviceAttestationDelegate(failSafeExpiryTimeout, failureCallback); + setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeout, failureCallback); } public void pairDevice( @@ -713,6 +714,7 @@ private native void read( private native long newDeviceController(ControllerParams params); private native void setDeviceAttestationDelegate( + long deviceControllerPtr, int failSafeExpiryTimeout, DeviceAttestationDelegate delegate); diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index cfcc835630b273..1eca400f82318c 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -25,25 +25,20 @@ public interface DeviceAttestationCompletionCallback extends DeviceAttestationDe * This allows the callback to stop commissioning after examining the device * info (DAC, PAI, CD). * - * @param deviceControllerPtr Controller corresponding to the commissioning - * process - * @param devicePtr Handle of device being commissioned - * @param attestationInfo Attestation information for the device - * @param errorCode Error code on attestation failure. 0 if success. + * @param devicePtr Handle of device being commissioned + * @param attestationInfo Attestation information for the device + * @param errorCode Error code on attestation failure. 0 if success. */ - void onDeviceAttestationCompleted( - long deviceControllerPtr, long devicePtr, AttestationInfo attestationInfo, int errorCode); + void onDeviceAttestationCompleted(long devicePtr, AttestationInfo attestationInfo, int errorCode); } public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { /** * The callback will be invoked when device attestation failed * - * @param deviceControllerPtr Controller corresponding to the commissioning - * process - * @param devicePtr Handle of device being commissioned - * @param errorCode Error code for the failure. + * @param devicePtr Handle of device being commissioned + * @param errorCode Error code for the failure. */ - void onDeviceAttestationFailed(long deviceControllerPtr, long devicePtr, int errorCode); + void onDeviceAttestationFailed(long devicePtr, int errorCode); } } From f9d3dd559ff3a5b35c422b558467e91e16cf9bfb Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 28 Oct 2022 19:02:09 +0800 Subject: [PATCH 12/44] add sample --- .vscode/settings.json | 3 +- .../CHIPTool/.idea/jarRepositories.xml | 5 ++++ .../DeviceProvisioningFragment.kt | 29 ++++++++++++++++++- 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index a8e2b99d4e8a70..da43e31e8a21eb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -115,7 +115,8 @@ "condition_variable": "cpp", "numeric": "cpp", "random": "cpp", - "thread": "cpp" + "thread": "cpp", + "shared_mutex": "cpp" }, // Configure paths or glob patterns to exclude from file watching. "files.watcherExclude": { diff --git a/examples/android/CHIPTool/.idea/jarRepositories.xml b/examples/android/CHIPTool/.idea/jarRepositories.xml index a5f05cd8c87d4a..e34606ccde7a9d 100644 --- a/examples/android/CHIPTool/.idea/jarRepositories.xml +++ b/examples/android/CHIPTool/.idea/jarRepositories.xml @@ -21,5 +21,10 @@

Note: It is also possible for internal logic (within Autocommissioner, etc) to re-call + *

+ * Note: It is also possible for internal logic (within Autocommissioner, etc) + * to re-call * ArmFailSafe to account for network config delays. * * @param failsafeTimerSeconds @@ -172,10 +205,14 @@ public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { * Enable/disable wifi network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters passed to + *

+ * Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters + * passed to * the CommissioningDelegate. * - *

When a WiFi scan is attempted, the result will be propagated to the ScanNetworksListener + *

+ * When a WiFi scan is attempted, the result will be propagated to the + * ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -190,10 +227,14 @@ public Builder setAttemptNetworkScanWiFi(boolean attemptNetworkScanWiFi) { * Enable/disable Thread network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

Specifically, this sets AttemptThreadNetworkScan in the CommissioningParameters passed to + *

+ * Specifically, this sets AttemptThreadNetworkScan in the + * CommissioningParameters passed to * the CommissioningDelegate. * - *

When a Thread scan is attempted, the result will be propagated to the ScanNetworksListener + *

+ * When a Thread scan is attempted, the result will be propagated to the + * ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -205,13 +246,18 @@ public Builder setAttemptNetworkScanThread(boolean attemptNetworkScanThread) { } /** - * Disable the CASE phase of commissioning when the CommissioningComplete command is sent by + * Disable the CASE phase of commissioning when the CommissioningComplete + * command is sent by * this ChipDeviceCommissioner. * - *

Specifically, this sets SkipCommissioningComplete in the CommissioningParameters passed to + *

+ * Specifically, this sets SkipCommissioningComplete in the + * CommissioningParameters passed to * the CommissioningDelegate. * - *

A controller will set this to true when the CASE phase of commissioning is done by a + *

+ * A controller will set this to true when the CASE phase of commissioning is + * done by a * separate process, for example, by a Hub on the network. * * @param skipCommissioningComplete @@ -247,9 +293,21 @@ public Builder setIpk(byte[] ipk) { return this; } + public Builder setPaaCerts(ArrayList paaCerts) { + this.paaCerts = paaCerts; + return this; + } + + public Builder setCdCerts(ArrayList cdCerts) { + this.cdCerts = cdCerts; + return this; + } + /** - * Sets the AdminSubject value passed to ChipDeviceCommissioner's CommissioningParameters. This - * value is passed in the AddNoc command sent to the commissionee and represents the subject of + * Sets the AdminSubject value passed to ChipDeviceCommissioner's + * CommissioningParameters. This + * value is passed in the AddNoc command sent to the commissionee and represents + * the subject of * the default ACL created by that call. * * @param adminSubject From 8481cde8566ac9a7eabba3663c4ff01d50e879f3 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 3 Nov 2022 20:21:28 +0800 Subject: [PATCH 14/44] fix jni method --- src/controller/java/CHIPDeviceController-JNI.cpp | 7 ++++--- .../java/src/chip/devicecontroller/ControllerParams.java | 8 ++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index ad3ace35791645..23460fe2af0854 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -321,12 +321,13 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr SuccessOrExit(err); jmethodID getPaaCerts; - err = - chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getPaaCerts", "()java/util/ArrayList", &getPaaCerts); + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getPaaCerts", "()Ljava/util/ArrayList;", + &getPaaCerts); SuccessOrExit(err); jmethodID getCdCerts; - err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getCdCerts", "()java/util/ArrayList", &getCdCerts); + err = + chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getCdCerts", "()Ljava/util/ArrayList;", &getCdCerts); SuccessOrExit(err); { diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index b7489ca360ed18..ab5f471ea1eafe 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -105,6 +105,14 @@ public byte[] getIpk() { return ipk; } + public ArrayList getPaaCerts() { + return paaCerts; + } + + public ArrayList getCdCerts() { + return cdCerts; + } + public long getAdminSubject() { return adminSubject; } From e6211dbd73850c826557ba4d6018a14e9c09ff72 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Mon, 7 Nov 2022 16:15:36 +0800 Subject: [PATCH 15/44] fix certs loss of scope and add some comments --- .../java/AndroidDeviceControllerWrapper.cpp | 52 +++++++++++++++---- .../java/AndroidDeviceControllerWrapper.h | 5 +- .../java/AttestationTrustStoreBridge.cpp | 7 +-- .../java/AttestationTrustStoreBridge.h | 4 +- .../devicecontroller/ControllerParams.java | 14 +++++ 5 files changed, 65 insertions(+), 17 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index af2311933b2b11..8b185d9212e6b0 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -58,6 +58,21 @@ AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() chip::Platform::Delete(mKeypairBridge); mKeypairBridge = nullptr; } + if (mDeviceAttestationDelegateBridge != nullptr) + { + delete mDeviceAttestationDelegateBridge; + mDeviceAttestationDelegateBridge = nullptr; + } + if (mDeviceAttestationVerifier != nullptr) + { + delete mDeviceAttestationVerifier; + mDeviceAttestationVerifier = nullptr; + } + if (mAttestationTrustStoreBridge != nullptr) + { + delete mAttestationTrustStoreBridge; + mAttestationTrustStoreBridge = nullptr; + } } void AndroidDeviceControllerWrapper::SetJavaObjectRef(JavaVM * vm, jobject obj) @@ -133,18 +148,24 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( // Initialize device attestation verifier const Credentials::AttestationTrustStore * trustStore; + CHIP_ERROR err = CHIP_NO_ERROR; if (paaCertsArrayList) { jint listSize; JniReferences::GetInstance().GetListSize(paaCertsArrayList, listSize); - CHIP_ERROR err = CHIP_NO_ERROR; - std::vector paaCerts; + std::vector> paaCerts; for (uint8_t i = 0; i < listSize; i++) { jobject paaCertObj = nullptr; err = JniReferences::GetInstance().GetListItem(paaCertsArrayList, i, paaCertObj); + if (err != CHIP_NO_ERROR) + { + *errInfoOnFailure = err; + return nullptr; + } JniByteArray paaCert(env, static_cast(paaCertObj)); - paaCerts.push_back(paaCert.byteSpan()); + // Make a copy of the cert so that it does not loss of scope. + paaCerts.push_back(std::vector(paaCert.byteSpan().begin(), paaCert.byteSpan().end())); } wrapper->mAttestationTrustStoreBridge = new AttestationTrustStoreBridge(paaCerts); if (wrapper->mAttestationTrustStoreBridge == nullptr) @@ -159,27 +180,37 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( { trustStore = chip::Credentials::GetTestAttestationTrustStore(); } - DeviceAttestationVerifier * deviceAttestationVerifier = chip::Credentials::GetDefaultDACVerifier(trustStore); - chip::Credentials::SetDeviceAttestationVerifier(deviceAttestationVerifier); - CHIP_ERROR err = CHIP_NO_ERROR; + wrapper->mDeviceAttestationVerifier = chip::Credentials::GetDefaultDACVerifier(trustStore); + if (wrapper->mDeviceAttestationVerifier == nullptr) + { + ChipLogError(Controller, "Init failure while creating the device attestation verifier"); + *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; + return nullptr; + } if (cdCertsArrayList) { - auto cdTrustStore = deviceAttestationVerifier->GetCertificationDeclarationTrustStore(); + auto cdTrustStore = wrapper->mDeviceAttestationVerifier->GetCertificationDeclarationTrustStore(); if (cdTrustStore == nullptr) { - ChipLogError(Controller, "Failed to create cdTrustStore"); + ChipLogError(Controller, "Failed to get cd trust store"); *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; return nullptr; } jint listSize; JniReferences::GetInstance().GetListSize(cdCertsArrayList, listSize); - std::vector cdCerts; for (uint8_t i = 0; i < listSize; i++) { jobject cdCertObj = nullptr; err = JniReferences::GetInstance().GetListItem(cdCertsArrayList, i, cdCertObj); + if (err != CHIP_NO_ERROR) + { + *errInfoOnFailure = err; + return nullptr; + } JniByteArray cdCert(env, static_cast(cdCertObj)); - err = cdTrustStore->AddTrustedKey(cdCert.byteSpan()); + std::vector cdCertCopy(cdCert.byteSpan().begin(), cdCert.byteSpan().end()); + chip::ByteSpan trustedKey = chip::ByteSpan(cdCertCopy.data(), cdCertCopy.size()); + err = cdTrustStore->AddTrustedKey(trustedKey); if (err != CHIP_NO_ERROR) { *errInfoOnFailure = err; @@ -205,6 +236,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( setupParams.operationalCredentialsDelegate = opCredsIssuer; setupParams.defaultCommissioner = &wrapper->mAutoCommissioner; initParams.fabricIndependentStorage = wrapperStorage; + setupParams.deviceAttestationVerifier = wrapper->mDeviceAttestationVerifier; wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 1eeac51a694cd8..ade3d6e886e4f4 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -206,8 +206,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Credentials::PartialDACVerifier mPartialDACVerifier; - DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; - AttestationTrustStoreBridge * mAttestationTrustStoreBridge = nullptr; + DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; + AttestationTrustStoreBridge * mAttestationTrustStoreBridge = nullptr; + chip::Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; AndroidDeviceControllerWrapper(ChipDeviceControllerPtr controller, AndroidOperationalCredentialsIssuerPtr opCredsIssuer) : mController(std::move(controller)), mOpCredsIssuer(std::move(opCredsIssuer)) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index bb3b6012160919..8552fe84f744e3 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -15,20 +15,21 @@ * limitations under the License. */ -#import "AttestationTrustStoreBridge.h" +#include "AttestationTrustStoreBridge.h" +#include CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const { VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); - for (auto candidate : mPaaCerts) + for (auto paaCert : mPaaCerts) { + chip::ByteSpan candidate = chip::ByteSpan(paaCert.data(), paaCert.size()); uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; chip::MutableByteSpan candidateSkidSpan{ skidBuf }; VerifyOrReturnError(CHIP_NO_ERROR == chip::Crypto::ExtractSKIDFromX509Cert(candidate, candidateSkidSpan), CHIP_ERROR_INTERNAL); - if (skid.data_equal(candidateSkidSpan)) { // Found a match diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index c7c0ba07b4084f..c8413b1fb4cc7b 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -21,12 +21,12 @@ class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustStore { public: - AttestationTrustStoreBridge(std::vector paaCerts) : mPaaCerts(paaCerts) {} + AttestationTrustStoreBridge(std::vector> paaCerts) : mPaaCerts(paaCerts) {} ~AttestationTrustStoreBridge(){}; CHIP_ERROR GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const override; private: - std::vector mPaaCerts; + std::vector> mPaaCerts; }; diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index ab5f471ea1eafe..a7a0913626621d 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -301,11 +301,25 @@ public Builder setIpk(byte[] ipk) { return this; } + /** + * The Product Attestation Authority certificates that are trusted to sign + * device attestation information. + * + * @param paaCerts The Product Attestation Authority certificates + * containing the X.509 DER certificate. + */ public Builder setPaaCerts(ArrayList paaCerts) { this.paaCerts = paaCerts; return this; } + /** + * The Certificate Declaration certificates that are trusted to sign + * device attestation information. + * + * @param cdCerts The Certificate Declaration certificates + * containing the X.509 DER certificate. + */ public Builder setCdCerts(ArrayList cdCerts) { this.cdCerts = cdCerts; return this; From b26afb9dc9f948d4a261db6be0b7ede1d4348c09 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 8 Nov 2022 16:01:09 +0800 Subject: [PATCH 16/44] implement destructor --- .../java/AttestationTrustStoreBridge.cpp | 14 ++++++++++++++ src/controller/java/AttestationTrustStoreBridge.h | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 8552fe84f744e3..bb7e81b748b71c 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -18,6 +18,20 @@ #include "AttestationTrustStoreBridge.h" #include +AttestationTrustStoreBridge::~AttestationTrustStoreBridge() +{ + if (!mPaaCerts.empty()) + { + for (auto paaCert : mPaaCerts) + { + paaCert.clear(); + paaCert.shrink_to_fit(); + } + mPaaCerts.clear(); + mPaaCerts.shrink_to_fit(); + } +} + CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const { diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index c8413b1fb4cc7b..b5eb8ab5bf97ef 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -22,7 +22,7 @@ class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustSt { public: AttestationTrustStoreBridge(std::vector> paaCerts) : mPaaCerts(paaCerts) {} - ~AttestationTrustStoreBridge(){}; + ~AttestationTrustStoreBridge(); CHIP_ERROR GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const override; From 27584d610ab97e1063f4c7e2fe145708faf0abfd Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 8 Nov 2022 16:02:53 +0800 Subject: [PATCH 17/44] fix destructor crash --- src/controller/java/AndroidDeviceControllerWrapper.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 8b185d9212e6b0..e144791daa2137 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -180,7 +180,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( { trustStore = chip::Credentials::GetTestAttestationTrustStore(); } - wrapper->mDeviceAttestationVerifier = chip::Credentials::GetDefaultDACVerifier(trustStore); + wrapper->mDeviceAttestationVerifier = new Credentials::DefaultDACVerifier(trustStore); if (wrapper->mDeviceAttestationVerifier == nullptr) { ChipLogError(Controller, "Init failure while creating the device attestation verifier"); From a654ede32cbc2eb0d232e3a4d2bc9366ee4df9d6 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 8 Nov 2022 16:35:23 +0800 Subject: [PATCH 18/44] revoke vscode setting change --- .vscode/settings.json | 24 +----------------------- 1 file changed, 1 insertion(+), 23 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 7e0374d68b01a3..a8e2b99d4e8a70 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -115,29 +115,7 @@ "condition_variable": "cpp", "numeric": "cpp", "random": "cpp", - "thread": "cpp", - "shared_mutex": "cpp", - "__bits": "cpp", - "any": "cpp", - "cfenv": "cpp", - "charconv": "cpp", - "codecvt": "cpp", - "compare": "cpp", - "concepts": "cpp", - "csetjmp": "cpp", - "csignal": "cpp", - "forward_list": "cpp", - "future": "cpp", - "list": "cpp", - "numbers": "cpp", - "ranges": "cpp", - "scoped_allocator": "cpp", - "semaphore": "cpp", - "span": "cpp", - "typeindex": "cpp", - "unordered_set": "cpp", - "valarray": "cpp", - "variant": "cpp" + "thread": "cpp" }, // Configure paths or glob patterns to exclude from file watching. "files.watcherExclude": { From 59c8ca611644f277663ca8466f6e10627862b4b8 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Mon, 21 Nov 2022 16:33:53 +0800 Subject: [PATCH 19/44] Restyled by whitespace --- .../chip/devicecontroller/ChipDeviceController.java | 10 +++++----- .../src/chip/devicecontroller/ControllerParams.java | 4 ++-- .../devicecontroller/DeviceAttestationDelegate.java | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 3aad6774bfa144..0a701af95a0c31 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -98,13 +98,13 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { /** * If DeviceAttestationCompletionCallback is setted, then it will always be * called when device attestation completes. - * + * * When {@link * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, * long, AttestationInfo, int)} is received, * {@link #continueCommissioning(long, boolean)} * must be called. - * + * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before * onDeviceAttestationCompleted is invoked. * @param completionCallback the callback will be invoked when @@ -121,12 +121,12 @@ public void setDeviceAttestationCompletionCallback(int failSafeExpiryTimeout, * If DeviceAttestationFailureCallback is setted, then it will be called * when device attestation fails, and the client can decide to continue or stop * the commissioning. - * + * * When {@link * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, * long, int)} is received, * {@link #continueCommissioning(long, boolean)} must be called. - * + * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before * onDeviceAttestationFailed is invoked. * @param failureCallback the callback will be invoked when device @@ -934,4 +934,4 @@ void onReadCommissioningInfo( */ void onOpCSRGenerationComplete(byte[] csr); } -} \ No newline at end of file +} diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index a7a0913626621d..98355d297ffb3c 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -304,7 +304,7 @@ public Builder setIpk(byte[] ipk) { /** * The Product Attestation Authority certificates that are trusted to sign * device attestation information. - * + * * @param paaCerts The Product Attestation Authority certificates * containing the X.509 DER certificate. */ @@ -316,7 +316,7 @@ public Builder setPaaCerts(ArrayList paaCerts) { /** * The Certificate Declaration certificates that are trusted to sign * device attestation information. - * + * * @param cdCerts The Certificate Declaration certificates * containing the X.509 DER certificate. */ diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 1eca400f82318c..3634d753159875 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -35,7 +35,7 @@ public interface DeviceAttestationCompletionCallback extends DeviceAttestationDe public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { /** * The callback will be invoked when device attestation failed - * + * * @param devicePtr Handle of device being commissioned * @param errorCode Error code for the failure. */ From 38110157c3493182e623df34e71a19fa5453c942 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Mon, 21 Nov 2022 16:40:09 +0800 Subject: [PATCH 20/44] Restyled by google-java-format --- .../ChipDeviceController.java | 284 +++++++----------- .../devicecontroller/ControllerParams.java | 116 +++---- .../DeviceAttestationDelegate.java | 37 ++- 3 files changed, 158 insertions(+), 279 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 0a701af95a0c31..4eaedf4760d44e 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -37,8 +37,7 @@ public class ChipDeviceController { private NOCChainIssuer nocChainIssuer; /** - * To load class and jni, we need to new AndroidChipPlatform after jni load but - * before new + * To load class and jni, we need to new AndroidChipPlatform after jni load but before new * ChipDeviceController */ public static void loadJni() { @@ -46,10 +45,8 @@ public static void loadJni() { } /** - * Returns a new {@link ChipDeviceController} with the specified parameters. you - * must set a vendor - * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() - * 0xFFF4 is a test vendor + * Returns a new {@link ChipDeviceController} with the specified parameters. you must set a vendor + * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() 0xFFF4 is a test vendor * ID */ public ChipDeviceController(ControllerParams params) { @@ -68,24 +65,16 @@ public void setScanNetworksListener(ScanNetworksListener listener) { } /** - * Sets this DeviceController to use the given issuer for issuing operational - * certs and verifying - * the DAC. By default, the DeviceController uses an internal, - * OperationalCredentialsDelegate (see + * Sets this DeviceController to use the given issuer for issuing operational certs and verifying + * the DAC. By default, the DeviceController uses an internal, OperationalCredentialsDelegate (see * AndroidOperationalCredentialsIssuer). * - *

- * When a NOCChainIssuer is set for this controller, then - * onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed and DAC verified. This allows for - * custom credentials - * issuer and DAC verifier implementations, for example, when a proprietary - * cloud API will perform + *

When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed and DAC verified. This allows for custom credentials + * issuer and DAC verifier implementations, for example, when a proprietary cloud API will perform * DAC verification and the CSR signing. * - *

- * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will - * be used rather + *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used rather * than the DefaultDACVerifier. * * @param issuer @@ -96,44 +85,39 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { } /** - * If DeviceAttestationCompletionCallback is setted, then it will always be - * called when device attestation completes. + * If DeviceAttestationCompletionCallback is setted, then it will always be called when device + * attestation completes. * - * When {@link + *

When {@link * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, - * long, AttestationInfo, int)} is received, - * {@link #continueCommissioning(long, boolean)} - * must be called. + * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be + * called. * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationCompleted is invoked. - * @param completionCallback the callback will be invoked when - * deviceattestation - * completed with device info for additional - * verification. + * onDeviceAttestationCompleted is invoked. + * @param completionCallback the callback will be invoked when deviceattestation completed with + * device info for additional verification. */ - public void setDeviceAttestationCompletionCallback(int failSafeExpiryTimeout, + public void setDeviceAttestationCompletionCallback( + int failSafeExpiryTimeout, DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback) { setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeout, completionCallback); } /** - * If DeviceAttestationFailureCallback is setted, then it will be called - * when device attestation fails, and the client can decide to continue or stop - * the commissioning. + * If DeviceAttestationFailureCallback is setted, then it will be called when device attestation + * fails, and the client can decide to continue or stop the commissioning. * - * When {@link + *

When {@link * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, - * long, int)} is received, - * {@link #continueCommissioning(long, boolean)} must be called. + * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. * * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationFailed is invoked. - * @param failureCallback the callback will be invoked when device - * attestation - * failed. + * onDeviceAttestationFailed is invoked. + * @param failureCallback the callback will be invoked when device attestation failed. */ - public void setDeviceAttestationFailureCallback(int failSafeExpiryTimeout, + public void setDeviceAttestationFailureCallback( + int failSafeExpiryTimeout, DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback) { setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeout, failureCallback); } @@ -150,15 +134,12 @@ public void pairDevice( /** * Pair a device connected through BLE. * - * @param bleServer the BluetoothGatt representing the BLE connection to the - * device - * @param connId the BluetoothGatt Id representing the BLE connection to - * the device - * @param deviceId the node ID to assign to the device + * @param bleServer the BluetoothGatt representing the BLE connection to the device + * @param connId the BluetoothGatt Id representing the BLE connection to the device + * @param deviceId the node ID to assign to the device * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use - * an internally randomly - * generated CSR nonce. + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly + * generated CSR nonce. */ public void pairDevice( BluetoothGatt bleServer, @@ -219,9 +200,9 @@ public void establishPaseConnection(long deviceId, int connId, long setupPincode /** * Establish a secure PASE connection to the given device via IP address. * - * @param deviceId the ID of the node to connect to - * @param address the IP address at which the node is located - * @param port the port at which the node is located + * @param deviceId the ID of the node to connect to + * @param address the IP address at which the node is located + * @param port the port at which the node is located * @param setupPincode the pincode for this node */ public void establishPaseConnection(long deviceId, String address, int port, long setupPincode) { @@ -230,12 +211,11 @@ public void establishPaseConnection(long deviceId, String address, int port, lon } /** - * Initiates the automatic commissioning flow using the specified network - * credentials. It is + * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned + * @param deviceId the ID of the node to be commissioned * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice(long deviceId, @Nullable NetworkCredentials networkCredentials) { @@ -243,13 +223,12 @@ public void commissionDevice(long deviceId, @Nullable NetworkCredentials network } /** - * Initiates the automatic commissioning flow using the specified network - * credentials. It is + * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice( @@ -258,12 +237,10 @@ public void commissionDevice( } /** - * This function instructs the commissioner to proceed to the next stage of - * commissioning after + * This function instructs the commissioner to proceed to the next stage of commissioning after * attestation is reported. * - * @param devicePtr a pointer to the device which is being - * commissioned. + * @param devicePtr a pointer to the device which is being commissioned. * @param ignoreAttestationFailure whether to ignore device attestation failure. */ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailure) { @@ -271,28 +248,18 @@ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailu } /** - * When a NOCChainIssuer is set for this controller, then - * onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed. This allows for custom - * credentials issuer - * implementations, for example, when a proprietary cloud API will perform the - * CSR signing. + * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed. This allows for custom credentials issuer + * implementations, for example, when a proprietary cloud API will perform the CSR signing. * - *

- * The commissioning workflow will stop upon the onNOCChainGenerationNeeded - * callback and resume + *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and resume * once onNOCChainGeneration is called. * - *

- * The following fields on the ControllerParams object MUST be populated: - * rootCertificate, + *

The following fields on the ControllerParams object MUST be populated: rootCertificate, * intermediateCertificate, operationalCertificate * - *

- * If ipk and adminSubject are set on the ControllerParams object, then they - * will be used in - * the AddNOC command set to the commissionee. If they are not populated, then - * the values provided + *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in + * the AddNOC command set to the commissionee. If they are not populated, then the values provided * in the ChipDeviceController initialization will be used. * * @param params @@ -303,19 +270,14 @@ public int onNOCChainGeneration(ControllerParams params) { } /** - * Update the network credentials held by the commissioner for the current - * commissioning session. - * The updated values will be used by the commissioner if the network - * credentials haven't already + * Update the network credentials held by the commissioner for the current commissioning session. + * The updated values will be used by the commissioner if the network credentials haven't already * been sent to the device. * - *

- * Its expected that this method will be called in response to the NetworkScan - * or the + *

Its expected that this method will be called in response to the NetworkScan or the * ReadCommissioningInfo callbacks. * - * @param networkCredentials the credentials (Wi-Fi or Thread) to use in - * commissioning + * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning */ public void updateCommissioningNetworkCredentials(NetworkCredentials networkCredentials) { updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); @@ -326,8 +288,7 @@ public void unpairDevice(long deviceId) { } /** - * Returns a pointer to a device currently being commissioned. This should be - * used before the + * Returns a pointer to a device currently being commissioned. This should be used before the * device is operationally available. */ public long getDeviceBeingCommissionedPointer(long nodeId) { @@ -335,18 +296,12 @@ public long getDeviceBeingCommissionedPointer(long nodeId) { } /** - * Through GetConnectedDeviceCallback, returns a pointer to a connected device - * or an error. + * Through GetConnectedDeviceCallback, returns a pointer to a connected device or an error. * - *

- * The native code invoked by this method creates a strong reference to the - * provided callback, - * which is released only when GetConnectedDeviceCallback has returned success - * or failure. + *

The native code invoked by this method creates a strong reference to the provided callback, + * which is released only when GetConnectedDeviceCallback has returned success or failure. * - *

- * TODO(#8443): This method could benefit from a ChipDevice abstraction to hide - * the pointer + *

TODO(#8443): This method could benefit from a ChipDevice abstraction to hide the pointer * passing. */ public void getConnectedDevicePointer(long nodeId, GetConnectedDeviceCallback callback) { @@ -403,8 +358,10 @@ public void onScanNetworksFailure(int errorCode) { public void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> wiFiScanResults, - Optional> threadScanResults) { + Optional> + wiFiScanResults, + Optional> + threadScanResults) { if (scanNetworksListener != null) { scanNetworksListener.onScanNetworksSuccess( networkingStatus, debugText, wiFiScanResults, threadScanResults); @@ -469,12 +426,10 @@ public String getIpAddress(long deviceId) { } /** - * Returns the {@link NetworkLocation} at which the given {@code deviceId} has - * been found. + * Returns the {@link NetworkLocation} at which the given {@code deviceId} has been found. * * @param deviceId the 64-bit node ID of the device - * @throws ChipDeviceControllerException if the device location could not be - * resolved + * @throws ChipDeviceControllerException if the device location could not be resolved */ public NetworkLocation getNetworkLocation(long deviceId) { return getNetworkLocation(deviceControllerPtr, deviceId); @@ -485,19 +440,17 @@ public long getCompressedFabricId() { } /** - * Returns the compressed fabric ID based on the given root certificate and node - * operational + * Returns the compressed fabric ID based on the given root certificate and node operational * credentials. * * @param rcac the root certificate (in Matter cert form) - * @param noc the NOC (in Matter cert form) + * @param noc the NOC (in Matter cert form) * @see #convertX509CertToMatterCert(byte[]) */ public native long generateCompressedFabricId(byte[] rcac, byte[] noc); /** - * Get commmissionible Node. Commmissionible Node results are able to get using - * {@link + * Get commmissionible Node. Commmissionible Node results are able to get using {@link * ChipDeviceController.getDiscoveredDevice}. */ public void discoverCommissionableNodes() { @@ -540,13 +493,11 @@ public void shutdownSubscriptions(long devicePtr) { } /** - * Returns an attestation challenge for the given device, for which there must - * be an existing + * Returns an attestation challenge for the given device, for which there must be an existing * secure session. * * @param devicePtr a pointer to the device from which to retrieve the challenge - * @throws ChipDeviceControllerException if there is no secure session for the - * given device + * @throws ChipDeviceControllerException if there is no secure session for the given device */ public byte[] getAttestationChallenge(long devicePtr) { return getAttestationChallenge(deviceControllerPtr, devicePtr); @@ -560,7 +511,8 @@ public void subscribeToAttributePath( List attributePaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = + new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -581,7 +533,8 @@ public void subscribeToEventPath( List eventPaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = + new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -594,10 +547,7 @@ public void subscribeToEventPath( false); } - /** - * Subscribe to the given attribute/event path with keepSubscriptions and - * isFabricFiltered. - */ + /** Subscribe to the given attribute/event path with keepSubscriptions and isFabricFiltered. */ public void subscribeToPath( SubscriptionEstablishedCallback subscriptionEstablishedCallback, ResubscriptionAttemptCallback resubscriptionAttemptCallback, @@ -612,7 +562,8 @@ public void subscribeToPath( // TODO: pass resubscriptionAttemptCallback to ReportCallbackJni since jni layer // is not ready // for auto-resubscribe - ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = + new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -665,20 +616,18 @@ public void readPath( /** * Converts a given X.509v3 certificate into a Matter certificate. * - * @throws ChipDeviceControllerException if there was an issue during encoding - * (e.g. out of - * memory, invalid certificate format) + * @throws ChipDeviceControllerException if there was an issue during encoding (e.g. out of + * memory, invalid certificate format) */ public native byte[] convertX509CertToMatterCert(byte[] x509Cert); /** * Generates a new PASE verifier for the given setup PIN code. * - * @param devicePtr a pointer to the device object for which to generate the - * PASE verifier + * @param devicePtr a pointer to the device object for which to generate the PASE verifier * @param setupPincode the PIN code to use - * @param iterations the number of iterations for computing the verifier - * @param salt the 16-byte salt + * @param iterations the number of iterations for computing the verifier + * @param salt the 16-byte salt */ public PaseVerifierParams computePaseVerifier( long devicePtr, long setupPincode, long iterations, byte[] salt) { @@ -714,9 +663,7 @@ private native void read( private native long newDeviceController(ControllerParams params); private native void setDeviceAttestationDelegate( - long deviceControllerPtr, - int failSafeExpiryTimeout, - DeviceAttestationDelegate delegate); + long deviceControllerPtr, int failSafeExpiryTimeout, DeviceAttestationDelegate delegate); private native void pairDevice( long deviceControllerPtr, @@ -821,46 +768,28 @@ protected void finalize() throws Throwable { } } - /** - * Interface to implement custom operational credentials issuer (NOC chain - * generation). - */ + /** Interface to implement custom operational credentials issuer (NOC chain generation). */ public interface NOCChainIssuer { /** - * When a NOCChainIssuer is set for this controller, then - * onNOCChainGenerationNeeded will be - * called when the DAC chain must be verified and NOC chain needs to be issued - * from a CSR. This - * allows for custom credentials issuer and DAC verifier implementations, for - * example, when a - * proprietary cloud API will perform DAC verification and the NOC chain - * issuance from CSR. + * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be + * called when the DAC chain must be verified and NOC chain needs to be issued from a CSR. This + * allows for custom credentials issuer and DAC verifier implementations, for example, when a + * proprietary cloud API will perform DAC verification and the NOC chain issuance from CSR. * - *

- * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will - * be used + *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used * rather than the DefaultDACVerifier. * - *

- * The commissioning workflow will stop upon the onNOCChainGenerationNeeded - * callback and + *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and * resume once onNOCChainGeneration is called. * - *

- * The following fields on the ControllerParams object passed to - * onNOCChainGeneration MUST be + *

The following fields on the ControllerParams object passed to onNOCChainGeneration MUST be * populated: rootCertificate, intermediateCertificate, operationalCertificate * - *

- * If ipk and adminSubject are set on the ControllerParams object, then they - * will be used in - * the AddNOC command set to the commissionee. If they are not populated, then - * the values + *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in + * the AddNOC command set to the commissionee. If they are not populated, then the values * provided in the ChipDeviceController initialization will be used. * - *

- * All csr and attestation fields are provided to allow for custom - * attestestation checks. + *

All csr and attestation fields are provided to allow for custom attestestation checks. */ void onNOCChainGenerationNeeded(CSRInfo csrInfo, AttestationInfo attestationInfo); } @@ -868,20 +797,13 @@ public interface NOCChainIssuer { /** * Interface to listen for scan networks callbacks from CHIPDeviceController. * - *

- * Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the - * enable/disable - * WiFi or Thread network scan during commissioning in the the default - * CommissioningDelegate used + *

Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the enable/disable + * WiFi or Thread network scan during commissioning in the the default CommissioningDelegate used * by the ChipDeviceCommissioner. * - *

- * When the callbacks onScanNetworksFailure or onScanNetworksSuccess are - * invoked, the - * commissioning flow has reached the kNeedsNetworkCreds and will wait to - * advance until this - * device controller's updateCommissioningNetworkCredentials method is called - * with the desired + *

When the callbacks onScanNetworksFailure or onScanNetworksSuccess are invoked, the + * commissioning flow has reached the kNeedsNetworkCreds and will wait to advance until this + * device controller's updateCommissioningNetworkCredentials method is called with the desired * network credentials set. */ public interface ScanNetworksListener { @@ -891,8 +813,10 @@ public interface ScanNetworksListener { void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> wiFiScanResults, - Optional> threadScanResults); + Optional> + wiFiScanResults, + Optional> + threadScanResults); } /** Interface to listen for callbacks from CHIPDeviceController. */ @@ -929,9 +853,7 @@ void onReadCommissioningInfo( /** Notifies the listener of the error. */ void onError(Throwable error); - /** - * Notifies the Commissioner when the OpCSR for the Comissionee is generated. - */ + /** Notifies the Commissioner when the OpCSR for the Comissionee is generated. */ void onOpCSRGenerationComplete(byte[] csr); } } diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index 98355d297ffb3c..8d660d20193733 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -1,13 +1,9 @@ package chip.devicecontroller; import java.util.ArrayList; - import javax.annotation.Nullable; -/** - * Parameters representing initialization arguments for - * {@link ChipDeviceController}. - */ +/** Parameters representing initialization arguments for {@link ChipDeviceController}. */ public final class ControllerParams { private final long fabricId; @@ -17,27 +13,18 @@ public final class ControllerParams { private final boolean attemptNetworkScanWiFi; private final boolean attemptNetworkScanThread; private final boolean skipCommissioningComplete; - @Nullable - private final KeypairDelegate keypairDelegate; - @Nullable - private final byte[] rootCertificate; - @Nullable - private final byte[] intermediateCertificate; - @Nullable - private final byte[] operationalCertificate; - @Nullable - private final byte[] ipk; - @Nullable - private final ArrayList paaCerts; - @Nullable - private final ArrayList cdCerts; + @Nullable private final KeypairDelegate keypairDelegate; + @Nullable private final byte[] rootCertificate; + @Nullable private final byte[] intermediateCertificate; + @Nullable private final byte[] operationalCertificate; + @Nullable private final byte[] ipk; + @Nullable private final ArrayList paaCerts; + @Nullable private final ArrayList cdCerts; private final long adminSubject; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; - /** - * @param udpListenPort the UDP listening port, or 0 to pick any available port. - */ + /** @param udpListenPort the UDP listening port, or 0 to pick any available port. */ private ControllerParams(Builder builder) { this.fabricId = builder.fabricId; this.udpListenPort = builder.udpListenPort; @@ -123,8 +110,7 @@ public static Builder newBuilder() { } /** - * Returns parameters which uses the provided {@code operationalKeyConfig} as - * its operating + * Returns parameters which uses the provided {@code operationalKeyConfig} as its operating * credentials. You must set a vendor ID, 0xFFF4 is a test vendor ID * ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() */ @@ -146,24 +132,16 @@ public static class Builder { private boolean attemptNetworkScanWiFi = false; private boolean attemptNetworkScanThread = false; private boolean skipCommissioningComplete = false; - @Nullable - private KeypairDelegate keypairDelegate = null; - @Nullable - private byte[] rootCertificate = null; - @Nullable - private byte[] intermediateCertificate = null; - @Nullable - private byte[] operationalCertificate = null; - @Nullable - private byte[] ipk = null; - @Nullable - private ArrayList paaCerts; - @Nullable - private ArrayList cdCerts; + @Nullable private KeypairDelegate keypairDelegate = null; + @Nullable private byte[] rootCertificate = null; + @Nullable private byte[] intermediateCertificate = null; + @Nullable private byte[] operationalCertificate = null; + @Nullable private byte[] ipk = null; + @Nullable private ArrayList paaCerts; + @Nullable private ArrayList cdCerts; private long adminSubject = 0; - private Builder() { - } + private Builder() {} public Builder setFabricId(long fabricId) { if (fabricId < 1) { @@ -187,15 +165,11 @@ public Builder setControllerVendorId(int controllerVendorId) { } /** - * Sets the FailsafeTimer duration passed to ChipDeviceCommissioner's - * CommissioningParameters. - * Increasing this value from its default will allow more time for network - * scans, cloud op cert + * Sets the FailsafeTimer duration passed to ChipDeviceCommissioner's CommissioningParameters. + * Increasing this value from its default will allow more time for network scans, cloud op cert * signing calls, and user interaction. * - *

- * Note: It is also possible for internal logic (within Autocommissioner, etc) - * to re-call + *

Note: It is also possible for internal logic (within Autocommissioner, etc) to re-call * ArmFailSafe to account for network config delays. * * @param failsafeTimerSeconds @@ -213,14 +187,10 @@ public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { * Enable/disable wifi network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

- * Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters - * passed to + *

Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters passed to * the CommissioningDelegate. * - *

- * When a WiFi scan is attempted, the result will be propagated to the - * ScanNetworksListener + *

When a WiFi scan is attempted, the result will be propagated to the ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -235,14 +205,10 @@ public Builder setAttemptNetworkScanWiFi(boolean attemptNetworkScanWiFi) { * Enable/disable Thread network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

- * Specifically, this sets AttemptThreadNetworkScan in the - * CommissioningParameters passed to + *

Specifically, this sets AttemptThreadNetworkScan in the CommissioningParameters passed to * the CommissioningDelegate. * - *

- * When a Thread scan is attempted, the result will be propagated to the - * ScanNetworksListener + *

When a Thread scan is attempted, the result will be propagated to the ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -254,18 +220,13 @@ public Builder setAttemptNetworkScanThread(boolean attemptNetworkScanThread) { } /** - * Disable the CASE phase of commissioning when the CommissioningComplete - * command is sent by + * Disable the CASE phase of commissioning when the CommissioningComplete command is sent by * this ChipDeviceCommissioner. * - *

- * Specifically, this sets SkipCommissioningComplete in the - * CommissioningParameters passed to + *

Specifically, this sets SkipCommissioningComplete in the CommissioningParameters passed to * the CommissioningDelegate. * - *

- * A controller will set this to true when the CASE phase of commissioning is - * done by a + *

A controller will set this to true when the CASE phase of commissioning is done by a * separate process, for example, by a Hub on the network. * * @param skipCommissioningComplete @@ -302,11 +263,11 @@ public Builder setIpk(byte[] ipk) { } /** - * The Product Attestation Authority certificates that are trusted to sign - * device attestation information. + * The Product Attestation Authority certificates that are trusted to sign device attestation + * information. * - * @param paaCerts The Product Attestation Authority certificates - * containing the X.509 DER certificate. + * @param paaCerts The Product Attestation Authority certificates containing the X.509 DER + * certificate. */ public Builder setPaaCerts(ArrayList paaCerts) { this.paaCerts = paaCerts; @@ -314,11 +275,10 @@ public Builder setPaaCerts(ArrayList paaCerts) { } /** - * The Certificate Declaration certificates that are trusted to sign - * device attestation information. + * The Certificate Declaration certificates that are trusted to sign device attestation + * information. * - * @param cdCerts The Certificate Declaration certificates - * containing the X.509 DER certificate. + * @param cdCerts The Certificate Declaration certificates containing the X.509 DER certificate. */ public Builder setCdCerts(ArrayList cdCerts) { this.cdCerts = cdCerts; @@ -326,10 +286,8 @@ public Builder setCdCerts(ArrayList cdCerts) { } /** - * Sets the AdminSubject value passed to ChipDeviceCommissioner's - * CommissioningParameters. This - * value is passed in the AddNoc command sent to the commissionee and represents - * the subject of + * Sets the AdminSubject value passed to ChipDeviceCommissioner's CommissioningParameters. This + * value is passed in the AddNoc command sent to the commissionee and represents the subject of * the default ACL created by that call. * * @param adminSubject diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 3634d753159875..3f9e48d1c76332 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -2,34 +2,33 @@ /** * Only one of the following delegate callbacks should be implemented. - *

- * If one of the following callbacks is implemented, - * {@link ChipDeviceController#continueCommissioning(long, boolean)} is expected - * to be called if commissioning should continue. - *

- * If DeviceAttestationCompletionCallback is implemented, then it will always be - * called when device attestation completes. - *

- * If DeviceAttestationFailureCallback is implemented, then it will be called - * when device attestation fails, and the client can decide to continue or stop - * the commissioning. + * + *

If one of the following callbacks is implemented, {@link + * ChipDeviceController#continueCommissioning(long, boolean)} is expected to be called if + * commissioning should continue. + * + *

If DeviceAttestationCompletionCallback is implemented, then it will always be called when + * device attestation completes. + * + *

If DeviceAttestationFailureCallback is implemented, then it will be called when device + * attestation fails, and the client can decide to continue or stop the commissioning. */ public interface DeviceAttestationDelegate { public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { /** - * The callback will be invoked when device attestation completed with device - * info for additional verification. + * The callback will be invoked when device attestation completed with device info for + * additional verification. * - *

- * This allows the callback to stop commissioning after examining the device - * info (DAC, PAI, CD). + *

This allows the callback to stop commissioning after examining the device info (DAC, PAI, + * CD). * - * @param devicePtr Handle of device being commissioned + * @param devicePtr Handle of device being commissioned * @param attestationInfo Attestation information for the device - * @param errorCode Error code on attestation failure. 0 if success. + * @param errorCode Error code on attestation failure. 0 if success. */ - void onDeviceAttestationCompleted(long devicePtr, AttestationInfo attestationInfo, int errorCode); + void onDeviceAttestationCompleted( + long devicePtr, AttestationInfo attestationInfo, int errorCode); } public interface DeviceAttestationFailureCallback extends DeviceAttestationDelegate { From 8c0108390f44f4620901737a2e47718eefae27aa Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Mon, 21 Nov 2022 16:41:02 +0800 Subject: [PATCH 21/44] Restyled by clang-format --- src/controller/java/CHIPDeviceController-JNI.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 23460fe2af0854..788faa65e2c368 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -611,7 +611,7 @@ JNI_METHOD(void, continueCommissioning) : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { From 8837adfa4dc109f2b2adefef9eb36c7f521041f0 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 15 Dec 2022 10:11:28 +0800 Subject: [PATCH 22/44] fix conflict --- .../java/AndroidDeviceControllerWrapper.cpp | 2 +- .../java/AndroidDeviceControllerWrapper.h | 24 +++++++++++++------ .../java/CHIPDeviceController-JNI.cpp | 2 +- 3 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index fe52bfab899c12..031b63142bd360 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -173,7 +173,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( jint listSize; JniReferences::GetInstance().GetListSize(paaCertsArrayList, listSize); std::vector> paaCerts; - for (uint8_t i = 0; i < listSize; i++) + for (jint i = 0; i < listSize; i++) { jobject paaCertObj = nullptr; err = JniReferences::GetInstance().GetListItem(paaCertsArrayList, i, paaCertObj); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index eb6ab1e7502a53..f88742258fe9ae 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -105,9 +105,15 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; CHIP_ERROR SyncDeleteKeyValue(const char * key) override; - chip::Controller::AutoCommissioner * GetAutoCommissioner() { return &mAutoCommissioner; } + chip::Controller::AutoCommissioner * GetAutoCommissioner() + { + return &mAutoCommissioner; + } - chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() { return &mPartialDACVerifier; } + chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() + { + return &mPartialDACVerifier; + } const chip::Controller::CommissioningParameters & GetCommissioningParameters() const { @@ -149,6 +155,8 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel * @param[in] intermediateCertificate an X.509 DER-encoded intermediate certificate for this node * @param[in] nodeOperationalCertificate an X.509 DER-encoded operational certificate for this node * @param[in] ipkEpochKey the IPK epoch key to use for this node + * @param[in] paaCertsArrayList + * @param[in] cdCertsArrayList * @param[in] listenPort the UDP port to listen on * @param[in] controllerVendorId the vendor ID identifying the controller * @param[in] failsafeTimerSeconds the failsafe timer in seconds @@ -168,9 +176,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel AndroidOperationalCredentialsIssuerPtr opCredsIssuer, #endif jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, - jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, - uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, - bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure); + jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, jobject paaCertsArrayList, jobject cdCertsArrayList, + uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, + bool attemptNetworkScanThread, bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure); #ifdef JAVA_MATTER_CONTROLLER_TEST chip::Controller::ExampleOperationalCredentialsIssuer * GetAndroidOperationalCredentialsIssuer() @@ -186,7 +194,10 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; } - DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } + DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() + { + return mDeviceAttestationDelegateBridge; + } void ClearDeviceAttestationDelegateBridge() { @@ -233,7 +244,6 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Credentials::PartialDACVerifier mPartialDACVerifier; - DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; AttestationTrustStoreBridge * mAttestationTrustStoreBridge = nullptr; chip::Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index a267480906d358..f5c9d747be752a 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -642,7 +642,7 @@ JNI_METHOD(void, continueCommissioning) : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { From 212dc10f767eac30ba4752120e9acbe568e91d03 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 15 Dec 2022 11:30:18 +0800 Subject: [PATCH 23/44] add unit of failSafeExpiryTimeout --- .../DeviceProvisioningFragment.kt | 13 +- .../java/CHIPDeviceController-JNI.cpp | 10 +- .../ChipDeviceController.java | 287 +++++++++++------- .../DeviceAttestationDelegate.java | 35 ++- 4 files changed, 227 insertions(+), 118 deletions(-) diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt index 66da9e3ec49a45..62135d93eca831 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/provisioning/DeviceProvisioningFragment.kt @@ -139,9 +139,11 @@ class DeviceProvisioningFragment : Fragment() { if (thread != null) { network = NetworkCredentials.forThread(NetworkCredentials.ThreadCredentials(thread.operationalDataset)) } - deviceController.setDeviceAttestationFailureCallback(600 + deviceController.setDeviceAttestationFailureCallback(DEVICE_ATTESTATION_FAILED_TIMEOUT ) { devicePtr, errorCode -> - Log.i(TAG, "Device attestation errorCode: $errorCode") + Log.i(TAG, "Device attestation errorCode: $errorCode, " + + "Look at 'src/credentials/attestation_verifier/DeviceAttestationVerifier.h' " + + "AttestationVerificationResult enum to understand the errors") requireActivity().runOnUiThread(Runnable { val alertDialog: AlertDialog? = activity?.let { val builder = AlertDialog.Builder(it) @@ -233,6 +235,13 @@ class DeviceProvisioningFragment : Fragment() { private const val ARG_NETWORK_CREDENTIALS = "network_credentials" private const val STATUS_PAIRING_SUCCESS = 0 + /** + * Set for the fail-safe timer before onDeviceAttestationFailed is invoked. + * + * This time depends on the Commissioning timeout of your app. + */ + private const val DEVICE_ATTESTATION_FAILED_TIMEOUT = 600 + /** * Return a new instance of [DeviceProvisioningFragment]. [networkCredentialsParcelable] can be null for * IP commissioning. diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index f5c9d747be752a..816995c347935e 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -85,7 +85,7 @@ static CHIP_ERROR ParseEventPathList(jobject eventPathList, std::vectorClearDeviceAttestationDelegateBridge(); DeviceAttestationDelegateBridge * deviceAttestationDelegateBridge = nullptr; - err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeout, + err = CreateDeviceAttestationDelegateBridge(env, handle, deviceAttestationDelegate, failSafeExpiryTimeoutSecs, &deviceAttestationDelegateBridge); VerifyOrExit(err == CHIP_NO_ERROR, err = CHIP_JNI_ERROR_EXCEPTION_THROWN); wrapper->SetDeviceAttestationDelegateBridge(deviceAttestationDelegateBridge); @@ -1526,11 +1526,11 @@ CHIP_ERROR N2J_NetworkLocation(JNIEnv * env, jstring ipAddress, jint port, jint } CHIP_ERROR CreateDeviceAttestationDelegateBridge(JNIEnv * env, jlong handle, jobject deviceAttestationDelegate, - jint failSafeExpiryTimeout, + jint failSafeExpiryTimeoutSecs, DeviceAttestationDelegateBridge ** deviceAttestationDelegateBridge) { CHIP_ERROR err = CHIP_NO_ERROR; - chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeout)); + chip::Optional timeoutSecs = chip::MakeOptional(static_cast(failSafeExpiryTimeoutSecs)); bool shouldWaitAfterDeviceAttestation = false; jclass completionCallbackCls = nullptr; jobject deviceAttestationDelegateRef = env->NewGlobalRef(deviceAttestationDelegate); diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 4eaedf4760d44e..31b1f58d16a48d 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -37,7 +37,8 @@ public class ChipDeviceController { private NOCChainIssuer nocChainIssuer; /** - * To load class and jni, we need to new AndroidChipPlatform after jni load but before new + * To load class and jni, we need to new AndroidChipPlatform after jni load but + * before new * ChipDeviceController */ public static void loadJni() { @@ -45,8 +46,10 @@ public static void loadJni() { } /** - * Returns a new {@link ChipDeviceController} with the specified parameters. you must set a vendor - * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() 0xFFF4 is a test vendor + * Returns a new {@link ChipDeviceController} with the specified parameters. you + * must set a vendor + * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() + * 0xFFF4 is a test vendor * ID */ public ChipDeviceController(ControllerParams params) { @@ -65,16 +68,24 @@ public void setScanNetworksListener(ScanNetworksListener listener) { } /** - * Sets this DeviceController to use the given issuer for issuing operational certs and verifying - * the DAC. By default, the DeviceController uses an internal, OperationalCredentialsDelegate (see + * Sets this DeviceController to use the given issuer for issuing operational + * certs and verifying + * the DAC. By default, the DeviceController uses an internal, + * OperationalCredentialsDelegate (see * AndroidOperationalCredentialsIssuer). * - *

When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed and DAC verified. This allows for custom credentials - * issuer and DAC verifier implementations, for example, when a proprietary cloud API will perform + *

+ * When a NOCChainIssuer is set for this controller, then + * onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed and DAC verified. This allows for + * custom credentials + * issuer and DAC verifier implementations, for example, when a proprietary + * cloud API will perform * DAC verification and the CSR signing. * - *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used rather + *

+ * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will + * be used rather * than the DefaultDACVerifier. * * @param issuer @@ -85,41 +96,53 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { } /** - * If DeviceAttestationCompletionCallback is setted, then it will always be called when device + * If DeviceAttestationCompletionCallback is setted, then it will always be + * called when device * attestation completes. * - *

When {@link + *

+ * When {@link * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, - * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be + * long, AttestationInfo, int)} is received, + * {@link #continueCommissioning(long, boolean)} must be * called. * - * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationCompleted is invoked. - * @param completionCallback the callback will be invoked when deviceattestation completed with - * device info for additional verification. + * @param failSafeExpiryTimeoutSecs the value to set for the fail-safe timer + * before + * onDeviceAttestationCompleted is invoked. The + * unit is seconds. + * @param completionCallback the callback will be invoked when + * deviceattestation completed with + * device info for additional verification. */ public void setDeviceAttestationCompletionCallback( - int failSafeExpiryTimeout, + int failSafeExpiryTimeoutSecs, DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback) { - setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeout, completionCallback); + setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeoutSecs, completionCallback); } /** - * If DeviceAttestationFailureCallback is setted, then it will be called when device attestation + * If DeviceAttestationFailureCallback is setted, then it will be called when + * device attestation * fails, and the client can decide to continue or stop the commissioning. * - *

When {@link + *

+ * When {@link * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, - * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. + * long, int)} is received, {@link #continueCommissioning(long, boolean)} must + * be called. * - * @param failSafeExpiryTimeout the value to set for the fail-safe timer before - * onDeviceAttestationFailed is invoked. - * @param failureCallback the callback will be invoked when device attestation failed. + * @param failSafeExpiryTimeoutSecs the value to set for the fail-safe timer + * before + * onDeviceAttestationFailed is invoked. The + * unit is seconds. + * @param failureCallback the callback will be invoked when device + * attestation failed. */ public void setDeviceAttestationFailureCallback( - int failSafeExpiryTimeout, + int failSafeExpiryTimeoutSecs, DeviceAttestationDelegate.DeviceAttestationFailureCallback failureCallback) { - setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeout, failureCallback); + setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeoutSecs, failureCallback); } public void pairDevice( @@ -134,12 +157,15 @@ public void pairDevice( /** * Pair a device connected through BLE. * - * @param bleServer the BluetoothGatt representing the BLE connection to the device - * @param connId the BluetoothGatt Id representing the BLE connection to the device - * @param deviceId the node ID to assign to the device + * @param bleServer the BluetoothGatt representing the BLE connection to the + * device + * @param connId the BluetoothGatt Id representing the BLE connection to + * the device + * @param deviceId the node ID to assign to the device * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly - * generated CSR nonce. + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use + * an internally randomly + * generated CSR nonce. */ public void pairDevice( BluetoothGatt bleServer, @@ -200,9 +226,9 @@ public void establishPaseConnection(long deviceId, int connId, long setupPincode /** * Establish a secure PASE connection to the given device via IP address. * - * @param deviceId the ID of the node to connect to - * @param address the IP address at which the node is located - * @param port the port at which the node is located + * @param deviceId the ID of the node to connect to + * @param address the IP address at which the node is located + * @param port the port at which the node is located * @param setupPincode the pincode for this node */ public void establishPaseConnection(long deviceId, String address, int port, long setupPincode) { @@ -211,11 +237,12 @@ public void establishPaseConnection(long deviceId, String address, int port, lon } /** - * Initiates the automatic commissioning flow using the specified network credentials. It is + * Initiates the automatic commissioning flow using the specified network + * credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned + * @param deviceId the ID of the node to be commissioned * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice(long deviceId, @Nullable NetworkCredentials networkCredentials) { @@ -223,12 +250,13 @@ public void commissionDevice(long deviceId, @Nullable NetworkCredentials network } /** - * Initiates the automatic commissioning flow using the specified network credentials. It is + * Initiates the automatic commissioning flow using the specified network + * credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice( @@ -237,10 +265,12 @@ public void commissionDevice( } /** - * This function instructs the commissioner to proceed to the next stage of commissioning after + * This function instructs the commissioner to proceed to the next stage of + * commissioning after * attestation is reported. * - * @param devicePtr a pointer to the device which is being commissioned. + * @param devicePtr a pointer to the device which is being + * commissioned. * @param ignoreAttestationFailure whether to ignore device attestation failure. */ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailure) { @@ -248,18 +278,28 @@ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailu } /** - * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed. This allows for custom credentials issuer - * implementations, for example, when a proprietary cloud API will perform the CSR signing. + * When a NOCChainIssuer is set for this controller, then + * onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed. This allows for custom + * credentials issuer + * implementations, for example, when a proprietary cloud API will perform the + * CSR signing. * - *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and resume + *

+ * The commissioning workflow will stop upon the onNOCChainGenerationNeeded + * callback and resume * once onNOCChainGeneration is called. * - *

The following fields on the ControllerParams object MUST be populated: rootCertificate, + *

+ * The following fields on the ControllerParams object MUST be populated: + * rootCertificate, * intermediateCertificate, operationalCertificate * - *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in - * the AddNOC command set to the commissionee. If they are not populated, then the values provided + *

+ * If ipk and adminSubject are set on the ControllerParams object, then they + * will be used in + * the AddNOC command set to the commissionee. If they are not populated, then + * the values provided * in the ChipDeviceController initialization will be used. * * @param params @@ -270,14 +310,19 @@ public int onNOCChainGeneration(ControllerParams params) { } /** - * Update the network credentials held by the commissioner for the current commissioning session. - * The updated values will be used by the commissioner if the network credentials haven't already + * Update the network credentials held by the commissioner for the current + * commissioning session. + * The updated values will be used by the commissioner if the network + * credentials haven't already * been sent to the device. * - *

Its expected that this method will be called in response to the NetworkScan or the + *

+ * Its expected that this method will be called in response to the NetworkScan + * or the * ReadCommissioningInfo callbacks. * - * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning + * @param networkCredentials the credentials (Wi-Fi or Thread) to use in + * commissioning */ public void updateCommissioningNetworkCredentials(NetworkCredentials networkCredentials) { updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); @@ -288,7 +333,8 @@ public void unpairDevice(long deviceId) { } /** - * Returns a pointer to a device currently being commissioned. This should be used before the + * Returns a pointer to a device currently being commissioned. This should be + * used before the * device is operationally available. */ public long getDeviceBeingCommissionedPointer(long nodeId) { @@ -296,12 +342,18 @@ public long getDeviceBeingCommissionedPointer(long nodeId) { } /** - * Through GetConnectedDeviceCallback, returns a pointer to a connected device or an error. + * Through GetConnectedDeviceCallback, returns a pointer to a connected device + * or an error. * - *

The native code invoked by this method creates a strong reference to the provided callback, - * which is released only when GetConnectedDeviceCallback has returned success or failure. + *

+ * The native code invoked by this method creates a strong reference to the + * provided callback, + * which is released only when GetConnectedDeviceCallback has returned success + * or failure. * - *

TODO(#8443): This method could benefit from a ChipDevice abstraction to hide the pointer + *

+ * TODO(#8443): This method could benefit from a ChipDevice abstraction to hide + * the pointer * passing. */ public void getConnectedDevicePointer(long nodeId, GetConnectedDeviceCallback callback) { @@ -358,10 +410,8 @@ public void onScanNetworksFailure(int errorCode) { public void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> - wiFiScanResults, - Optional> - threadScanResults) { + Optional> wiFiScanResults, + Optional> threadScanResults) { if (scanNetworksListener != null) { scanNetworksListener.onScanNetworksSuccess( networkingStatus, debugText, wiFiScanResults, threadScanResults); @@ -426,10 +476,12 @@ public String getIpAddress(long deviceId) { } /** - * Returns the {@link NetworkLocation} at which the given {@code deviceId} has been found. + * Returns the {@link NetworkLocation} at which the given {@code deviceId} has + * been found. * * @param deviceId the 64-bit node ID of the device - * @throws ChipDeviceControllerException if the device location could not be resolved + * @throws ChipDeviceControllerException if the device location could not be + * resolved */ public NetworkLocation getNetworkLocation(long deviceId) { return getNetworkLocation(deviceControllerPtr, deviceId); @@ -440,17 +492,19 @@ public long getCompressedFabricId() { } /** - * Returns the compressed fabric ID based on the given root certificate and node operational + * Returns the compressed fabric ID based on the given root certificate and node + * operational * credentials. * * @param rcac the root certificate (in Matter cert form) - * @param noc the NOC (in Matter cert form) + * @param noc the NOC (in Matter cert form) * @see #convertX509CertToMatterCert(byte[]) */ public native long generateCompressedFabricId(byte[] rcac, byte[] noc); /** - * Get commmissionible Node. Commmissionible Node results are able to get using {@link + * Get commmissionible Node. Commmissionible Node results are able to get using + * {@link * ChipDeviceController.getDiscoveredDevice}. */ public void discoverCommissionableNodes() { @@ -493,11 +547,13 @@ public void shutdownSubscriptions(long devicePtr) { } /** - * Returns an attestation challenge for the given device, for which there must be an existing + * Returns an attestation challenge for the given device, for which there must + * be an existing * secure session. * * @param devicePtr a pointer to the device from which to retrieve the challenge - * @throws ChipDeviceControllerException if there is no secure session for the given device + * @throws ChipDeviceControllerException if there is no secure session for the + * given device */ public byte[] getAttestationChallenge(long devicePtr) { return getAttestationChallenge(deviceControllerPtr, devicePtr); @@ -511,8 +567,7 @@ public void subscribeToAttributePath( List attributePaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = - new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -533,8 +588,7 @@ public void subscribeToEventPath( List eventPaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = - new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -547,7 +601,10 @@ public void subscribeToEventPath( false); } - /** Subscribe to the given attribute/event path with keepSubscriptions and isFabricFiltered. */ + /** + * Subscribe to the given attribute/event path with keepSubscriptions and + * isFabricFiltered. + */ public void subscribeToPath( SubscriptionEstablishedCallback subscriptionEstablishedCallback, ResubscriptionAttemptCallback resubscriptionAttemptCallback, @@ -562,8 +619,7 @@ public void subscribeToPath( // TODO: pass resubscriptionAttemptCallback to ReportCallbackJni since jni layer // is not ready // for auto-resubscribe - ReportCallbackJni jniCallback = - new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -616,18 +672,20 @@ public void readPath( /** * Converts a given X.509v3 certificate into a Matter certificate. * - * @throws ChipDeviceControllerException if there was an issue during encoding (e.g. out of - * memory, invalid certificate format) + * @throws ChipDeviceControllerException if there was an issue during encoding + * (e.g. out of + * memory, invalid certificate format) */ public native byte[] convertX509CertToMatterCert(byte[] x509Cert); /** * Generates a new PASE verifier for the given setup PIN code. * - * @param devicePtr a pointer to the device object for which to generate the PASE verifier + * @param devicePtr a pointer to the device object for which to generate the + * PASE verifier * @param setupPincode the PIN code to use - * @param iterations the number of iterations for computing the verifier - * @param salt the 16-byte salt + * @param iterations the number of iterations for computing the verifier + * @param salt the 16-byte salt */ public PaseVerifierParams computePaseVerifier( long devicePtr, long setupPincode, long iterations, byte[] salt) { @@ -663,7 +721,7 @@ private native void read( private native long newDeviceController(ControllerParams params); private native void setDeviceAttestationDelegate( - long deviceControllerPtr, int failSafeExpiryTimeout, DeviceAttestationDelegate delegate); + long deviceControllerPtr, int failSafeExpiryTimeoutSecs, DeviceAttestationDelegate delegate); private native void pairDevice( long deviceControllerPtr, @@ -768,28 +826,46 @@ protected void finalize() throws Throwable { } } - /** Interface to implement custom operational credentials issuer (NOC chain generation). */ + /** + * Interface to implement custom operational credentials issuer (NOC chain + * generation). + */ public interface NOCChainIssuer { /** - * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be - * called when the DAC chain must be verified and NOC chain needs to be issued from a CSR. This - * allows for custom credentials issuer and DAC verifier implementations, for example, when a - * proprietary cloud API will perform DAC verification and the NOC chain issuance from CSR. + * When a NOCChainIssuer is set for this controller, then + * onNOCChainGenerationNeeded will be + * called when the DAC chain must be verified and NOC chain needs to be issued + * from a CSR. This + * allows for custom credentials issuer and DAC verifier implementations, for + * example, when a + * proprietary cloud API will perform DAC verification and the NOC chain + * issuance from CSR. * - *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used + *

+ * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will + * be used * rather than the DefaultDACVerifier. * - *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and + *

+ * The commissioning workflow will stop upon the onNOCChainGenerationNeeded + * callback and * resume once onNOCChainGeneration is called. * - *

The following fields on the ControllerParams object passed to onNOCChainGeneration MUST be + *

+ * The following fields on the ControllerParams object passed to + * onNOCChainGeneration MUST be * populated: rootCertificate, intermediateCertificate, operationalCertificate * - *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in - * the AddNOC command set to the commissionee. If they are not populated, then the values + *

+ * If ipk and adminSubject are set on the ControllerParams object, then they + * will be used in + * the AddNOC command set to the commissionee. If they are not populated, then + * the values * provided in the ChipDeviceController initialization will be used. * - *

All csr and attestation fields are provided to allow for custom attestestation checks. + *

+ * All csr and attestation fields are provided to allow for custom + * attestestation checks. */ void onNOCChainGenerationNeeded(CSRInfo csrInfo, AttestationInfo attestationInfo); } @@ -797,13 +873,20 @@ public interface NOCChainIssuer { /** * Interface to listen for scan networks callbacks from CHIPDeviceController. * - *

Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the enable/disable - * WiFi or Thread network scan during commissioning in the the default CommissioningDelegate used + *

+ * Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the + * enable/disable + * WiFi or Thread network scan during commissioning in the the default + * CommissioningDelegate used * by the ChipDeviceCommissioner. * - *

When the callbacks onScanNetworksFailure or onScanNetworksSuccess are invoked, the - * commissioning flow has reached the kNeedsNetworkCreds and will wait to advance until this - * device controller's updateCommissioningNetworkCredentials method is called with the desired + *

+ * When the callbacks onScanNetworksFailure or onScanNetworksSuccess are + * invoked, the + * commissioning flow has reached the kNeedsNetworkCreds and will wait to + * advance until this + * device controller's updateCommissioningNetworkCredentials method is called + * with the desired * network credentials set. */ public interface ScanNetworksListener { @@ -813,10 +896,8 @@ public interface ScanNetworksListener { void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> - wiFiScanResults, - Optional> - threadScanResults); + Optional> wiFiScanResults, + Optional> threadScanResults); } /** Interface to listen for callbacks from CHIPDeviceController. */ @@ -853,7 +934,9 @@ void onReadCommissioningInfo( /** Notifies the listener of the error. */ void onError(Throwable error); - /** Notifies the Commissioner when the OpCSR for the Comissionee is generated. */ + /** + * Notifies the Commissioner when the OpCSR for the Comissionee is generated. + */ void onOpCSRGenerationComplete(byte[] csr); } } diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 3f9e48d1c76332..9e35919e1094b4 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -3,29 +3,46 @@ /** * Only one of the following delegate callbacks should be implemented. * - *

If one of the following callbacks is implemented, {@link - * ChipDeviceController#continueCommissioning(long, boolean)} is expected to be called if + *

+ * If one of the following callbacks is implemented, {@link + * ChipDeviceController#continueCommissioning(long, boolean)} is expected to be + * called if * commissioning should continue. * - *

If DeviceAttestationCompletionCallback is implemented, then it will always be called when + *

+ * If DeviceAttestationCompletionCallback is implemented, then it will always be + * called when * device attestation completes. * - *

If DeviceAttestationFailureCallback is implemented, then it will be called when device - * attestation fails, and the client can decide to continue or stop the commissioning. + *

+ * If DeviceAttestationFailureCallback is implemented, then it will be called + * when device + * attestation fails, and the client can decide to continue or stop the + * commissioning. + * + * For example: + * + *

+ * deviceController.continueCommissioning(devicePtr, false)
+ * 
+ * */ public interface DeviceAttestationDelegate { public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { /** - * The callback will be invoked when device attestation completed with device info for + * The callback will be invoked when device attestation completed with device + * info for * additional verification. * - *

This allows the callback to stop commissioning after examining the device info (DAC, PAI, + *

+ * This allows the callback to stop commissioning after examining the device + * info (DAC, PAI, * CD). * - * @param devicePtr Handle of device being commissioned + * @param devicePtr Handle of device being commissioned * @param attestationInfo Attestation information for the device - * @param errorCode Error code on attestation failure. 0 if success. + * @param errorCode Error code on attestation failure. 0 if success. */ void onDeviceAttestationCompleted( long devicePtr, AttestationInfo attestationInfo, int errorCode); From 9d41d2640e5e6e228f0772b19e85ff74380e2e24 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 15 Dec 2022 11:31:40 +0800 Subject: [PATCH 24/44] add sample code --- .../chip/devicecontroller/DeviceAttestationDelegate.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 9e35919e1094b4..00811dfeb763fb 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -23,7 +23,11 @@ * For example: * *

- * deviceController.continueCommissioning(devicePtr, false)
+ * // Continue commissioning
+ * deviceController.continueCommissioning(devicePtr, true)
+ * 
+ * // Stop commissioning
+ * deviceController.continueCommissioning(devicePtr, true)
  * 
* */ From 747645d25ace336dfe20c30b7f91709843922f1f Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 15 Dec 2022 11:45:38 +0800 Subject: [PATCH 25/44] Restyled by whitespace --- .../chip/devicecontroller/DeviceAttestationDelegate.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 00811dfeb763fb..7aa8b50e1755ff 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -19,17 +19,17 @@ * when device * attestation fails, and the client can decide to continue or stop the * commissioning. - * + * * For example: - * + * *
  * // Continue commissioning
  * deviceController.continueCommissioning(devicePtr, true)
- * 
+ *
  * // Stop commissioning
  * deviceController.continueCommissioning(devicePtr, true)
  * 
- * + * */ public interface DeviceAttestationDelegate { From 17348b2a2a1cf83dc292db13ff9837147a28fd0b Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 15 Dec 2022 11:46:48 +0800 Subject: [PATCH 26/44] Restyled by google-java-format --- .../ChipDeviceController.java | 280 +++++++----------- .../DeviceAttestationDelegate.java | 31 +- 2 files changed, 109 insertions(+), 202 deletions(-) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 31b1f58d16a48d..74f1628b5eb63d 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -37,8 +37,7 @@ public class ChipDeviceController { private NOCChainIssuer nocChainIssuer; /** - * To load class and jni, we need to new AndroidChipPlatform after jni load but - * before new + * To load class and jni, we need to new AndroidChipPlatform after jni load but before new * ChipDeviceController */ public static void loadJni() { @@ -46,10 +45,8 @@ public static void loadJni() { } /** - * Returns a new {@link ChipDeviceController} with the specified parameters. you - * must set a vendor - * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() - * 0xFFF4 is a test vendor + * Returns a new {@link ChipDeviceController} with the specified parameters. you must set a vendor + * ID, ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() 0xFFF4 is a test vendor * ID */ public ChipDeviceController(ControllerParams params) { @@ -68,24 +65,16 @@ public void setScanNetworksListener(ScanNetworksListener listener) { } /** - * Sets this DeviceController to use the given issuer for issuing operational - * certs and verifying - * the DAC. By default, the DeviceController uses an internal, - * OperationalCredentialsDelegate (see + * Sets this DeviceController to use the given issuer for issuing operational certs and verifying + * the DAC. By default, the DeviceController uses an internal, OperationalCredentialsDelegate (see * AndroidOperationalCredentialsIssuer). * - *

- * When a NOCChainIssuer is set for this controller, then - * onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed and DAC verified. This allows for - * custom credentials - * issuer and DAC verifier implementations, for example, when a proprietary - * cloud API will perform + *

When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed and DAC verified. This allows for custom credentials + * issuer and DAC verifier implementations, for example, when a proprietary cloud API will perform * DAC verification and the CSR signing. * - *

- * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will - * be used rather + *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used rather * than the DefaultDACVerifier. * * @param issuer @@ -96,48 +85,37 @@ public void setNOCChainIssuer(NOCChainIssuer issuer) { } /** - * If DeviceAttestationCompletionCallback is setted, then it will always be - * called when device + * If DeviceAttestationCompletionCallback is setted, then it will always be called when device * attestation completes. * - *

- * When {@link + *

When {@link * DeviceAttestationDelegate.DeviceAttestationCompletionCallback#onDeviceAttestationCompleted(long, - * long, AttestationInfo, int)} is received, - * {@link #continueCommissioning(long, boolean)} must be + * long, AttestationInfo, int)} is received, {@link #continueCommissioning(long, boolean)} must be * called. * - * @param failSafeExpiryTimeoutSecs the value to set for the fail-safe timer - * before - * onDeviceAttestationCompleted is invoked. The - * unit is seconds. - * @param completionCallback the callback will be invoked when - * deviceattestation completed with - * device info for additional verification. + * @param failSafeExpiryTimeoutSecs the value to set for the fail-safe timer before + * onDeviceAttestationCompleted is invoked. The unit is seconds. + * @param completionCallback the callback will be invoked when deviceattestation completed with + * device info for additional verification. */ public void setDeviceAttestationCompletionCallback( int failSafeExpiryTimeoutSecs, DeviceAttestationDelegate.DeviceAttestationCompletionCallback completionCallback) { - setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeoutSecs, completionCallback); + setDeviceAttestationDelegate( + deviceControllerPtr, failSafeExpiryTimeoutSecs, completionCallback); } /** - * If DeviceAttestationFailureCallback is setted, then it will be called when - * device attestation + * If DeviceAttestationFailureCallback is setted, then it will be called when device attestation * fails, and the client can decide to continue or stop the commissioning. * - *

- * When {@link + *

When {@link * DeviceAttestationDelegate.DeviceAttestationFailureCallback#onDeviceAttestationFailed(long, - * long, int)} is received, {@link #continueCommissioning(long, boolean)} must - * be called. + * long, int)} is received, {@link #continueCommissioning(long, boolean)} must be called. * - * @param failSafeExpiryTimeoutSecs the value to set for the fail-safe timer - * before - * onDeviceAttestationFailed is invoked. The - * unit is seconds. - * @param failureCallback the callback will be invoked when device - * attestation failed. + * @param failSafeExpiryTimeoutSecs the value to set for the fail-safe timer before + * onDeviceAttestationFailed is invoked. The unit is seconds. + * @param failureCallback the callback will be invoked when device attestation failed. */ public void setDeviceAttestationFailureCallback( int failSafeExpiryTimeoutSecs, @@ -157,15 +135,12 @@ public void pairDevice( /** * Pair a device connected through BLE. * - * @param bleServer the BluetoothGatt representing the BLE connection to the - * device - * @param connId the BluetoothGatt Id representing the BLE connection to - * the device - * @param deviceId the node ID to assign to the device + * @param bleServer the BluetoothGatt representing the BLE connection to the device + * @param connId the BluetoothGatt Id representing the BLE connection to the device + * @param deviceId the node ID to assign to the device * @param setupPincode the pincode for the device - * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use - * an internally randomly - * generated CSR nonce. + * @param csrNonce the 32-byte CSR nonce to use, or null if we want to use an internally randomly + * generated CSR nonce. */ public void pairDevice( BluetoothGatt bleServer, @@ -226,9 +201,9 @@ public void establishPaseConnection(long deviceId, int connId, long setupPincode /** * Establish a secure PASE connection to the given device via IP address. * - * @param deviceId the ID of the node to connect to - * @param address the IP address at which the node is located - * @param port the port at which the node is located + * @param deviceId the ID of the node to connect to + * @param address the IP address at which the node is located + * @param port the port at which the node is located * @param setupPincode the pincode for this node */ public void establishPaseConnection(long deviceId, String address, int port, long setupPincode) { @@ -237,12 +212,11 @@ public void establishPaseConnection(long deviceId, String address, int port, lon } /** - * Initiates the automatic commissioning flow using the specified network - * credentials. It is + * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned + * @param deviceId the ID of the node to be commissioned * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice(long deviceId, @Nullable NetworkCredentials networkCredentials) { @@ -250,13 +224,12 @@ public void commissionDevice(long deviceId, @Nullable NetworkCredentials network } /** - * Initiates the automatic commissioning flow using the specified network - * credentials. It is + * Initiates the automatic commissioning flow using the specified network credentials. It is * expected that a secure session has already been established via {@link * #establishPaseConnection(long, int, long)}. * - * @param deviceId the ID of the node to be commissioned - * @param csrNonce a nonce to be used for the CSR request + * @param deviceId the ID of the node to be commissioned + * @param csrNonce a nonce to be used for the CSR request * @param networkCredentials the credentials (Wi-Fi or Thread) to be provisioned */ public void commissionDevice( @@ -265,12 +238,10 @@ public void commissionDevice( } /** - * This function instructs the commissioner to proceed to the next stage of - * commissioning after + * This function instructs the commissioner to proceed to the next stage of commissioning after * attestation is reported. * - * @param devicePtr a pointer to the device which is being - * commissioned. + * @param devicePtr a pointer to the device which is being commissioned. * @param ignoreAttestationFailure whether to ignore device attestation failure. */ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailure) { @@ -278,28 +249,18 @@ public void continueCommissioning(long devicePtr, boolean ignoreAttestationFailu } /** - * When a NOCChainIssuer is set for this controller, then - * onNOCChainGenerationNeeded will be - * called when the NOC CSR needs to be signed. This allows for custom - * credentials issuer - * implementations, for example, when a proprietary cloud API will perform the - * CSR signing. + * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be + * called when the NOC CSR needs to be signed. This allows for custom credentials issuer + * implementations, for example, when a proprietary cloud API will perform the CSR signing. * - *

- * The commissioning workflow will stop upon the onNOCChainGenerationNeeded - * callback and resume + *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and resume * once onNOCChainGeneration is called. * - *

- * The following fields on the ControllerParams object MUST be populated: - * rootCertificate, + *

The following fields on the ControllerParams object MUST be populated: rootCertificate, * intermediateCertificate, operationalCertificate * - *

- * If ipk and adminSubject are set on the ControllerParams object, then they - * will be used in - * the AddNOC command set to the commissionee. If they are not populated, then - * the values provided + *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in + * the AddNOC command set to the commissionee. If they are not populated, then the values provided * in the ChipDeviceController initialization will be used. * * @param params @@ -310,19 +271,14 @@ public int onNOCChainGeneration(ControllerParams params) { } /** - * Update the network credentials held by the commissioner for the current - * commissioning session. - * The updated values will be used by the commissioner if the network - * credentials haven't already + * Update the network credentials held by the commissioner for the current commissioning session. + * The updated values will be used by the commissioner if the network credentials haven't already * been sent to the device. * - *

- * Its expected that this method will be called in response to the NetworkScan - * or the + *

Its expected that this method will be called in response to the NetworkScan or the * ReadCommissioningInfo callbacks. * - * @param networkCredentials the credentials (Wi-Fi or Thread) to use in - * commissioning + * @param networkCredentials the credentials (Wi-Fi or Thread) to use in commissioning */ public void updateCommissioningNetworkCredentials(NetworkCredentials networkCredentials) { updateCommissioningNetworkCredentials(deviceControllerPtr, networkCredentials); @@ -333,8 +289,7 @@ public void unpairDevice(long deviceId) { } /** - * Returns a pointer to a device currently being commissioned. This should be - * used before the + * Returns a pointer to a device currently being commissioned. This should be used before the * device is operationally available. */ public long getDeviceBeingCommissionedPointer(long nodeId) { @@ -342,18 +297,12 @@ public long getDeviceBeingCommissionedPointer(long nodeId) { } /** - * Through GetConnectedDeviceCallback, returns a pointer to a connected device - * or an error. + * Through GetConnectedDeviceCallback, returns a pointer to a connected device or an error. * - *

- * The native code invoked by this method creates a strong reference to the - * provided callback, - * which is released only when GetConnectedDeviceCallback has returned success - * or failure. + *

The native code invoked by this method creates a strong reference to the provided callback, + * which is released only when GetConnectedDeviceCallback has returned success or failure. * - *

- * TODO(#8443): This method could benefit from a ChipDevice abstraction to hide - * the pointer + *

TODO(#8443): This method could benefit from a ChipDevice abstraction to hide the pointer * passing. */ public void getConnectedDevicePointer(long nodeId, GetConnectedDeviceCallback callback) { @@ -410,8 +359,10 @@ public void onScanNetworksFailure(int errorCode) { public void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> wiFiScanResults, - Optional> threadScanResults) { + Optional> + wiFiScanResults, + Optional> + threadScanResults) { if (scanNetworksListener != null) { scanNetworksListener.onScanNetworksSuccess( networkingStatus, debugText, wiFiScanResults, threadScanResults); @@ -476,12 +427,10 @@ public String getIpAddress(long deviceId) { } /** - * Returns the {@link NetworkLocation} at which the given {@code deviceId} has - * been found. + * Returns the {@link NetworkLocation} at which the given {@code deviceId} has been found. * * @param deviceId the 64-bit node ID of the device - * @throws ChipDeviceControllerException if the device location could not be - * resolved + * @throws ChipDeviceControllerException if the device location could not be resolved */ public NetworkLocation getNetworkLocation(long deviceId) { return getNetworkLocation(deviceControllerPtr, deviceId); @@ -492,19 +441,17 @@ public long getCompressedFabricId() { } /** - * Returns the compressed fabric ID based on the given root certificate and node - * operational + * Returns the compressed fabric ID based on the given root certificate and node operational * credentials. * * @param rcac the root certificate (in Matter cert form) - * @param noc the NOC (in Matter cert form) + * @param noc the NOC (in Matter cert form) * @see #convertX509CertToMatterCert(byte[]) */ public native long generateCompressedFabricId(byte[] rcac, byte[] noc); /** - * Get commmissionible Node. Commmissionible Node results are able to get using - * {@link + * Get commmissionible Node. Commmissionible Node results are able to get using {@link * ChipDeviceController.getDiscoveredDevice}. */ public void discoverCommissionableNodes() { @@ -547,13 +494,11 @@ public void shutdownSubscriptions(long devicePtr) { } /** - * Returns an attestation challenge for the given device, for which there must - * be an existing + * Returns an attestation challenge for the given device, for which there must be an existing * secure session. * * @param devicePtr a pointer to the device from which to retrieve the challenge - * @throws ChipDeviceControllerException if there is no secure session for the - * given device + * @throws ChipDeviceControllerException if there is no secure session for the given device */ public byte[] getAttestationChallenge(long devicePtr) { return getAttestationChallenge(deviceControllerPtr, devicePtr); @@ -567,7 +512,8 @@ public void subscribeToAttributePath( List attributePaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = + new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -588,7 +534,8 @@ public void subscribeToEventPath( List eventPaths, int minInterval, int maxInterval) { - ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = + new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -601,10 +548,7 @@ public void subscribeToEventPath( false); } - /** - * Subscribe to the given attribute/event path with keepSubscriptions and - * isFabricFiltered. - */ + /** Subscribe to the given attribute/event path with keepSubscriptions and isFabricFiltered. */ public void subscribeToPath( SubscriptionEstablishedCallback subscriptionEstablishedCallback, ResubscriptionAttemptCallback resubscriptionAttemptCallback, @@ -619,7 +563,8 @@ public void subscribeToPath( // TODO: pass resubscriptionAttemptCallback to ReportCallbackJni since jni layer // is not ready // for auto-resubscribe - ReportCallbackJni jniCallback = new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); + ReportCallbackJni jniCallback = + new ReportCallbackJni(subscriptionEstablishedCallback, reportCallback, null); subscribe( deviceControllerPtr, jniCallback.getCallbackHandle(), @@ -672,20 +617,18 @@ public void readPath( /** * Converts a given X.509v3 certificate into a Matter certificate. * - * @throws ChipDeviceControllerException if there was an issue during encoding - * (e.g. out of - * memory, invalid certificate format) + * @throws ChipDeviceControllerException if there was an issue during encoding (e.g. out of + * memory, invalid certificate format) */ public native byte[] convertX509CertToMatterCert(byte[] x509Cert); /** * Generates a new PASE verifier for the given setup PIN code. * - * @param devicePtr a pointer to the device object for which to generate the - * PASE verifier + * @param devicePtr a pointer to the device object for which to generate the PASE verifier * @param setupPincode the PIN code to use - * @param iterations the number of iterations for computing the verifier - * @param salt the 16-byte salt + * @param iterations the number of iterations for computing the verifier + * @param salt the 16-byte salt */ public PaseVerifierParams computePaseVerifier( long devicePtr, long setupPincode, long iterations, byte[] salt) { @@ -826,46 +769,28 @@ protected void finalize() throws Throwable { } } - /** - * Interface to implement custom operational credentials issuer (NOC chain - * generation). - */ + /** Interface to implement custom operational credentials issuer (NOC chain generation). */ public interface NOCChainIssuer { /** - * When a NOCChainIssuer is set for this controller, then - * onNOCChainGenerationNeeded will be - * called when the DAC chain must be verified and NOC chain needs to be issued - * from a CSR. This - * allows for custom credentials issuer and DAC verifier implementations, for - * example, when a - * proprietary cloud API will perform DAC verification and the NOC chain - * issuance from CSR. + * When a NOCChainIssuer is set for this controller, then onNOCChainGenerationNeeded will be + * called when the DAC chain must be verified and NOC chain needs to be issued from a CSR. This + * allows for custom credentials issuer and DAC verifier implementations, for example, when a + * proprietary cloud API will perform DAC verification and the NOC chain issuance from CSR. * - *

- * When a NOCChainIssuer is set for this controller, the PartialDACVerifier will - * be used + *

When a NOCChainIssuer is set for this controller, the PartialDACVerifier will be used * rather than the DefaultDACVerifier. * - *

- * The commissioning workflow will stop upon the onNOCChainGenerationNeeded - * callback and + *

The commissioning workflow will stop upon the onNOCChainGenerationNeeded callback and * resume once onNOCChainGeneration is called. * - *

- * The following fields on the ControllerParams object passed to - * onNOCChainGeneration MUST be + *

The following fields on the ControllerParams object passed to onNOCChainGeneration MUST be * populated: rootCertificate, intermediateCertificate, operationalCertificate * - *

- * If ipk and adminSubject are set on the ControllerParams object, then they - * will be used in - * the AddNOC command set to the commissionee. If they are not populated, then - * the values + *

If ipk and adminSubject are set on the ControllerParams object, then they will be used in + * the AddNOC command set to the commissionee. If they are not populated, then the values * provided in the ChipDeviceController initialization will be used. * - *

- * All csr and attestation fields are provided to allow for custom - * attestestation checks. + *

All csr and attestation fields are provided to allow for custom attestestation checks. */ void onNOCChainGenerationNeeded(CSRInfo csrInfo, AttestationInfo attestationInfo); } @@ -873,20 +798,13 @@ public interface NOCChainIssuer { /** * Interface to listen for scan networks callbacks from CHIPDeviceController. * - *

- * Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the - * enable/disable - * WiFi or Thread network scan during commissioning in the the default - * CommissioningDelegate used + *

Set the AttemptNetworkScanWiFi or AttemptNetworkScanThread to configure the enable/disable + * WiFi or Thread network scan during commissioning in the the default CommissioningDelegate used * by the ChipDeviceCommissioner. * - *

- * When the callbacks onScanNetworksFailure or onScanNetworksSuccess are - * invoked, the - * commissioning flow has reached the kNeedsNetworkCreds and will wait to - * advance until this - * device controller's updateCommissioningNetworkCredentials method is called - * with the desired + *

When the callbacks onScanNetworksFailure or onScanNetworksSuccess are invoked, the + * commissioning flow has reached the kNeedsNetworkCreds and will wait to advance until this + * device controller's updateCommissioningNetworkCredentials method is called with the desired * network credentials set. */ public interface ScanNetworksListener { @@ -896,8 +814,10 @@ public interface ScanNetworksListener { void onScanNetworksSuccess( Integer networkingStatus, Optional debugText, - Optional> wiFiScanResults, - Optional> threadScanResults); + Optional> + wiFiScanResults, + Optional> + threadScanResults); } /** Interface to listen for callbacks from CHIPDeviceController. */ @@ -934,9 +854,7 @@ void onReadCommissioningInfo( /** Notifies the listener of the error. */ void onError(Throwable error); - /** - * Notifies the Commissioner when the OpCSR for the Comissionee is generated. - */ + /** Notifies the Commissioner when the OpCSR for the Comissionee is generated. */ void onOpCSRGenerationComplete(byte[] csr); } } diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 7aa8b50e1755ff..12a85e03413eaf 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -3,24 +3,17 @@ /** * Only one of the following delegate callbacks should be implemented. * - *

- * If one of the following callbacks is implemented, {@link - * ChipDeviceController#continueCommissioning(long, boolean)} is expected to be - * called if + *

If one of the following callbacks is implemented, {@link + * ChipDeviceController#continueCommissioning(long, boolean)} is expected to be called if * commissioning should continue. * - *

- * If DeviceAttestationCompletionCallback is implemented, then it will always be - * called when + *

If DeviceAttestationCompletionCallback is implemented, then it will always be called when * device attestation completes. * - *

- * If DeviceAttestationFailureCallback is implemented, then it will be called - * when device - * attestation fails, and the client can decide to continue or stop the - * commissioning. + *

If DeviceAttestationFailureCallback is implemented, then it will be called when device + * attestation fails, and the client can decide to continue or stop the commissioning. * - * For example: + *

For example: * *

  * // Continue commissioning
@@ -29,24 +22,20 @@
  * // Stop commissioning
  * deviceController.continueCommissioning(devicePtr, true)
  * 
- * */ public interface DeviceAttestationDelegate { public interface DeviceAttestationCompletionCallback extends DeviceAttestationDelegate { /** - * The callback will be invoked when device attestation completed with device - * info for + * The callback will be invoked when device attestation completed with device info for * additional verification. * - *

- * This allows the callback to stop commissioning after examining the device - * info (DAC, PAI, + *

This allows the callback to stop commissioning after examining the device info (DAC, PAI, * CD). * - * @param devicePtr Handle of device being commissioned + * @param devicePtr Handle of device being commissioned * @param attestationInfo Attestation information for the device - * @param errorCode Error code on attestation failure. 0 if success. + * @param errorCode Error code on attestation failure. 0 if success. */ void onDeviceAttestationCompleted( long devicePtr, AttestationInfo attestationInfo, int errorCode); From e5972aedbf1c32957e08fcd3d632bee52542ee78 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 15 Dec 2022 11:47:19 +0800 Subject: [PATCH 27/44] Restyled by clang-format --- .../java/AndroidDeviceControllerWrapper.h | 15 +++------------ src/controller/java/CHIPDeviceController-JNI.cpp | 2 +- 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index f88742258fe9ae..ebad4bc36874c7 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -105,15 +105,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; CHIP_ERROR SyncDeleteKeyValue(const char * key) override; - chip::Controller::AutoCommissioner * GetAutoCommissioner() - { - return &mAutoCommissioner; - } + chip::Controller::AutoCommissioner * GetAutoCommissioner() { return &mAutoCommissioner; } - chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() - { - return &mPartialDACVerifier; - } + chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() { return &mPartialDACVerifier; } const chip::Controller::CommissioningParameters & GetCommissioningParameters() const { @@ -194,10 +188,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; } - DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() - { - return mDeviceAttestationDelegateBridge; - } + DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } void ClearDeviceAttestationDelegateBridge() { diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 816995c347935e..08375e9ed5f633 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -642,7 +642,7 @@ JNI_METHOD(void, continueCommissioning) : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { From f069618f460fb85224e2945487ee569ec42ffebb Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Wed, 4 Jan 2023 19:33:50 +0800 Subject: [PATCH 28/44] fix comments --- .../src/chip/devicecontroller/DeviceAttestationDelegate.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java index 12a85e03413eaf..f6de1f11333a32 100644 --- a/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/DeviceAttestationDelegate.java @@ -20,7 +20,7 @@ * deviceController.continueCommissioning(devicePtr, true) * * // Stop commissioning - * deviceController.continueCommissioning(devicePtr, true) + * deviceController.continueCommissioning(devicePtr, false) * */ public interface DeviceAttestationDelegate { From f4857573cfd803c591a1cd1eb584464020545828 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Wed, 4 Jan 2023 20:48:46 +0800 Subject: [PATCH 29/44] remove android attestation trust store --- .../java/AndroidDeviceControllerWrapper.cpp | 92 +----------- .../java/AndroidDeviceControllerWrapper.h | 28 ++-- .../java/AttestationTrustStoreBridge.cpp | 54 ------- .../java/AttestationTrustStoreBridge.h | 32 ----- src/controller/java/BUILD.gn | 2 - .../java/CHIPDeviceController-JNI.cpp | 19 +-- .../devicecontroller/ControllerParams.java | 135 +++++++++--------- 7 files changed, 94 insertions(+), 268 deletions(-) delete mode 100644 src/controller/java/AttestationTrustStoreBridge.cpp delete mode 100644 src/controller/java/AttestationTrustStoreBridge.h diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 031b63142bd360..99a800efd98a66 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -66,16 +66,6 @@ AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() delete mDeviceAttestationDelegateBridge; mDeviceAttestationDelegateBridge = nullptr; } - if (mDeviceAttestationVerifier != nullptr) - { - delete mDeviceAttestationVerifier; - mDeviceAttestationVerifier = nullptr; - } - if (mAttestationTrustStoreBridge != nullptr) - { - delete mAttestationTrustStoreBridge; - mAttestationTrustStoreBridge = nullptr; - } } void AndroidDeviceControllerWrapper::SetJavaObjectRef(JavaVM * vm, jobject obj) @@ -100,9 +90,8 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( AndroidOperationalCredentialsIssuerPtr opCredsIssuerPtr, #endif jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, - jbyteArray ipkEpochKey, jobject paaCertsArrayList, jobject cdCertsArrayList, uint16_t listenPort, uint16_t controllerVendorId, - uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, bool skipCommissioningComplete, - CHIP_ERROR * errInfoOnFailure) + jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, + bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure) { if (errInfoOnFailure == nullptr) { @@ -166,77 +155,9 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( #endif // Initialize device attestation verifier - const Credentials::AttestationTrustStore * trustStore; - CHIP_ERROR err = CHIP_NO_ERROR; - if (paaCertsArrayList) - { - jint listSize; - JniReferences::GetInstance().GetListSize(paaCertsArrayList, listSize); - std::vector> paaCerts; - for (jint i = 0; i < listSize; i++) - { - jobject paaCertObj = nullptr; - err = JniReferences::GetInstance().GetListItem(paaCertsArrayList, i, paaCertObj); - if (err != CHIP_NO_ERROR) - { - *errInfoOnFailure = err; - return nullptr; - } - JniByteArray paaCert(env, static_cast(paaCertObj)); - // Make a copy of the cert so that it does not loss of scope. - paaCerts.push_back(std::vector(paaCert.byteSpan().begin(), paaCert.byteSpan().end())); - } - wrapper->mAttestationTrustStoreBridge = new AttestationTrustStoreBridge(paaCerts); - if (wrapper->mAttestationTrustStoreBridge == nullptr) - { - ChipLogError(Controller, "Failed to create AttestationTrustStoreBridge"); - *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; - return nullptr; - } - trustStore = wrapper->mAttestationTrustStoreBridge; - } - else - { - trustStore = chip::Credentials::GetTestAttestationTrustStore(); - } - wrapper->mDeviceAttestationVerifier = new Credentials::DefaultDACVerifier(trustStore); - if (wrapper->mDeviceAttestationVerifier == nullptr) - { - ChipLogError(Controller, "Init failure while creating the device attestation verifier"); - *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; - return nullptr; - } - if (cdCertsArrayList) - { - auto cdTrustStore = wrapper->mDeviceAttestationVerifier->GetCertificationDeclarationTrustStore(); - if (cdTrustStore == nullptr) - { - ChipLogError(Controller, "Failed to get cd trust store"); - *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; - return nullptr; - } - jint listSize; - JniReferences::GetInstance().GetListSize(cdCertsArrayList, listSize); - for (uint8_t i = 0; i < listSize; i++) - { - jobject cdCertObj = nullptr; - err = JniReferences::GetInstance().GetListItem(cdCertsArrayList, i, cdCertObj); - if (err != CHIP_NO_ERROR) - { - *errInfoOnFailure = err; - return nullptr; - } - JniByteArray cdCert(env, static_cast(cdCertObj)); - std::vector cdCertCopy(cdCert.byteSpan().begin(), cdCert.byteSpan().end()); - chip::ByteSpan trustedKey = chip::ByteSpan(cdCertCopy.data(), cdCertCopy.size()); - err = cdTrustStore->AddTrustedKey(trustedKey); - if (err != CHIP_NO_ERROR) - { - *errInfoOnFailure = err; - return nullptr; - } - } - } + // TODO: Replace testingRootStore with a AttestationTrustStore that has the necessary official PAA roots available + const chip::Credentials::AttestationTrustStore * testingRootStore = chip::Credentials::GetTestAttestationTrustStore(); + SetDeviceAttestationVerifier(GetDefaultDACVerifier(testingRootStore)); chip::Controller::FactoryInitParams initParams; chip::Controller::SetupParams setupParams; @@ -255,7 +176,6 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( setupParams.operationalCredentialsDelegate = opCredsIssuer; setupParams.defaultCommissioner = &wrapper->mAutoCommissioner; initParams.fabricIndependentStorage = wrapperStorage; - setupParams.deviceAttestationVerifier = wrapper->mDeviceAttestationVerifier; wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); @@ -266,7 +186,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( params.SetSkipCommissioningComplete(skipCommissioningComplete); wrapper->UpdateCommissioningParameters(params); - err = wrapper->mGroupDataProvider.Init(); + CHIP_ERROR err = wrapper->mGroupDataProvider.Init(); if (err != CHIP_NO_ERROR) { *errInfoOnFailure = err; diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index ebad4bc36874c7..5a780914de38e5 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -40,7 +40,6 @@ #endif // JAVA_MATTER_CONTROLLER_TEST #include "AndroidOperationalCredentialsIssuer.h" -#include "AttestationTrustStoreBridge.h" #include "DeviceAttestationDelegateBridge.h" /** @@ -105,9 +104,15 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; CHIP_ERROR SyncDeleteKeyValue(const char * key) override; - chip::Controller::AutoCommissioner * GetAutoCommissioner() { return &mAutoCommissioner; } + chip::Controller::AutoCommissioner * GetAutoCommissioner() + { + return &mAutoCommissioner; + } - chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() { return &mPartialDACVerifier; } + chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() + { + return &mPartialDACVerifier; + } const chip::Controller::CommissioningParameters & GetCommissioningParameters() const { @@ -149,8 +154,6 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel * @param[in] intermediateCertificate an X.509 DER-encoded intermediate certificate for this node * @param[in] nodeOperationalCertificate an X.509 DER-encoded operational certificate for this node * @param[in] ipkEpochKey the IPK epoch key to use for this node - * @param[in] paaCertsArrayList - * @param[in] cdCertsArrayList * @param[in] listenPort the UDP port to listen on * @param[in] controllerVendorId the vendor ID identifying the controller * @param[in] failsafeTimerSeconds the failsafe timer in seconds @@ -170,9 +173,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel AndroidOperationalCredentialsIssuerPtr opCredsIssuer, #endif jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, - jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, jobject paaCertsArrayList, jobject cdCertsArrayList, - uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, - bool attemptNetworkScanThread, bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure); + jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, + uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, + bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure); #ifdef JAVA_MATTER_CONTROLLER_TEST chip::Controller::ExampleOperationalCredentialsIssuer * GetAndroidOperationalCredentialsIssuer() @@ -188,7 +191,10 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; } - DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } + DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() + { + return mDeviceAttestationDelegateBridge; + } void ClearDeviceAttestationDelegateBridge() { @@ -235,9 +241,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Credentials::PartialDACVerifier mPartialDACVerifier; - DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; - AttestationTrustStoreBridge * mAttestationTrustStoreBridge = nullptr; - chip::Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; + DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; AndroidDeviceControllerWrapper(ChipDeviceControllerPtr controller, #ifdef JAVA_MATTER_CONTROLLER_TEST diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp deleted file mode 100644 index bb7e81b748b71c..00000000000000 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/** - * - * 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. - */ - -#include "AttestationTrustStoreBridge.h" -#include - -AttestationTrustStoreBridge::~AttestationTrustStoreBridge() -{ - if (!mPaaCerts.empty()) - { - for (auto paaCert : mPaaCerts) - { - paaCert.clear(); - paaCert.shrink_to_fit(); - } - mPaaCerts.clear(); - mPaaCerts.shrink_to_fit(); - } -} - -CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, - chip::MutableByteSpan & outPaaDerBuffer) const -{ - VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); - - for (auto paaCert : mPaaCerts) - { - chip::ByteSpan candidate = chip::ByteSpan(paaCert.data(), paaCert.size()); - uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; - chip::MutableByteSpan candidateSkidSpan{ skidBuf }; - VerifyOrReturnError(CHIP_NO_ERROR == chip::Crypto::ExtractSKIDFromX509Cert(candidate, candidateSkidSpan), - CHIP_ERROR_INTERNAL); - if (skid.data_equal(candidateSkidSpan)) - { - // Found a match - return CopySpanToMutableSpan(candidate, outPaaDerBuffer); - } - } - return CHIP_ERROR_CA_CERT_NOT_FOUND; -} diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h deleted file mode 100644 index b5eb8ab5bf97ef..00000000000000 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * - * 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. - */ - -#include -#include - -class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustStore -{ -public: - AttestationTrustStoreBridge(std::vector> paaCerts) : mPaaCerts(paaCerts) {} - ~AttestationTrustStoreBridge(); - - CHIP_ERROR GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, - chip::MutableByteSpan & outPaaDerBuffer) const override; - -private: - std::vector> mPaaCerts; -}; diff --git a/src/controller/java/BUILD.gn b/src/controller/java/BUILD.gn index d7f722c68c63f9..a8064c265e394a 100644 --- a/src/controller/java/BUILD.gn +++ b/src/controller/java/BUILD.gn @@ -36,8 +36,6 @@ shared_library("jni") { "AndroidDeviceControllerWrapper.h", "AndroidOperationalCredentialsIssuer.cpp", "AndroidOperationalCredentialsIssuer.h", - "AttestationTrustStoreBridge.cpp", - "AttestationTrustStoreBridge.h", "BaseCHIPCluster-JNI.cpp", "CHIPAttributeTLVValueDecoder.h", "CHIPDefaultCallbacks.cpp", diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 08375e9ed5f633..2a487541060ddf 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -333,16 +333,6 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAdminSubject", "()J", &getAdminSubject); SuccessOrExit(err); - jmethodID getPaaCerts; - err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getPaaCerts", "()Ljava/util/ArrayList;", - &getPaaCerts); - SuccessOrExit(err); - - jmethodID getCdCerts; - err = - chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getCdCerts", "()Ljava/util/ArrayList;", &getCdCerts); - SuccessOrExit(err); - { uint64_t fabricId = env->CallLongMethod(controllerParams, getFabricId); uint16_t listenPort = env->CallIntMethod(controllerParams, getUdpListenPort); @@ -352,8 +342,6 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); - jobject paaCerts = env->CallObjectMethod(controllerParams, getPaaCerts); - jobject cdCerts = env->CallObjectMethod(controllerParams, getCdCerts); uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); uint16_t caseFailsafeTimerSeconds = env->CallIntMethod(controllerParams, getCASEFailsafeTimerSeconds); bool attemptNetworkScanWiFi = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanWiFi); @@ -371,9 +359,8 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr wrapper = AndroidDeviceControllerWrapper::AllocateNew( sJVM, self, kLocalDeviceId, fabricId, chip::kUndefinedCATs, &DeviceLayer::SystemLayer(), DeviceLayer::TCPEndPointManager(), DeviceLayer::UDPEndPointManager(), std::move(opCredsIssuer), keypairDelegate, - rootCertificate, intermediateCertificate, operationalCertificate, ipk, paaCerts, cdCerts, listenPort, - controllerVendorId, failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, skipCommissioningComplete, - &err); + rootCertificate, intermediateCertificate, operationalCertificate, ipk, listenPort, controllerVendorId, + failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, skipCommissioningComplete, &err); SuccessOrExit(err); if (caseFailsafeTimerSeconds > 0) @@ -642,7 +629,7 @@ JNI_METHOD(void, continueCommissioning) : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index dbebe3e63546bb..148247341e1525 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -3,7 +3,10 @@ import java.util.ArrayList; import javax.annotation.Nullable; -/** Parameters representing initialization arguments for {@link ChipDeviceController}. */ +/** + * Parameters representing initialization arguments for + * {@link ChipDeviceController}. + */ public final class ControllerParams { private final long fabricId; @@ -14,18 +17,23 @@ public final class ControllerParams { private final boolean attemptNetworkScanWiFi; private final boolean attemptNetworkScanThread; private final boolean skipCommissioningComplete; - @Nullable private final KeypairDelegate keypairDelegate; - @Nullable private final byte[] rootCertificate; - @Nullable private final byte[] intermediateCertificate; - @Nullable private final byte[] operationalCertificate; - @Nullable private final byte[] ipk; - @Nullable private final ArrayList paaCerts; - @Nullable private final ArrayList cdCerts; + @Nullable + private final KeypairDelegate keypairDelegate; + @Nullable + private final byte[] rootCertificate; + @Nullable + private final byte[] intermediateCertificate; + @Nullable + private final byte[] operationalCertificate; + @Nullable + private final byte[] ipk; private final long adminSubject; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; - /** @param udpListenPort the UDP listening port, or 0 to pick any available port. */ + /** + * @param udpListenPort the UDP listening port, or 0 to pick any available port. + */ private ControllerParams(Builder builder) { this.fabricId = builder.fabricId; this.udpListenPort = builder.udpListenPort; @@ -40,8 +48,6 @@ private ControllerParams(Builder builder) { this.intermediateCertificate = builder.intermediateCertificate; this.operationalCertificate = builder.operationalCertificate; this.ipk = builder.ipk; - this.paaCerts = builder.paaCerts; - this.cdCerts = builder.cdCerts; this.adminSubject = builder.adminSubject; } @@ -98,14 +104,6 @@ public byte[] getIpk() { return ipk; } - public ArrayList getPaaCerts() { - return paaCerts; - } - - public ArrayList getCdCerts() { - return cdCerts; - } - public long getAdminSubject() { return adminSubject; } @@ -116,7 +114,8 @@ public static Builder newBuilder() { } /** - * Returns parameters which uses the provided {@code operationalKeyConfig} as its operating + * Returns parameters which uses the provided {@code operationalKeyConfig} as + * its operating * credentials. You must set a vendor ID, 0xFFF4 is a test vendor ID * ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() */ @@ -139,16 +138,20 @@ public static class Builder { private boolean attemptNetworkScanWiFi = false; private boolean attemptNetworkScanThread = false; private boolean skipCommissioningComplete = false; - @Nullable private KeypairDelegate keypairDelegate = null; - @Nullable private byte[] rootCertificate = null; - @Nullable private byte[] intermediateCertificate = null; - @Nullable private byte[] operationalCertificate = null; - @Nullable private byte[] ipk = null; - @Nullable private ArrayList paaCerts; - @Nullable private ArrayList cdCerts; + @Nullable + private KeypairDelegate keypairDelegate = null; + @Nullable + private byte[] rootCertificate = null; + @Nullable + private byte[] intermediateCertificate = null; + @Nullable + private byte[] operationalCertificate = null; + @Nullable + private byte[] ipk = null; private long adminSubject = 0; - private Builder() {} + private Builder() { + } public Builder setFabricId(long fabricId) { if (fabricId < 1) { @@ -172,11 +175,15 @@ public Builder setControllerVendorId(int controllerVendorId) { } /** - * Sets the FailsafeTimer duration passed to ChipDeviceCommissioner's CommissioningParameters. - * Increasing this value from its default will allow more time for network scans, cloud op cert + * Sets the FailsafeTimer duration passed to ChipDeviceCommissioner's + * CommissioningParameters. + * Increasing this value from its default will allow more time for network + * scans, cloud op cert * signing calls, and user interaction. * - *

Note: It is also possible for internal logic (within Autocommissioner, etc) to re-call + *

+ * Note: It is also possible for internal logic (within Autocommissioner, etc) + * to re-call * ArmFailSafe to account for network config delays. * * @param failsafeTimerSeconds @@ -191,11 +198,15 @@ public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { } /** - * Sets the CASEFailsafeExpirySeconds duration passed to ChipDeviceCommissioner's - * CommissioningParameters. After PASE session has finished, the failsafe is rearmed with the + * Sets the CASEFailsafeExpirySeconds duration passed to + * ChipDeviceCommissioner's + * CommissioningParameters. After PASE session has finished, the failsafe is + * rearmed with the * specified expiry before continuing commissioning. * - *

Note: If CASEFailsafeExpirySeconds is not set (or is 0), the failsafe will not be rearmed. + *

+ * Note: If CASEFailsafeExpirySeconds is not set (or is 0), the failsafe will + * not be rearmed. * * @param caseFailsafeExpirySeconds * @return @@ -212,10 +223,14 @@ public Builder setCASEFailsafeTimerSeconds(int failsafeTimerSeconds) { * Enable/disable wifi network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters passed to + *

+ * Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters + * passed to * the CommissioningDelegate. * - *

When a WiFi scan is attempted, the result will be propagated to the ScanNetworksListener + *

+ * When a WiFi scan is attempted, the result will be propagated to the + * ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -230,10 +245,14 @@ public Builder setAttemptNetworkScanWiFi(boolean attemptNetworkScanWiFi) { * Enable/disable Thread network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

Specifically, this sets AttemptThreadNetworkScan in the CommissioningParameters passed to + *

+ * Specifically, this sets AttemptThreadNetworkScan in the + * CommissioningParameters passed to * the CommissioningDelegate. * - *

When a Thread scan is attempted, the result will be propagated to the ScanNetworksListener + *

+ * When a Thread scan is attempted, the result will be propagated to the + * ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -245,13 +264,18 @@ public Builder setAttemptNetworkScanThread(boolean attemptNetworkScanThread) { } /** - * Disable the CASE phase of commissioning when the CommissioningComplete command is sent by + * Disable the CASE phase of commissioning when the CommissioningComplete + * command is sent by * this ChipDeviceCommissioner. * - *

Specifically, this sets SkipCommissioningComplete in the CommissioningParameters passed to + *

+ * Specifically, this sets SkipCommissioningComplete in the + * CommissioningParameters passed to * the CommissioningDelegate. * - *

A controller will set this to true when the CASE phase of commissioning is done by a + *

+ * A controller will set this to true when the CASE phase of commissioning is + * done by a * separate process, for example, by a Hub on the network. * * @param skipCommissioningComplete @@ -288,31 +312,10 @@ public Builder setIpk(byte[] ipk) { } /** - * The Product Attestation Authority certificates that are trusted to sign device attestation - * information. - * - * @param paaCerts The Product Attestation Authority certificates containing the X.509 DER - * certificate. - */ - public Builder setPaaCerts(ArrayList paaCerts) { - this.paaCerts = paaCerts; - return this; - } - - /** - * The Certificate Declaration certificates that are trusted to sign device attestation - * information. - * - * @param cdCerts The Certificate Declaration certificates containing the X.509 DER certificate. - */ - public Builder setCdCerts(ArrayList cdCerts) { - this.cdCerts = cdCerts; - return this; - } - - /** - * Sets the AdminSubject value passed to ChipDeviceCommissioner's CommissioningParameters. This - * value is passed in the AddNoc command sent to the commissionee and represents the subject of + * Sets the AdminSubject value passed to ChipDeviceCommissioner's + * CommissioningParameters. This + * value is passed in the AddNoc command sent to the commissionee and represents + * the subject of * the default ACL created by that call. * * @param adminSubject From 2b094c80e872824a1f781d1606967a6944eb24f6 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Wed, 4 Jan 2023 21:00:33 +0800 Subject: [PATCH 30/44] restyle --- .../java/AndroidDeviceControllerWrapper.h | 15 +-- .../java/CHIPDeviceController-JNI.cpp | 2 +- .../devicecontroller/ControllerParams.java | 99 ++++++------------- 3 files changed, 33 insertions(+), 83 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 5a780914de38e5..3267f7fc4519b5 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -104,15 +104,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel CHIP_ERROR SyncGetKeyValue(const char * key, void * buffer, uint16_t & size) override; CHIP_ERROR SyncDeleteKeyValue(const char * key) override; - chip::Controller::AutoCommissioner * GetAutoCommissioner() - { - return &mAutoCommissioner; - } + chip::Controller::AutoCommissioner * GetAutoCommissioner() { return &mAutoCommissioner; } - chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() - { - return &mPartialDACVerifier; - } + chip::Credentials::PartialDACVerifier * GetPartialDACVerifier() { return &mPartialDACVerifier; } const chip::Controller::CommissioningParameters & GetCommissioningParameters() const { @@ -191,10 +185,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel mDeviceAttestationDelegateBridge = deviceAttestationDelegateBridge; } - DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() - { - return mDeviceAttestationDelegateBridge; - } + DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } void ClearDeviceAttestationDelegateBridge() { diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 2a487541060ddf..fb7aa8aedf77e6 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -629,7 +629,7 @@ JNI_METHOD(void, continueCommissioning) : chip::Credentials::AttestationVerificationResult::kSuccess; chip::DeviceProxy * deviceProxy = reinterpret_cast(devicePtr); err = wrapper->Controller()->ContinueCommissioningAfterDeviceAttestation( - deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); + deviceProxy, ignoreAttestationFailure ? chip::Credentials::AttestationVerificationResult::kSuccess : lastAttestationResult); if (err != CHIP_NO_ERROR) { diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index 148247341e1525..5c13d853f84c59 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -1,12 +1,8 @@ package chip.devicecontroller; -import java.util.ArrayList; import javax.annotation.Nullable; -/** - * Parameters representing initialization arguments for - * {@link ChipDeviceController}. - */ +/** Parameters representing initialization arguments for {@link ChipDeviceController}. */ public final class ControllerParams { private final long fabricId; @@ -17,23 +13,16 @@ public final class ControllerParams { private final boolean attemptNetworkScanWiFi; private final boolean attemptNetworkScanThread; private final boolean skipCommissioningComplete; - @Nullable - private final KeypairDelegate keypairDelegate; - @Nullable - private final byte[] rootCertificate; - @Nullable - private final byte[] intermediateCertificate; - @Nullable - private final byte[] operationalCertificate; - @Nullable - private final byte[] ipk; + @Nullable private final KeypairDelegate keypairDelegate; + @Nullable private final byte[] rootCertificate; + @Nullable private final byte[] intermediateCertificate; + @Nullable private final byte[] operationalCertificate; + @Nullable private final byte[] ipk; private final long adminSubject; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; - /** - * @param udpListenPort the UDP listening port, or 0 to pick any available port. - */ + /** @param udpListenPort the UDP listening port, or 0 to pick any available port. */ private ControllerParams(Builder builder) { this.fabricId = builder.fabricId; this.udpListenPort = builder.udpListenPort; @@ -114,8 +103,7 @@ public static Builder newBuilder() { } /** - * Returns parameters which uses the provided {@code operationalKeyConfig} as - * its operating + * Returns parameters which uses the provided {@code operationalKeyConfig} as its operating * credentials. You must set a vendor ID, 0xFFF4 is a test vendor ID * ControllerParams.newBuilder().setControllerVendorId(0xFFF4).build() */ @@ -138,20 +126,14 @@ public static class Builder { private boolean attemptNetworkScanWiFi = false; private boolean attemptNetworkScanThread = false; private boolean skipCommissioningComplete = false; - @Nullable - private KeypairDelegate keypairDelegate = null; - @Nullable - private byte[] rootCertificate = null; - @Nullable - private byte[] intermediateCertificate = null; - @Nullable - private byte[] operationalCertificate = null; - @Nullable - private byte[] ipk = null; + @Nullable private KeypairDelegate keypairDelegate = null; + @Nullable private byte[] rootCertificate = null; + @Nullable private byte[] intermediateCertificate = null; + @Nullable private byte[] operationalCertificate = null; + @Nullable private byte[] ipk = null; private long adminSubject = 0; - private Builder() { - } + private Builder() {} public Builder setFabricId(long fabricId) { if (fabricId < 1) { @@ -175,15 +157,11 @@ public Builder setControllerVendorId(int controllerVendorId) { } /** - * Sets the FailsafeTimer duration passed to ChipDeviceCommissioner's - * CommissioningParameters. - * Increasing this value from its default will allow more time for network - * scans, cloud op cert + * Sets the FailsafeTimer duration passed to ChipDeviceCommissioner's CommissioningParameters. + * Increasing this value from its default will allow more time for network scans, cloud op cert * signing calls, and user interaction. * - *

- * Note: It is also possible for internal logic (within Autocommissioner, etc) - * to re-call + *

Note: It is also possible for internal logic (within Autocommissioner, etc) to re-call * ArmFailSafe to account for network config delays. * * @param failsafeTimerSeconds @@ -198,15 +176,11 @@ public Builder setFailsafeTimerSeconds(int failsafeTimerSeconds) { } /** - * Sets the CASEFailsafeExpirySeconds duration passed to - * ChipDeviceCommissioner's - * CommissioningParameters. After PASE session has finished, the failsafe is - * rearmed with the + * Sets the CASEFailsafeExpirySeconds duration passed to ChipDeviceCommissioner's + * CommissioningParameters. After PASE session has finished, the failsafe is rearmed with the * specified expiry before continuing commissioning. * - *

- * Note: If CASEFailsafeExpirySeconds is not set (or is 0), the failsafe will - * not be rearmed. + *

Note: If CASEFailsafeExpirySeconds is not set (or is 0), the failsafe will not be rearmed. * * @param caseFailsafeExpirySeconds * @return @@ -223,14 +197,10 @@ public Builder setCASEFailsafeTimerSeconds(int failsafeTimerSeconds) { * Enable/disable wifi network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

- * Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters - * passed to + *

Specifically, this sets AttemptWiFiNetworkScan in the CommissioningParameters passed to * the CommissioningDelegate. * - *

- * When a WiFi scan is attempted, the result will be propagated to the - * ScanNetworksListener + *

When a WiFi scan is attempted, the result will be propagated to the ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -245,14 +215,10 @@ public Builder setAttemptNetworkScanWiFi(boolean attemptNetworkScanWiFi) { * Enable/disable Thread network scan during commissioning in the the default * CommissioningDelegate used by the ChipDeviceCommissioner. * - *

- * Specifically, this sets AttemptThreadNetworkScan in the - * CommissioningParameters passed to + *

Specifically, this sets AttemptThreadNetworkScan in the CommissioningParameters passed to * the CommissioningDelegate. * - *

- * When a Thread scan is attempted, the result will be propagated to the - * ScanNetworksListener + *

When a Thread scan is attempted, the result will be propagated to the ScanNetworksListener * assigned to the ChipDeviceController. * * @param attemptNetworkScanWiFi @@ -264,18 +230,13 @@ public Builder setAttemptNetworkScanThread(boolean attemptNetworkScanThread) { } /** - * Disable the CASE phase of commissioning when the CommissioningComplete - * command is sent by + * Disable the CASE phase of commissioning when the CommissioningComplete command is sent by * this ChipDeviceCommissioner. * - *

- * Specifically, this sets SkipCommissioningComplete in the - * CommissioningParameters passed to + *

Specifically, this sets SkipCommissioningComplete in the CommissioningParameters passed to * the CommissioningDelegate. * - *

- * A controller will set this to true when the CASE phase of commissioning is - * done by a + *

A controller will set this to true when the CASE phase of commissioning is done by a * separate process, for example, by a Hub on the network. * * @param skipCommissioningComplete @@ -312,10 +273,8 @@ public Builder setIpk(byte[] ipk) { } /** - * Sets the AdminSubject value passed to ChipDeviceCommissioner's - * CommissioningParameters. This - * value is passed in the AddNoc command sent to the commissionee and represents - * the subject of + * Sets the AdminSubject value passed to ChipDeviceCommissioner's CommissioningParameters. This + * value is passed in the AddNoc command sent to the commissionee and represents the subject of * the default ACL created by that call. * * @param adminSubject From a870918425f77a0df854cb0964a5e8074d48561a Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 5 Jan 2023 19:36:06 +0800 Subject: [PATCH 31/44] [android] support attestation trust store delegate --- .../java/AndroidDeviceControllerWrapper.cpp | 35 +++++++- .../java/AndroidDeviceControllerWrapper.h | 7 +- .../java/AttestationTrustStoreBridge.cpp | 85 +++++++++++++++++++ .../java/AttestationTrustStoreBridge.h | 35 ++++++++ src/controller/java/BUILD.gn | 3 + .../java/CHIPDeviceController-JNI.cpp | 72 ++++++++++++---- .../AttestationTrustStoreDelegate.java | 25 ++++++ .../devicecontroller/ControllerParams.java | 13 +++ 8 files changed, 254 insertions(+), 21 deletions(-) create mode 100644 src/controller/java/AttestationTrustStoreBridge.cpp create mode 100644 src/controller/java/AttestationTrustStoreBridge.h create mode 100644 src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 99a800efd98a66..1acb138d3c41fb 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -66,6 +66,16 @@ AndroidDeviceControllerWrapper::~AndroidDeviceControllerWrapper() delete mDeviceAttestationDelegateBridge; mDeviceAttestationDelegateBridge = nullptr; } + if (mDeviceAttestationVerifier != nullptr) + { + delete mDeviceAttestationVerifier; + mDeviceAttestationVerifier = nullptr; + } + if (mAttestationTrustStoreBridge != nullptr) + { + delete mAttestationTrustStoreBridge; + mAttestationTrustStoreBridge = nullptr; + } } void AndroidDeviceControllerWrapper::SetJavaObjectRef(JavaVM * vm, jobject obj) @@ -91,7 +101,8 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( #endif jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, - bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure) + bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, bool skipCommissioningComplete, + jobject attestationTrustStoreDelegate, CHIP_ERROR * errInfoOnFailure) { if (errInfoOnFailure == nullptr) { @@ -155,9 +166,24 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( #endif // Initialize device attestation verifier - // TODO: Replace testingRootStore with a AttestationTrustStore that has the necessary official PAA roots available - const chip::Credentials::AttestationTrustStore * testingRootStore = chip::Credentials::GetTestAttestationTrustStore(); - SetDeviceAttestationVerifier(GetDefaultDACVerifier(testingRootStore)); + const Credentials::AttestationTrustStore * trustStore; + if (attestationTrustStoreDelegate != nullptr) + { + wrapper->mAttestationTrustStoreBridge = new AttestationTrustStoreBridge(attestationTrustStoreDelegate); + if (wrapper->mAttestationTrustStoreBridge == nullptr) + { + ChipLogError(Controller, "Failed to create AttestationTrustStoreBridge"); + *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; + return nullptr; + } + trustStore = wrapper->mAttestationTrustStoreBridge; + } + else + { + trustStore = chip::Credentials::GetTestAttestationTrustStore(); + } + + wrapper->mDeviceAttestationVerifier = new Credentials::DefaultDACVerifier(trustStore); chip::Controller::FactoryInitParams initParams; chip::Controller::SetupParams setupParams; @@ -176,6 +202,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( setupParams.operationalCredentialsDelegate = opCredsIssuer; setupParams.defaultCommissioner = &wrapper->mAutoCommissioner; initParams.fabricIndependentStorage = wrapperStorage; + setupParams.deviceAttestationVerifier = wrapper->mDeviceAttestationVerifier; wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 3267f7fc4519b5..74d71fa3032e7f 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -40,6 +40,7 @@ #endif // JAVA_MATTER_CONTROLLER_TEST #include "AndroidOperationalCredentialsIssuer.h" +#include "AttestationTrustStoreBridge.h" #include "DeviceAttestationDelegateBridge.h" /** @@ -169,7 +170,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, - bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure); + bool skipCommissioningComplete, jobject attestationTrustStoreDelegate, CHIP_ERROR * errInfoOnFailure); #ifdef JAVA_MATTER_CONTROLLER_TEST chip::Controller::ExampleOperationalCredentialsIssuer * GetAndroidOperationalCredentialsIssuer() @@ -232,7 +233,9 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Credentials::PartialDACVerifier mPartialDACVerifier; - DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; + DeviceAttestationDelegateBridge * mDeviceAttestationDelegateBridge = nullptr; + AttestationTrustStoreBridge * mAttestationTrustStoreBridge = nullptr; + chip::Credentials::DeviceAttestationVerifier * mDeviceAttestationVerifier = nullptr; AndroidDeviceControllerWrapper(ChipDeviceControllerPtr controller, #ifdef JAVA_MATTER_CONTROLLER_TEST diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp new file mode 100644 index 00000000000000..e924c189d17a13 --- /dev/null +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -0,0 +1,85 @@ +/** + * + * 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. + */ + +#include "AttestationTrustStoreBridge.h" +#include +#include +#include +#include +#include + +using namespace chip; + +AttestationTrustStoreBridge::~AttestationTrustStoreBridge() +{ + if (mAttestationTrustStoreDelegate != nullptr) + { + mAttestationTrustStoreDelegate = nullptr; + } +} + +CHIP_ERROR GetPaaCertFromJavaDelegate(jobject attestationTrustStoreDelegate, const chip::ByteSpan & skid, jbyteArray & javaPaaCert) +{ + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jclass attestationTrustStoreDelegateCls = nullptr; + jbyteArray javaSkid = nullptr; + jmethodID getProductAttestationAuthorityCertMethod = nullptr; + + JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/AttestationTrustStoreDelegate", + attestationTrustStoreDelegateCls); + VerifyOrReturnError(attestationTrustStoreDelegateCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); + + JniReferences::GetInstance().FindMethod(env, attestationTrustStoreDelegate, "getProductAttestationAuthorityCert", "(B[)B[", + &getProductAttestationAuthorityCertMethod); + VerifyOrReturnError(getProductAttestationAuthorityCertMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); + + JniReferences::GetInstance().N2J_ByteArray(env, skid.data(), static_cast(skid.size()), javaSkid); + VerifyOrReturnError(javaSkid != nullptr, CHIP_ERROR_NO_MEMORY); + + javaPaaCert = + (jbyteArray) env->CallObjectMethod(attestationTrustStoreDelegate, getProductAttestationAuthorityCertMethod, javaSkid); + + return CHIP_NO_ERROR; +} + +CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, + chip::MutableByteSpan & outPaaDerBuffer) const +{ + + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + jbyteArray javaPaaCert = nullptr; + + VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); + + CHIP_ERROR err = GetPaaCertFromJavaDelegate(mAttestationTrustStoreDelegate, skid, javaPaaCert); + VerifyOrReturnError(err != CHIP_NO_ERROR, err); + if (javaPaaCert != nullptr) + { + JniByteArray paaCertBytes(env, javaPaaCert); + uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; + chip::MutableByteSpan candidateSkidSpan{ skidBuf }; + VerifyOrReturnError(CHIP_NO_ERROR == chip::Crypto::ExtractSKIDFromX509Cert(paaCertBytes.byteSpan(), candidateSkidSpan), + CHIP_ERROR_INTERNAL); + // Make sure the skid of the paa cert is match. + if (skid.data_equal(candidateSkidSpan)) + { + // Found a match + return CopySpanToMutableSpan(paaCertBytes.byteSpan(), outPaaDerBuffer); + } + } + return CHIP_ERROR_CA_CERT_NOT_FOUND; +} \ No newline at end of file diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h new file mode 100644 index 00000000000000..da495c6cd0deb7 --- /dev/null +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -0,0 +1,35 @@ +/** + * + * 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. + */ + +#include +#include +#include + +class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustStore +{ +public: + AttestationTrustStoreBridge(jobject attestationTrustStoreDelegate) : + mAttestationTrustStoreDelegate(attestationTrustStoreDelegate) + {} + ~AttestationTrustStoreBridge(); + + CHIP_ERROR GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, + chip::MutableByteSpan & outPaaDerBuffer) const override; + +private: + jobject mAttestationTrustStoreDelegate = nullptr; +}; \ No newline at end of file diff --git a/src/controller/java/BUILD.gn b/src/controller/java/BUILD.gn index a8064c265e394a..ecfe4ce2a594bc 100644 --- a/src/controller/java/BUILD.gn +++ b/src/controller/java/BUILD.gn @@ -36,6 +36,8 @@ shared_library("jni") { "AndroidDeviceControllerWrapper.h", "AndroidOperationalCredentialsIssuer.cpp", "AndroidOperationalCredentialsIssuer.h", + "AttestationTrustStoreBridge.cpp", + "AttestationTrustStoreBridge.h", "BaseCHIPCluster-JNI.cpp", "CHIPAttributeTLVValueDecoder.h", "CHIPDefaultCallbacks.cpp", @@ -102,6 +104,7 @@ android_library("java") { "src/chip/clusterinfo/DelegatedClusterCallback.java", "src/chip/clusterinfo/InteractionInfo.java", "src/chip/devicecontroller/AttestationInfo.java", + "src/chip/devicecontroller/AttestationTrustStoreDelegate.java", "src/chip/devicecontroller/CSRInfo.java", "src/chip/devicecontroller/ChipClusterException.java", "src/chip/devicecontroller/ChipCommandType.java", diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index fb7aa8aedf77e6..3e30a1377fc3ef 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -333,21 +333,28 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAdminSubject", "()J", &getAdminSubject); SuccessOrExit(err); + jmethodID getAttestationTrustStoreDelegate; + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "attestationTrustStoreDelegate", + "()Lchip/devicecontroller/AttestationTrustStoreDelegate;", + &getAttestationTrustStoreDelegate); + SuccessOrExit(err); + { - uint64_t fabricId = env->CallLongMethod(controllerParams, getFabricId); - uint16_t listenPort = env->CallIntMethod(controllerParams, getUdpListenPort); - uint16_t controllerVendorId = env->CallIntMethod(controllerParams, getControllerVendorId); - jobject keypairDelegate = env->CallObjectMethod(controllerParams, getKeypairDelegate); - jbyteArray rootCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getRootCertificate); - jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); - jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); - jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); - uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); - uint16_t caseFailsafeTimerSeconds = env->CallIntMethod(controllerParams, getCASEFailsafeTimerSeconds); - bool attemptNetworkScanWiFi = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanWiFi); - bool attemptNetworkScanThread = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanThread); - bool skipCommissioningComplete = env->CallBooleanMethod(controllerParams, getSkipCommissioningComplete); - uint64_t adminSubject = env->CallLongMethod(controllerParams, getAdminSubject); + uint64_t fabricId = env->CallLongMethod(controllerParams, getFabricId); + uint16_t listenPort = env->CallIntMethod(controllerParams, getUdpListenPort); + uint16_t controllerVendorId = env->CallIntMethod(controllerParams, getControllerVendorId); + jobject keypairDelegate = env->CallObjectMethod(controllerParams, getKeypairDelegate); + jbyteArray rootCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getRootCertificate); + jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); + jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); + jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); + uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); + uint16_t caseFailsafeTimerSeconds = env->CallIntMethod(controllerParams, getCASEFailsafeTimerSeconds); + bool attemptNetworkScanWiFi = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanWiFi); + bool attemptNetworkScanThread = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanThread); + bool skipCommissioningComplete = env->CallBooleanMethod(controllerParams, getSkipCommissioningComplete); + uint64_t adminSubject = env->CallLongMethod(controllerParams, getAdminSubject); + jobject attestationTrustStoreDelegate = env->CallObjectMethod(controllerParams, getAttestationTrustStoreDelegate); #ifdef JAVA_MATTER_CONTROLLER_TEST std::unique_ptr opCredsIssuer( @@ -360,7 +367,8 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr sJVM, self, kLocalDeviceId, fabricId, chip::kUndefinedCATs, &DeviceLayer::SystemLayer(), DeviceLayer::TCPEndPointManager(), DeviceLayer::UDPEndPointManager(), std::move(opCredsIssuer), keypairDelegate, rootCertificate, intermediateCertificate, operationalCertificate, ipk, listenPort, controllerVendorId, - failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, skipCommissioningComplete, &err); + failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, skipCommissioningComplete, + attestationTrustStoreDelegate, &err); SuccessOrExit(err); if (caseFailsafeTimerSeconds > 0) @@ -732,6 +740,40 @@ JNI_METHOD(jbyteArray, convertX509CertToMatterCert) return outJbytes; } +JNI_METHOD(jbyteArray, extractSKIDFromX509Cert) +(JNIEnv * env, jobject self, jbyteArray x509Cert) +{ + chip::DeviceLayer::StackLock lock; + + uint32_t allocatedCertLength = chip::Credentials::kMaxCHIPCertLength; + chip::Platform::ScopedMemoryBuffer outBuf; + jbyteArray outJbytes = nullptr; + JniByteArray x509CertBytes(env, x509Cert); + + CHIP_ERROR err = CHIP_NO_ERROR; + VerifyOrExit(outBuf.Alloc(allocatedCertLength), err = CHIP_ERROR_NO_MEMORY); + { + MutableByteSpan outBytes(outBuf.Get(), allocatedCertLength); + + err = chip::Crypto::ExtractSKIDFromX509Cert(x509CertBytes.byteSpan(), outBytes); + SuccessOrExit(err); + + VerifyOrExit(chip::CanCastTo(outBytes.size()), err = CHIP_ERROR_INTERNAL); + + err = JniReferences::GetInstance().N2J_ByteArray(env, outBytes.data(), static_cast(outBytes.size()), outJbytes); + SuccessOrExit(err); + } + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to extract skid frome X509 cert. Err = %" CHIP_ERROR_FORMAT, err.Format()); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } + + return outJbytes; +} + JNI_METHOD(void, unpairDevice)(JNIEnv * env, jobject self, jlong handle, jlong deviceId) { chip::DeviceLayer::StackLock lock; diff --git a/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java b/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java new file mode 100644 index 00000000000000..87704fad7ad217 --- /dev/null +++ b/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java @@ -0,0 +1,25 @@ +package chip.devicecontroller; + +/** + * Delegate for attestation trust store for device attestation verifiers. + * + * API is synchronous. + */ +public interface AttestationTrustStoreDelegate { + /** + * Look-up a product attestation authority (PAA) cert by subject key + * identifier (SKID). + * + * The implementations of this interface must have access to a set of PAAs to + * trust. + * + * Interface is synchronous, and therefore this should not be used unless to + * expose a PAA store that is both fully local and quick to access. + * + * @param skid Buffer containing the subject key identifier (SKID) of the PAA to + * look-up + * @return If found, the result should return paa cert in x.509 format, if not + * found, return null. + */ + byte[] getProductAttestationAuthorityCert(byte[] skid); +} diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index 5c13d853f84c59..7819f6bff36344 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -19,6 +19,7 @@ public final class ControllerParams { @Nullable private final byte[] operationalCertificate; @Nullable private final byte[] ipk; private final long adminSubject; + @Nullable private final AttestationTrustStoreDelegate attestationTrustStoreDelegate; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; @@ -38,6 +39,7 @@ private ControllerParams(Builder builder) { this.operationalCertificate = builder.operationalCertificate; this.ipk = builder.ipk; this.adminSubject = builder.adminSubject; + this.attestationTrustStoreDelegate = builder.attestationTrustStoreDelegate; } public long getFabricId() { @@ -97,6 +99,10 @@ public long getAdminSubject() { return adminSubject; } + public AttestationTrustStoreDelegate getAttestationTrustStoreDelegate() { + return attestationTrustStoreDelegate; + } + /** Returns parameters with ephemerally generated operational credentials */ public static Builder newBuilder() { return new Builder(); @@ -132,6 +138,7 @@ public static class Builder { @Nullable private byte[] operationalCertificate = null; @Nullable private byte[] ipk = null; private long adminSubject = 0; + @Nullable private AttestationTrustStoreDelegate attestationTrustStoreDelegate; private Builder() {} @@ -285,6 +292,12 @@ public Builder setAdminSubject(long adminSubject) { return this; } + public Builder setAttestationTrustStoreDelegate( + AttestationTrustStoreDelegate attestationTrustStoreDelegate) { + this.attestationTrustStoreDelegate = attestationTrustStoreDelegate; + return this; + } + public ControllerParams build() { return new ControllerParams(this); } From b76318bea513207521fb296db34c6ab3c0730db7 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 5 Jan 2023 19:39:08 +0800 Subject: [PATCH 32/44] restyled. --- .../java/AttestationTrustStoreBridge.cpp | 2 +- .../java/AttestationTrustStoreBridge.h | 2 +- .../AttestationTrustStoreDelegate.java | 24 ++++++++----------- 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index e924c189d17a13..886683f9f2a10f 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -82,4 +82,4 @@ CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const } } return CHIP_ERROR_CA_CERT_NOT_FOUND; -} \ No newline at end of file +} diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index da495c6cd0deb7..557e61ef12978e 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -32,4 +32,4 @@ class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustSt private: jobject mAttestationTrustStoreDelegate = nullptr; -}; \ No newline at end of file +}; diff --git a/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java b/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java index 87704fad7ad217..8f85175e747f25 100644 --- a/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java @@ -2,24 +2,20 @@ /** * Delegate for attestation trust store for device attestation verifiers. - * - * API is synchronous. + * + *

API is synchronous. */ public interface AttestationTrustStoreDelegate { /** - * Look-up a product attestation authority (PAA) cert by subject key - * identifier (SKID). - * - * The implementations of this interface must have access to a set of PAAs to - * trust. + * Look-up a product attestation authority (PAA) cert by subject key identifier (SKID). * - * Interface is synchronous, and therefore this should not be used unless to - * expose a PAA store that is both fully local and quick to access. - * - * @param skid Buffer containing the subject key identifier (SKID) of the PAA to - * look-up - * @return If found, the result should return paa cert in x.509 format, if not - * found, return null. + *

The implementations of this interface must have access to a set of PAAs to trust. + * + *

Interface is synchronous, and therefore this should not be used unless to expose a PAA store + * that is both fully local and quick to access. + * + * @param skid Buffer containing the subject key identifier (SKID) of the PAA to look-up + * @return If found, the result should return paa cert in x.509 format, if not found, return null. */ byte[] getProductAttestationAuthorityCert(byte[] skid); } From af9da6d7225e9f45b09aecfe919fe5963ac175a7 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 6 Jan 2023 17:17:10 +0800 Subject: [PATCH 33/44] fix jni crash --- .../java/AndroidDeviceControllerWrapper.cpp | 3 +- .../java/AttestationTrustStoreBridge.cpp | 72 ++++++++++--------- .../java/AttestationTrustStoreBridge.h | 2 + .../java/CHIPDeviceController-JNI.cpp | 12 ++-- .../AttestationTrustStoreDelegate.java | 6 +- .../ChipDeviceController.java | 8 +++ 6 files changed, 62 insertions(+), 41 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 1acb138d3c41fb..8a0bb903e59719 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -169,7 +169,8 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( const Credentials::AttestationTrustStore * trustStore; if (attestationTrustStoreDelegate != nullptr) { - wrapper->mAttestationTrustStoreBridge = new AttestationTrustStoreBridge(attestationTrustStoreDelegate); + jobject attestationTrustStoreDelegateRef = env->NewGlobalRef(attestationTrustStoreDelegate); + wrapper->mAttestationTrustStoreBridge = new AttestationTrustStoreBridge(attestationTrustStoreDelegateRef); if (wrapper->mAttestationTrustStoreBridge == nullptr) { ChipLogError(Controller, "Failed to create AttestationTrustStoreBridge"); diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 886683f9f2a10f..70e68267f41139 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -16,6 +16,7 @@ */ #include "AttestationTrustStoreBridge.h" +#include #include #include #include @@ -28,11 +29,44 @@ AttestationTrustStoreBridge::~AttestationTrustStoreBridge() { if (mAttestationTrustStoreDelegate != nullptr) { + JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); + VerifyOrReturn(env != nullptr, ChipLogError(Controller, "Could not get JNIEnv for current thread")); + env->DeleteGlobalRef(mAttestationTrustStoreDelegate); mAttestationTrustStoreDelegate = nullptr; } } -CHIP_ERROR GetPaaCertFromJavaDelegate(jobject attestationTrustStoreDelegate, const chip::ByteSpan & skid, jbyteArray & javaPaaCert) +CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, + chip::MutableByteSpan & outPaaDerBuffer) const +{ + constexpr size_t paaCertAllocatedLen = chip::Credentials::kMaxDERCertLength; + Platform::ScopedMemoryBuffer paaCert; + MutableByteSpan paaDerBuffer; + + VerifyOrReturnError(paaCert.Alloc(paaCertAllocatedLen), CHIP_ERROR_NO_MEMORY); + + VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); + + paaDerBuffer = MutableByteSpan(paaCert.Get(), paaCertAllocatedLen); + CHIP_ERROR err = GetPaaCertFromJava(skid, paaDerBuffer); + VerifyOrReturnError(err == CHIP_NO_ERROR, err); + + uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; + chip::MutableByteSpan candidateSkidSpan{ skidBuf }; + VerifyOrReturnError(CHIP_NO_ERROR == chip::Crypto::ExtractSKIDFromX509Cert(paaDerBuffer, candidateSkidSpan), + CHIP_ERROR_INTERNAL); + + // Make sure the skid of the paa cert is match. + if (skid.data_equal(candidateSkidSpan)) + { + // Found a match + return CopySpanToMutableSpan(paaDerBuffer, outPaaDerBuffer); + } + return CHIP_ERROR_CA_CERT_NOT_FOUND; +} + +CHIP_ERROR AttestationTrustStoreBridge::GetPaaCertFromJava(const chip::ByteSpan & skid, + chip::MutableByteSpan & outPaaDerBuffer) const { JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); jclass attestationTrustStoreDelegateCls = nullptr; @@ -43,43 +77,17 @@ CHIP_ERROR GetPaaCertFromJavaDelegate(jobject attestationTrustStoreDelegate, con attestationTrustStoreDelegateCls); VerifyOrReturnError(attestationTrustStoreDelegateCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); - JniReferences::GetInstance().FindMethod(env, attestationTrustStoreDelegate, "getProductAttestationAuthorityCert", "(B[)B[", + JniReferences::GetInstance().FindMethod(env, mAttestationTrustStoreDelegate, "getProductAttestationAuthorityCert", "([B)[B", &getProductAttestationAuthorityCertMethod); VerifyOrReturnError(getProductAttestationAuthorityCertMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); JniReferences::GetInstance().N2J_ByteArray(env, skid.data(), static_cast(skid.size()), javaSkid); VerifyOrReturnError(javaSkid != nullptr, CHIP_ERROR_NO_MEMORY); - javaPaaCert = - (jbyteArray) env->CallObjectMethod(attestationTrustStoreDelegate, getProductAttestationAuthorityCertMethod, javaSkid); + jbyteArray javaPaaCert = + (jbyteArray) env->CallObjectMethod(mAttestationTrustStoreDelegate, getProductAttestationAuthorityCertMethod, javaSkid); + JniByteArray paaCertBytes(env, javaPaaCert); + CopySpanToMutableSpan(paaCertBytes.byteSpan(), outPaaDerBuffer); return CHIP_NO_ERROR; } - -CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, - chip::MutableByteSpan & outPaaDerBuffer) const -{ - - JNIEnv * env = JniReferences::GetInstance().GetEnvForCurrentThread(); - jbyteArray javaPaaCert = nullptr; - - VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); - - CHIP_ERROR err = GetPaaCertFromJavaDelegate(mAttestationTrustStoreDelegate, skid, javaPaaCert); - VerifyOrReturnError(err != CHIP_NO_ERROR, err); - if (javaPaaCert != nullptr) - { - JniByteArray paaCertBytes(env, javaPaaCert); - uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; - chip::MutableByteSpan candidateSkidSpan{ skidBuf }; - VerifyOrReturnError(CHIP_NO_ERROR == chip::Crypto::ExtractSKIDFromX509Cert(paaCertBytes.byteSpan(), candidateSkidSpan), - CHIP_ERROR_INTERNAL); - // Make sure the skid of the paa cert is match. - if (skid.data_equal(candidateSkidSpan)) - { - // Found a match - return CopySpanToMutableSpan(paaCertBytes.byteSpan(), outPaaDerBuffer); - } - } - return CHIP_ERROR_CA_CERT_NOT_FOUND; -} diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index 557e61ef12978e..48ac99b1a64d41 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -32,4 +32,6 @@ class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustSt private: jobject mAttestationTrustStoreDelegate = nullptr; + + CHIP_ERROR GetPaaCertFromJava(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const; }; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 3e30a1377fc3ef..6b4a2d06f7a424 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -334,7 +334,7 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr SuccessOrExit(err); jmethodID getAttestationTrustStoreDelegate; - err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "attestationTrustStoreDelegate", + err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAttestationTrustStoreDelegate", "()Lchip/devicecontroller/AttestationTrustStoreDelegate;", &getAttestationTrustStoreDelegate); SuccessOrExit(err); @@ -740,22 +740,20 @@ JNI_METHOD(jbyteArray, convertX509CertToMatterCert) return outJbytes; } -JNI_METHOD(jbyteArray, extractSKIDFromX509Cert) -(JNIEnv * env, jobject self, jbyteArray x509Cert) +JNI_METHOD(jbyteArray, extractSkidFromPaaCert) +(JNIEnv * env, jobject self, jbyteArray paaCert) { - chip::DeviceLayer::StackLock lock; - uint32_t allocatedCertLength = chip::Credentials::kMaxCHIPCertLength; chip::Platform::ScopedMemoryBuffer outBuf; jbyteArray outJbytes = nullptr; - JniByteArray x509CertBytes(env, x509Cert); + JniByteArray paaCertBytes(env, paaCert); CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(outBuf.Alloc(allocatedCertLength), err = CHIP_ERROR_NO_MEMORY); { MutableByteSpan outBytes(outBuf.Get(), allocatedCertLength); - err = chip::Crypto::ExtractSKIDFromX509Cert(x509CertBytes.byteSpan(), outBytes); + err = chip::Crypto::ExtractSKIDFromX509Cert(paaCertBytes.byteSpan(), outBytes); SuccessOrExit(err); VerifyOrExit(chip::CanCastTo(outBytes.size()), err = CHIP_ERROR_INTERNAL); diff --git a/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java b/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java index 8f85175e747f25..f4fbec34386b5c 100644 --- a/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java +++ b/src/controller/java/src/chip/devicecontroller/AttestationTrustStoreDelegate.java @@ -1,9 +1,12 @@ package chip.devicecontroller; +import javax.annotation.Nullable; + /** * Delegate for attestation trust store for device attestation verifiers. * - *

API is synchronous. + *

API is synchronous. This implementation will replace the built-in attestation trust store, + * please make sure you have the required paa certificate before commissioning. */ public interface AttestationTrustStoreDelegate { /** @@ -17,5 +20,6 @@ public interface AttestationTrustStoreDelegate { * @param skid Buffer containing the subject key identifier (SKID) of the PAA to look-up * @return If found, the result should return paa cert in x.509 format, if not found, return null. */ + @Nullable byte[] getProductAttestationAuthorityCert(byte[] skid); } diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 74f1628b5eb63d..d247684dd98126 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -622,6 +622,14 @@ public void readPath( */ public native byte[] convertX509CertToMatterCert(byte[] x509Cert); + /** + * Extract skid from paa cert. + * + * @param paaCert + * @return + */ + public native byte[] extractSkidFromPaaCert(byte[] paaCert); + /** * Generates a new PASE verifier for the given setup PIN code. * From d764674a4ca432108a0303920fcf6e4a009f4451 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 10 Jan 2023 21:04:23 +0800 Subject: [PATCH 34/44] Modify the timing of setting the Attestation trust store --- .../java/AndroidDeviceControllerWrapper.cpp | 26 ++----- .../java/AndroidDeviceControllerWrapper.h | 16 ++++- .../java/CHIPDeviceController-JNI.cpp | 68 ++++++++++++------- .../ChipDeviceController.java | 8 +++ .../devicecontroller/ControllerParams.java | 13 ---- 5 files changed, 72 insertions(+), 59 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.cpp b/src/controller/java/AndroidDeviceControllerWrapper.cpp index 8a0bb903e59719..0d696c9a6a42ea 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.cpp +++ b/src/controller/java/AndroidDeviceControllerWrapper.cpp @@ -101,8 +101,7 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( #endif jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, - bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, bool skipCommissioningComplete, - jobject attestationTrustStoreDelegate, CHIP_ERROR * errInfoOnFailure) + bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure) { if (errInfoOnFailure == nullptr) { @@ -166,25 +165,9 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( #endif // Initialize device attestation verifier - const Credentials::AttestationTrustStore * trustStore; - if (attestationTrustStoreDelegate != nullptr) - { - jobject attestationTrustStoreDelegateRef = env->NewGlobalRef(attestationTrustStoreDelegate); - wrapper->mAttestationTrustStoreBridge = new AttestationTrustStoreBridge(attestationTrustStoreDelegateRef); - if (wrapper->mAttestationTrustStoreBridge == nullptr) - { - ChipLogError(Controller, "Failed to create AttestationTrustStoreBridge"); - *errInfoOnFailure = CHIP_ERROR_NO_MEMORY; - return nullptr; - } - trustStore = wrapper->mAttestationTrustStoreBridge; - } - else - { - trustStore = chip::Credentials::GetTestAttestationTrustStore(); - } - - wrapper->mDeviceAttestationVerifier = new Credentials::DefaultDACVerifier(trustStore); + // TODO: Replace testingRootStore with a AttestationTrustStore that has the necessary official PAA roots available + const chip::Credentials::AttestationTrustStore * testingRootStore = chip::Credentials::GetTestAttestationTrustStore(); + chip::Credentials::SetDeviceAttestationVerifier(GetDefaultDACVerifier(testingRootStore)); chip::Controller::FactoryInitParams initParams; chip::Controller::SetupParams setupParams; @@ -203,7 +186,6 @@ AndroidDeviceControllerWrapper * AndroidDeviceControllerWrapper::AllocateNew( setupParams.operationalCredentialsDelegate = opCredsIssuer; setupParams.defaultCommissioner = &wrapper->mAutoCommissioner; initParams.fabricIndependentStorage = wrapperStorage; - setupParams.deviceAttestationVerifier = wrapper->mDeviceAttestationVerifier; wrapper->mGroupDataProvider.SetStorageDelegate(wrapperStorage); diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 74d71fa3032e7f..602d261ecbdbcb 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -170,7 +170,7 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel jobject keypairDelegate, jbyteArray rootCertificate, jbyteArray intermediateCertificate, jbyteArray nodeOperationalCertificate, jbyteArray ipkEpochKey, uint16_t listenPort, uint16_t controllerVendorId, uint16_t failsafeTimerSeconds, bool attemptNetworkScanWiFi, bool attemptNetworkScanThread, - bool skipCommissioningComplete, jobject attestationTrustStoreDelegate, CHIP_ERROR * errInfoOnFailure); + bool skipCommissioningComplete, CHIP_ERROR * errInfoOnFailure); #ifdef JAVA_MATTER_CONTROLLER_TEST chip::Controller::ExampleOperationalCredentialsIssuer * GetAndroidOperationalCredentialsIssuer() @@ -188,6 +188,20 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } + void SetAttestationTrustStoreBridge(AttestationTrustStoreBridge * attestationTrustStoreBridge) + { + mAttestationTrustStoreBridge = attestationTrustStoreBridge; + } + + AttestationTrustStoreBridge * GetAttestationTrustStoreBridge() { return mAttestationTrustStoreBridge; } + + void SetDeviceAttestationVerifier(chip::Credentials::DeviceAttestationVerifier * deviceAttestationVerifier) + { + mDeviceAttestationVerifier = deviceAttestationVerifier; + } + + chip::Credentials::DeviceAttestationVerifier * GetDeviceAttestationVerifier() { return mDeviceAttestationVerifier; } + void ClearDeviceAttestationDelegateBridge() { if (mDeviceAttestationDelegateBridge != nullptr) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 6b4a2d06f7a424..06023dbc65bf23 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -333,28 +333,21 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAdminSubject", "()J", &getAdminSubject); SuccessOrExit(err); - jmethodID getAttestationTrustStoreDelegate; - err = chip::JniReferences::GetInstance().FindMethod(env, controllerParams, "getAttestationTrustStoreDelegate", - "()Lchip/devicecontroller/AttestationTrustStoreDelegate;", - &getAttestationTrustStoreDelegate); - SuccessOrExit(err); - { - uint64_t fabricId = env->CallLongMethod(controllerParams, getFabricId); - uint16_t listenPort = env->CallIntMethod(controllerParams, getUdpListenPort); - uint16_t controllerVendorId = env->CallIntMethod(controllerParams, getControllerVendorId); - jobject keypairDelegate = env->CallObjectMethod(controllerParams, getKeypairDelegate); - jbyteArray rootCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getRootCertificate); - jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); - jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); - jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); - uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); - uint16_t caseFailsafeTimerSeconds = env->CallIntMethod(controllerParams, getCASEFailsafeTimerSeconds); - bool attemptNetworkScanWiFi = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanWiFi); - bool attemptNetworkScanThread = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanThread); - bool skipCommissioningComplete = env->CallBooleanMethod(controllerParams, getSkipCommissioningComplete); - uint64_t adminSubject = env->CallLongMethod(controllerParams, getAdminSubject); - jobject attestationTrustStoreDelegate = env->CallObjectMethod(controllerParams, getAttestationTrustStoreDelegate); + uint64_t fabricId = env->CallLongMethod(controllerParams, getFabricId); + uint16_t listenPort = env->CallIntMethod(controllerParams, getUdpListenPort); + uint16_t controllerVendorId = env->CallIntMethod(controllerParams, getControllerVendorId); + jobject keypairDelegate = env->CallObjectMethod(controllerParams, getKeypairDelegate); + jbyteArray rootCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getRootCertificate); + jbyteArray intermediateCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getIntermediateCertificate); + jbyteArray operationalCertificate = (jbyteArray) env->CallObjectMethod(controllerParams, getOperationalCertificate); + jbyteArray ipk = (jbyteArray) env->CallObjectMethod(controllerParams, getIpk); + uint16_t failsafeTimerSeconds = env->CallIntMethod(controllerParams, getFailsafeTimerSeconds); + uint16_t caseFailsafeTimerSeconds = env->CallIntMethod(controllerParams, getCASEFailsafeTimerSeconds); + bool attemptNetworkScanWiFi = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanWiFi); + bool attemptNetworkScanThread = env->CallBooleanMethod(controllerParams, getAttemptNetworkScanThread); + bool skipCommissioningComplete = env->CallBooleanMethod(controllerParams, getSkipCommissioningComplete); + uint64_t adminSubject = env->CallLongMethod(controllerParams, getAdminSubject); #ifdef JAVA_MATTER_CONTROLLER_TEST std::unique_ptr opCredsIssuer( @@ -367,8 +360,7 @@ JNI_METHOD(jlong, newDeviceController)(JNIEnv * env, jobject self, jobject contr sJVM, self, kLocalDeviceId, fabricId, chip::kUndefinedCATs, &DeviceLayer::SystemLayer(), DeviceLayer::TCPEndPointManager(), DeviceLayer::UDPEndPointManager(), std::move(opCredsIssuer), keypairDelegate, rootCertificate, intermediateCertificate, operationalCertificate, ipk, listenPort, controllerVendorId, - failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, skipCommissioningComplete, - attestationTrustStoreDelegate, &err); + failsafeTimerSeconds, attemptNetworkScanWiFi, attemptNetworkScanThread, skipCommissioningComplete, &err); SuccessOrExit(err); if (caseFailsafeTimerSeconds > 0) @@ -448,6 +440,36 @@ JNI_METHOD(void, setDeviceAttestationDelegate) } } +JNI_METHOD(void, setAttestationTrustStoreDelegate) +(JNIEnv * env, jobject self, jlong handle, jobject attestationTrustStoreDelegate) +{ + chip::DeviceLayer::StackLock lock; + CHIP_ERROR err = CHIP_NO_ERROR; + AndroidDeviceControllerWrapper * wrapper = AndroidDeviceControllerWrapper::FromJNIHandle(handle); + + ChipLogProgress(Controller, "setAttestationTrustStoreDelegate() called"); + + if (attestationTrustStoreDelegate != nullptr) + { + jobject attestationTrustStoreDelegateRef = env->NewGlobalRef(attestationTrustStoreDelegate); + + wrapper->SetAttestationTrustStoreBridge(new AttestationTrustStoreBridge(attestationTrustStoreDelegateRef)); + VerifyOrExit(wrapper->GetAttestationTrustStoreBridge() != nullptr, err = CHIP_ERROR_NO_MEMORY); + + wrapper->SetDeviceAttestationVerifier(new Credentials::DefaultDACVerifier(wrapper->GetAttestationTrustStoreBridge())); + VerifyOrExit(wrapper->GetDeviceAttestationVerifier() != nullptr, err = CHIP_ERROR_NO_MEMORY); + + wrapper->Controller()->SetDeviceAttestationVerifier(wrapper->GetDeviceAttestationVerifier()); + } + +exit: + if (err != CHIP_NO_ERROR) + { + ChipLogError(Controller, "Failed to set device attestation delegate."); + JniReferences::GetInstance().ThrowError(env, sChipDeviceControllerExceptionCls, err); + } +} + JNI_METHOD(void, commissionDevice) (JNIEnv * env, jobject self, jlong handle, jlong deviceId, jbyteArray csrNonce, jobject networkCredentials) { diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index d247684dd98126..e39858f5e9215c 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -123,6 +123,11 @@ public void setDeviceAttestationFailureCallback( setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeoutSecs, failureCallback); } + public void setAttestationTrustStoreDelegate( + AttestationTrustStoreDelegate attestationTrustStoreDelegate) { + setAttestationTrustStoreDelegate(deviceControllerPtr, attestationTrustStoreDelegate); + } + public void pairDevice( BluetoothGatt bleServer, int connId, @@ -674,6 +679,9 @@ private native void read( private native void setDeviceAttestationDelegate( long deviceControllerPtr, int failSafeExpiryTimeoutSecs, DeviceAttestationDelegate delegate); + private native void setAttestationTrustStoreDelegate( + long deviceControllerPtr, AttestationTrustStoreDelegate delegate); + private native void pairDevice( long deviceControllerPtr, long deviceId, diff --git a/src/controller/java/src/chip/devicecontroller/ControllerParams.java b/src/controller/java/src/chip/devicecontroller/ControllerParams.java index 7819f6bff36344..5c13d853f84c59 100644 --- a/src/controller/java/src/chip/devicecontroller/ControllerParams.java +++ b/src/controller/java/src/chip/devicecontroller/ControllerParams.java @@ -19,7 +19,6 @@ public final class ControllerParams { @Nullable private final byte[] operationalCertificate; @Nullable private final byte[] ipk; private final long adminSubject; - @Nullable private final AttestationTrustStoreDelegate attestationTrustStoreDelegate; private static final int LEGACY_GLOBAL_CHIP_PORT = 5540; @@ -39,7 +38,6 @@ private ControllerParams(Builder builder) { this.operationalCertificate = builder.operationalCertificate; this.ipk = builder.ipk; this.adminSubject = builder.adminSubject; - this.attestationTrustStoreDelegate = builder.attestationTrustStoreDelegate; } public long getFabricId() { @@ -99,10 +97,6 @@ public long getAdminSubject() { return adminSubject; } - public AttestationTrustStoreDelegate getAttestationTrustStoreDelegate() { - return attestationTrustStoreDelegate; - } - /** Returns parameters with ephemerally generated operational credentials */ public static Builder newBuilder() { return new Builder(); @@ -138,7 +132,6 @@ public static class Builder { @Nullable private byte[] operationalCertificate = null; @Nullable private byte[] ipk = null; private long adminSubject = 0; - @Nullable private AttestationTrustStoreDelegate attestationTrustStoreDelegate; private Builder() {} @@ -292,12 +285,6 @@ public Builder setAdminSubject(long adminSubject) { return this; } - public Builder setAttestationTrustStoreDelegate( - AttestationTrustStoreDelegate attestationTrustStoreDelegate) { - this.attestationTrustStoreDelegate = attestationTrustStoreDelegate; - return this; - } - public ControllerParams build() { return new ControllerParams(this); } From 731c941a4345805cd5957ed1f698651b2039807a Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 12 Jan 2023 20:13:21 +0800 Subject: [PATCH 35/44] setAttestationTrustStoreDelegate add comments --- .../src/chip/devicecontroller/ChipDeviceController.java | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index 3730df8cbb1b95..a0fb8f5fb84481 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -123,6 +123,14 @@ public void setDeviceAttestationFailureCallback( setDeviceAttestationDelegate(deviceControllerPtr, failSafeExpiryTimeoutSecs, failureCallback); } + /** + * Set delegate for attestation trust store for device attestation verifiers. + * + *

It will replace the built-in attestation trust store, please make sure you have the required + * paa certificate before commissioning. + * + * @param attestationTrustStoreDelegate Delegate for attestation trust store + */ public void setAttestationTrustStoreDelegate( AttestationTrustStoreDelegate attestationTrustStoreDelegate) { setAttestationTrustStoreDelegate(deviceControllerPtr, attestationTrustStoreDelegate); From b0b7e1c78dc16bce74ff000f84c88051136aed69 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 13 Jan 2023 10:53:57 +0800 Subject: [PATCH 36/44] Remove redundant variables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Damian Królik <66667989+Damian-Nordic@users.noreply.github.com> --- src/controller/java/AttestationTrustStoreBridge.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 70e68267f41139..061aa934bc6fa4 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -48,8 +48,7 @@ CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); paaDerBuffer = MutableByteSpan(paaCert.Get(), paaCertAllocatedLen); - CHIP_ERROR err = GetPaaCertFromJava(skid, paaDerBuffer); - VerifyOrReturnError(err == CHIP_NO_ERROR, err); + ReturnErrorOnFailure(GetPaaCertFromJava(skid, paaDerBuffer)); uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; chip::MutableByteSpan candidateSkidSpan{ skidBuf }; From 7de0a341ab1543fd62f3555637b3202ae8b8b186 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 13 Jan 2023 11:25:15 +0800 Subject: [PATCH 37/44] Release jni class references --- src/controller/java/AttestationTrustStoreBridge.cpp | 1 + src/controller/java/DeviceAttestationDelegateBridge.cpp | 3 +++ .../java/src/chip/devicecontroller/ChipDeviceController.java | 4 ++-- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 70e68267f41139..ba7c82ba831c81 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -76,6 +76,7 @@ CHIP_ERROR AttestationTrustStoreBridge::GetPaaCertFromJava(const chip::ByteSpan JniReferences::GetInstance().GetClassRef(env, "chip/devicecontroller/AttestationTrustStoreDelegate", attestationTrustStoreDelegateCls); VerifyOrReturnError(attestationTrustStoreDelegateCls != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); + JniClass attestationTrustStoreDelegateJniCls(attestationTrustStoreDelegateCls); JniReferences::GetInstance().FindMethod(env, mAttestationTrustStoreDelegate, "getProductAttestationAuthorityCert", "([B)[B", &getProductAttestationAuthorityCertMethod); diff --git a/src/controller/java/DeviceAttestationDelegateBridge.cpp b/src/controller/java/DeviceAttestationDelegateBridge.cpp index be46a783b197ad..5f002c726c175d 100644 --- a/src/controller/java/DeviceAttestationDelegateBridge.cpp +++ b/src/controller/java/DeviceAttestationDelegateBridge.cpp @@ -77,11 +77,14 @@ void DeviceAttestationDelegateBridge::OnDeviceAttestationCompleted( env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationCompletionCallback", completionCallbackCls); VerifyOrReturn(completionCallbackCls != nullptr, ChipLogError(Controller, "Could not find device attestation completion callback class.")); + JniClass completionCallbackJniCls(completionCallbackCls); + jclass failureCallbackCls = nullptr; JniReferences::GetInstance().GetClassRef( env, "chip/devicecontroller/DeviceAttestationDelegate$DeviceAttestationFailureCallback", failureCallbackCls); VerifyOrReturn(failureCallbackCls != nullptr, ChipLogError(Controller, "Could not find device attestation failure callback class.")); + JniClass failureCallbackJniCls(failureCallbackCls); if (env->IsInstanceOf(mDeviceAttestationDelegate, completionCallbackCls)) { diff --git a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java index a0fb8f5fb84481..99214ec881d0d3 100644 --- a/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java +++ b/src/controller/java/src/chip/devicecontroller/ChipDeviceController.java @@ -642,8 +642,8 @@ public void readPath( /** * Extract skid from paa cert. * - * @param paaCert - * @return + * @param paaCert The product attestation authority (PAA) cert + * @return The subject key identifier (SKID) */ public native byte[] extractSkidFromPaaCert(byte[] paaCert); From 4ed1234f7b111e6150daa9d3b7f8f5e618f8934e Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Fri, 13 Jan 2023 11:54:07 +0800 Subject: [PATCH 38/44] Fix objects leak when calling 'setAttestationTrustStoreDelegate' twice --- .../java/AndroidDeviceControllerWrapper.h | 26 ++++++++++++++++--- .../java/AttestationTrustStoreBridge.cpp | 2 +- .../java/CHIPDeviceController-JNI.cpp | 3 ++- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/controller/java/AndroidDeviceControllerWrapper.h b/src/controller/java/AndroidDeviceControllerWrapper.h index 602d261ecbdbcb..a7191a9004bdd7 100644 --- a/src/controller/java/AndroidDeviceControllerWrapper.h +++ b/src/controller/java/AndroidDeviceControllerWrapper.h @@ -188,6 +188,15 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel DeviceAttestationDelegateBridge * GetDeviceAttestationDelegateBridge() { return mDeviceAttestationDelegateBridge; } + void ClearDeviceAttestationDelegateBridge() + { + if (mDeviceAttestationDelegateBridge != nullptr) + { + delete mDeviceAttestationDelegateBridge; + mDeviceAttestationDelegateBridge = nullptr; + } + } + void SetAttestationTrustStoreBridge(AttestationTrustStoreBridge * attestationTrustStoreBridge) { mAttestationTrustStoreBridge = attestationTrustStoreBridge; @@ -195,6 +204,15 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel AttestationTrustStoreBridge * GetAttestationTrustStoreBridge() { return mAttestationTrustStoreBridge; } + void ClearAttestationTrustStoreBridge() + { + if (mAttestationTrustStoreBridge != nullptr) + { + delete mAttestationTrustStoreBridge; + mAttestationTrustStoreBridge = nullptr; + } + } + void SetDeviceAttestationVerifier(chip::Credentials::DeviceAttestationVerifier * deviceAttestationVerifier) { mDeviceAttestationVerifier = deviceAttestationVerifier; @@ -202,12 +220,12 @@ class AndroidDeviceControllerWrapper : public chip::Controller::DevicePairingDel chip::Credentials::DeviceAttestationVerifier * GetDeviceAttestationVerifier() { return mDeviceAttestationVerifier; } - void ClearDeviceAttestationDelegateBridge() + void ClearDeviceAttestationVerifier() { - if (mDeviceAttestationDelegateBridge != nullptr) + if (mDeviceAttestationVerifier != nullptr) { - delete mDeviceAttestationDelegateBridge; - mDeviceAttestationDelegateBridge = nullptr; + delete mDeviceAttestationVerifier; + mDeviceAttestationVerifier = nullptr; } } diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 54a1f3dbf24b4e..71450b4f952a25 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -47,7 +47,7 @@ CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); - paaDerBuffer = MutableByteSpan(paaCert.Get(), paaCertAllocatedLen); + paaDerBuffer = MutableByteSpan(paaCert.Get(), paaCertAllocatedLen); ReturnErrorOnFailure(GetPaaCertFromJava(skid, paaDerBuffer)); uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 31c08c85323a0d..92cf55143fe0b0 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -449,11 +449,12 @@ JNI_METHOD(void, setAttestationTrustStoreDelegate) if (attestationTrustStoreDelegate != nullptr) { + wrapper->ClearAttestationTrustStoreBridge(); jobject attestationTrustStoreDelegateRef = env->NewGlobalRef(attestationTrustStoreDelegate); - wrapper->SetAttestationTrustStoreBridge(new AttestationTrustStoreBridge(attestationTrustStoreDelegateRef)); VerifyOrExit(wrapper->GetAttestationTrustStoreBridge() != nullptr, err = CHIP_ERROR_NO_MEMORY); + wrapper->ClearDeviceAttestationVerifier(); wrapper->SetDeviceAttestationVerifier(new Credentials::DefaultDACVerifier(wrapper->GetAttestationTrustStoreBridge())); VerifyOrExit(wrapper->GetDeviceAttestationVerifier() != nullptr, err = CHIP_ERROR_NO_MEMORY); From a8b9a86a69a63589aec1af74a43751309dd96773 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 17 Jan 2023 23:13:34 +0800 Subject: [PATCH 39/44] Remove unused include --- src/controller/java/AttestationTrustStoreBridge.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index 48ac99b1a64d41..3e3dc91f0987ea 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -15,9 +15,8 @@ * limitations under the License. */ -#include #include -#include +#include class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustStore { From f2d3c35cd27a571855b3ecf9c9b74a75fb26e1ba Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 17 Jan 2023 23:15:18 +0800 Subject: [PATCH 40/44] Modify private to protected --- src/controller/java/AttestationTrustStoreBridge.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index 3e3dc91f0987ea..5a964a05bc68ea 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -29,7 +29,7 @@ class AttestationTrustStoreBridge : public chip::Credentials::AttestationTrustSt CHIP_ERROR GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const override; -private: +protected: jobject mAttestationTrustStoreDelegate = nullptr; CHIP_ERROR GetPaaCertFromJava(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const; From 7e29657741976dce1c43042ddf41e2c6f3789fe5 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Tue, 17 Jan 2023 23:21:26 +0800 Subject: [PATCH 41/44] Optimize variable initialization --- src/controller/java/AttestationTrustStoreBridge.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 71450b4f952a25..1ddb415b18b39c 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -39,15 +39,13 @@ AttestationTrustStoreBridge::~AttestationTrustStoreBridge() CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::ByteSpan & skid, chip::MutableByteSpan & outPaaDerBuffer) const { + VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); + constexpr size_t paaCertAllocatedLen = chip::Credentials::kMaxDERCertLength; Platform::ScopedMemoryBuffer paaCert; - MutableByteSpan paaDerBuffer; - VerifyOrReturnError(paaCert.Alloc(paaCertAllocatedLen), CHIP_ERROR_NO_MEMORY); - - VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); - - paaDerBuffer = MutableByteSpan(paaCert.Get(), paaCertAllocatedLen); + + MutableByteSpan paaDerBuffer{paaCert.Get(), paaCertAllocatedLen}; ReturnErrorOnFailure(GetPaaCertFromJava(skid, paaDerBuffer)); uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; From 4c219c2ec9c12f461f312bdd0c81f576120e7a41 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Wed, 18 Jan 2023 15:16:09 +0800 Subject: [PATCH 42/44] fix compile error --- src/controller/java/AttestationTrustStoreBridge.cpp | 6 +++--- src/controller/java/AttestationTrustStoreBridge.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 1ddb415b18b39c..57dbaf68d3613e 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -40,12 +40,12 @@ CHIP_ERROR AttestationTrustStoreBridge::GetProductAttestationAuthorityCert(const chip::MutableByteSpan & outPaaDerBuffer) const { VerifyOrReturnError(skid.size() == chip::Crypto::kSubjectKeyIdentifierLength, CHIP_ERROR_INVALID_ARGUMENT); - + constexpr size_t paaCertAllocatedLen = chip::Credentials::kMaxDERCertLength; Platform::ScopedMemoryBuffer paaCert; VerifyOrReturnError(paaCert.Alloc(paaCertAllocatedLen), CHIP_ERROR_NO_MEMORY); - - MutableByteSpan paaDerBuffer{paaCert.Get(), paaCertAllocatedLen}; + + MutableByteSpan paaDerBuffer{ paaCert.Get(), paaCertAllocatedLen }; ReturnErrorOnFailure(GetPaaCertFromJava(skid, paaDerBuffer)); uint8_t skidBuf[chip::Crypto::kSubjectKeyIdentifierLength] = { 0 }; diff --git a/src/controller/java/AttestationTrustStoreBridge.h b/src/controller/java/AttestationTrustStoreBridge.h index 5a964a05bc68ea..be84be2f530307 100644 --- a/src/controller/java/AttestationTrustStoreBridge.h +++ b/src/controller/java/AttestationTrustStoreBridge.h @@ -14,7 +14,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include #include From 67dc3cfa6c350f4727dfa34ec2d8154e09376d08 Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Wed, 18 Jan 2023 18:13:16 +0800 Subject: [PATCH 43/44] Moving the alloc of AttestationTrustStoreBridge before clear --- src/controller/java/CHIPDeviceController-JNI.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/controller/java/CHIPDeviceController-JNI.cpp b/src/controller/java/CHIPDeviceController-JNI.cpp index 92cf55143fe0b0..17bbc1985dbd4c 100644 --- a/src/controller/java/CHIPDeviceController-JNI.cpp +++ b/src/controller/java/CHIPDeviceController-JNI.cpp @@ -449,14 +449,18 @@ JNI_METHOD(void, setAttestationTrustStoreDelegate) if (attestationTrustStoreDelegate != nullptr) { - wrapper->ClearAttestationTrustStoreBridge(); jobject attestationTrustStoreDelegateRef = env->NewGlobalRef(attestationTrustStoreDelegate); - wrapper->SetAttestationTrustStoreBridge(new AttestationTrustStoreBridge(attestationTrustStoreDelegateRef)); - VerifyOrExit(wrapper->GetAttestationTrustStoreBridge() != nullptr, err = CHIP_ERROR_NO_MEMORY); + AttestationTrustStoreBridge * attestationTrustStoreBridge = + new AttestationTrustStoreBridge(attestationTrustStoreDelegateRef); + VerifyOrExit(attestationTrustStoreBridge != nullptr, err = CHIP_ERROR_NO_MEMORY); + wrapper->ClearAttestationTrustStoreBridge(); + wrapper->SetAttestationTrustStoreBridge(attestationTrustStoreBridge); + DeviceAttestationVerifier * deviceAttestationVerifier = + new Credentials::DefaultDACVerifier(wrapper->GetAttestationTrustStoreBridge()); + VerifyOrExit(deviceAttestationVerifier != nullptr, err = CHIP_ERROR_NO_MEMORY); wrapper->ClearDeviceAttestationVerifier(); - wrapper->SetDeviceAttestationVerifier(new Credentials::DefaultDACVerifier(wrapper->GetAttestationTrustStoreBridge())); - VerifyOrExit(wrapper->GetDeviceAttestationVerifier() != nullptr, err = CHIP_ERROR_NO_MEMORY); + wrapper->SetDeviceAttestationVerifier(deviceAttestationVerifier); wrapper->Controller()->SetDeviceAttestationVerifier(wrapper->GetDeviceAttestationVerifier()); } From 3f82e301b9d81f4723a9225dae54f85cc400b20c Mon Sep 17 00:00:00 2001 From: panliming-tuya Date: Thu, 19 Jan 2023 18:06:32 +0800 Subject: [PATCH 44/44] Add Android example --- .../com/google/chip/chiptool/ChipClient.kt | 4 ++ .../ExampleAttestationTrustStoreDelegate.kt | 48 +++++++++++++++++++ .../java/AttestationTrustStoreBridge.cpp | 2 + 3 files changed, 54 insertions(+) create mode 100644 examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/attestation/ExampleAttestationTrustStoreDelegate.kt diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt index 6e3833820716a3..568046623c15a2 100644 --- a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/ChipClient.kt @@ -30,6 +30,7 @@ import chip.platform.NsdManagerServiceBrowser import chip.platform.NsdManagerServiceResolver import chip.platform.PreferencesConfigurationManager import chip.platform.PreferencesKeyValueStoreManager +import com.google.chip.chiptool.attestation.ExampleAttestationTrustStoreDelegate import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine @@ -47,6 +48,9 @@ object ChipClient { if (!this::chipDeviceController.isInitialized) { chipDeviceController = ChipDeviceController(ControllerParams.newBuilder().setControllerVendorId(VENDOR_ID).build()) + // Set delegate for attestation trust store for device attestation verifier. + // It will replace the default attestation trust store. + chipDeviceController.setAttestationTrustStoreDelegate(ExampleAttestationTrustStoreDelegate(chipDeviceController)) } return chipDeviceController } diff --git a/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/attestation/ExampleAttestationTrustStoreDelegate.kt b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/attestation/ExampleAttestationTrustStoreDelegate.kt new file mode 100644 index 00000000000000..f5ae91dff353ee --- /dev/null +++ b/examples/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/attestation/ExampleAttestationTrustStoreDelegate.kt @@ -0,0 +1,48 @@ +package com.google.chip.chiptool.attestation + +import android.util.Base64 +import chip.devicecontroller.AttestationTrustStoreDelegate +import chip.devicecontroller.ChipDeviceController +import java.util.* + +class ExampleAttestationTrustStoreDelegate(val chipDeviceController: ChipDeviceController) : + AttestationTrustStoreDelegate { + + private val paaCerts = arrayListOf(TEST_PAA_FFF1_Cert, TEST_PAA_NOVID_CERT) + + override fun getProductAttestationAuthorityCert(skid: ByteArray): ByteArray? { + for (paaCert in paaCerts) { + val paaCertBytes = Base64.decode(paaCert, Base64.DEFAULT) + val skidFromPaaCert = chipDeviceController.extractSkidFromPaaCert(paaCertBytes) + if (Arrays.equals(skid, skidFromPaaCert)) { + return paaCertBytes + } + } + return null + } + + companion object { + const val TEST_PAA_FFF1_Cert = + "MIIBvTCCAWSgAwIBAgIITqjoMYLUHBwwCgYIKoZIzj0EAwIwMDEYMBYGA1UEAwwP\n" + + "TWF0dGVyIFRlc3QgUEFBMRQwEgYKKwYBBAGConwCAQwERkZGMTAgFw0yMTA2Mjgx\n" + + "NDIzNDNaGA85OTk5MTIzMTIzNTk1OVowMDEYMBYGA1UEAwwPTWF0dGVyIFRlc3Qg\n" + + "UEFBMRQwEgYKKwYBBAGConwCAQwERkZGMTBZMBMGByqGSM49AgEGCCqGSM49AwEH\n" + + "A0IABLbLY3KIfyko9brIGqnZOuJDHK2p154kL2UXfvnO2TKijs0Duq9qj8oYShpQ\n" + + "NUKWDUU/MD8fGUIddR6Pjxqam3WjZjBkMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYD\n" + + "VR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRq/SJ3H1Ef7L8WQZdnENzcMaFxfjAfBgNV\n" + + "HSMEGDAWgBRq/SJ3H1Ef7L8WQZdnENzcMaFxfjAKBggqhkjOPQQDAgNHADBEAiBQ\n" + + "qoAC9NkyqaAFOPZTaK0P/8jvu8m+t9pWmDXPmqdRDgIgI7rI/g8j51RFtlM5CBpH\n" + + "mUkpxyqvChVI1A0DTVFLJd4=" + + const val TEST_PAA_NOVID_CERT = + "MIIBkTCCATegAwIBAgIHC4+6qN2G7jAKBggqhkjOPQQDAjAaMRgwFgYDVQQDDA9N\n" + + "YXR0ZXIgVGVzdCBQQUEwIBcNMjEwNjI4MTQyMzQzWhgPOTk5OTEyMzEyMzU5NTla\n" + + "MBoxGDAWBgNVBAMMD01hdHRlciBUZXN0IFBBQTBZMBMGByqGSM49AgEGCCqGSM49\n" + + "AwEHA0IABBDvAqgah7aBIfuo0xl4+AejF+UKqKgoRGgokUuTPejt1KXDnJ/3Gkzj\n" + + "ZH/X9iZTt9JJX8ukwPR/h2iAA54HIEqjZjBkMBIGA1UdEwEB/wQIMAYBAf8CAQEw\n" + + "DgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBR4XOcFuGuPTm/Hk6pgy0PqaWiC1TAf\n" + + "BgNVHSMEGDAWgBR4XOcFuGuPTm/Hk6pgy0PqaWiC1TAKBggqhkjOPQQDAgNIADBF\n" + + "AiEAue/bPqBqUuwL8B5h2u0sLRVt22zwFBAdq3mPrAX6R+UCIGAGHT411g2dSw1E\n" + + "ja12EvfoXFguP8MS3Bh5TdNzcV5d" + } +} diff --git a/src/controller/java/AttestationTrustStoreBridge.cpp b/src/controller/java/AttestationTrustStoreBridge.cpp index 57dbaf68d3613e..d5915543fa0be0 100644 --- a/src/controller/java/AttestationTrustStoreBridge.cpp +++ b/src/controller/java/AttestationTrustStoreBridge.cpp @@ -84,6 +84,8 @@ CHIP_ERROR AttestationTrustStoreBridge::GetPaaCertFromJava(const chip::ByteSpan jbyteArray javaPaaCert = (jbyteArray) env->CallObjectMethod(mAttestationTrustStoreDelegate, getProductAttestationAuthorityCertMethod, javaSkid); + VerifyOrReturnError(javaPaaCert != nullptr, CHIP_ERROR_CA_CERT_NOT_FOUND); + JniByteArray paaCertBytes(env, javaPaaCert); CopySpanToMutableSpan(paaCertBytes.byteSpan(), outPaaDerBuffer);