Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Add GetDevicePublicKey #2400

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

aromaa
Copy link
Contributor

@aromaa aromaa commented Jul 21, 2022

Description

Motivation and Context

How Has This Been Tested?

Screenshots

Types of changes

  • Improvement (non-breaking change that improves a feature, code or algorithm)
  • Bug fix (non-breaking change which fixes an issue with code or algorithm)
  • New feature (non-breaking change which adds functionality to code)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Config and build (change in the configuration and build system, has no impact on code or features)
  • Dev Containers (changes related with Dev Containers, has no impact on code or features)
  • Dependencies (update dependencies and changes associated, has no impact on code or features)
  • Documentation (changes or updates in the documentation, has no impact on code or features)

Checklist

  • My code follows the code style of this project (only if there are changes in source code).
  • My changes require an update to the documentation (there are changes that require the docs website to be updated).
  • I have updated the documentation accordingly (the changes require an update on the docs in this repo).
  • I have read the CONTRIBUTING document.
  • I have tested everything locally and all new and existing tests passed (only if there are changes in source code).

Summary by CodeRabbit

  • New Features

    • Added a method to retrieve the device's public key in raw byte array format.
    • Expanded SSL certificate handling capabilities with new functions for public key extraction.
  • Version Update

    • Updated System.Net assembly version to support new functionality.
  • Technical Improvements

    • Introduced a new X.509 certificate data structure for handling raw data.
    • Enhanced infrastructure for public key extraction across different platforms.
    • Organized enum types into more appropriate header files for improved maintainability.

@nfbot nfbot added the Type: dependencies Pull requests that update a dependency file(s) or version label Jul 21, 2022
@aromaa aromaa closed this Dec 13, 2022
@aromaa aromaa force-pushed the feature/device-public-key branch from 918c50c to e66624a Compare December 13, 2022 09:53
@nfbot nfbot added invalid and removed Type: dependencies Pull requests that update a dependency file(s) or version labels Dec 13, 2022
@aromaa aromaa reopened this Dec 13, 2022
@aromaa
Copy link
Contributor Author

aromaa commented Dec 13, 2022

Okay, I somehow did something wrong while rebasing this to fix the force push conflict and messed up the whole commit history and lost my own while at it. sigh Anyways, fixed it.

@networkfusion
Copy link
Member

@aromaa Is this PR still valid given all the changes?

@aromaa
Copy link
Contributor Author

aromaa commented Sep 27, 2023

This needs a bit updating to stub the new platforms and a bit of updating. I'm planning to do that in the future as I will be needing to update my devices soon for the new Azure certificate so the branch will be up to date after that.

@aromaa aromaa force-pushed the feature/device-public-key branch from 405b6c8 to 2e99008 Compare October 4, 2023 16:41
@aromaa
Copy link
Contributor Author

aromaa commented Oct 4, 2023

Actually there wasn't much else to do as the new platforms are already falling back to the existing stubs. Fixed few copy & paste mistakes. Still seems to work just fine on my ESP32.

@nfbot nfbot added the Type: dependencies Pull requests that update a dependency file(s) or version label Oct 4, 2023
@josesimoes josesimoes force-pushed the main branch 2 times, most recently from 02e0d18 to 591537f Compare December 7, 2023 01:59
@josesimoes josesimoes force-pushed the main branch 3 times, most recently from 288fd6f to c6dee33 Compare July 30, 2024 14:04
@josesimoes josesimoes force-pushed the main branch 3 times, most recently from f1c86c5 to 449142a Compare August 2, 2024 11:15
@aromaa aromaa force-pushed the feature/device-public-key branch from c7f5b09 to 1f3b8b8 Compare January 25, 2025 13:34
Copy link

coderabbitai bot commented Jan 25, 2025

Walkthrough

The pull request introduces a new method for retrieving a device's public key in raw byte array format across multiple system components. This change involves adding a new method GetDevicePublicKeyRaw to the CertificateManager class, updating version identifiers, and creating supporting infrastructure for public key extraction. The modifications span several files in the System.Net and SSL-related components, providing a mechanism to access raw public key data from device certificates.

Changes

File Change Summary
src/DeviceInterfaces/System.Net/sys_net_native.cpp - Added method handler for GetDevicePublicKeyRaw
- Updated assembly version identifier
- Incremented version info
src/DeviceInterfaces/System.Net/sys_net_native.h - Added method declaration for GetDevicePublicKeyRaw
- Removed multiple enum type declarations
src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp - Implemented GetDevicePublicKeyRaw method to retrieve device public key
src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager_stubs.cpp - Added stub implementation for GetDevicePublicKeyRaw
src/PAL/COM/sockets/ssl/ssl.cpp - Added SSL_GetPublicKeyRaw function for retrieving raw public key
src/PAL/Include/nanoPAL_Sockets.h - Added _X509RawData structure
- Added SSL_GetPublicKeyRaw function prototype
targets/AzureRTOS/ST/_common/drivers/wifi/inventek/ssl_ISM43362.cpp - Added ssl_get_public_key_raw_internal stub function
targets/TI_SimpleLink/_common/ssl_simplelink.cpp - Added ssl_get_public_key_raw_internal stub function

Sequence Diagram

sequenceDiagram
    participant CertificateManager
    participant SSL
    participant DeviceCertificate
    
    CertificateManager->>DeviceCertificate: GetDeviceCertificate()
    DeviceCertificate-->>CertificateManager: Return Certificate
    
    CertificateManager->>SSL: SSL_GetPublicKeyRaw(certificate)
    SSL->>SSL: Initialize SSL if needed
    SSL-->>CertificateManager: Extract Raw Public Key
    
    CertificateManager->>CertificateManager: Create Byte Array
    CertificateManager-->>CertificateManager: Return Public Key
Loading

Possibly related PRs

  • Fix protecting HB from GC #3062: The main PR introduces a new method for retrieving a device's public key, while PR Fix protecting HB from GC #3062 focuses on enhancing garbage collection handling related to data buffers. Both PRs involve modifications to methods that manage data, but they do not directly relate to the same functionality or code paths.

Suggested labels

Area: Common libs, Platform: Azure-RTOS, Platform: TI-SimpleLink


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 55abccd and 99f9df6.

📒 Files selected for processing (1)
  • src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ST_NUCLEO64_F091RC)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/PAL/COM/sockets/ssl/MbedTLS/ssl_parse_certificate_internal.cpp (1)

63-64: Add error logging for certificate parsing failures.

The function silently fails when certificate parsing fails. Consider adding error logging to help with debugging.

Apply this diff to add error logging:

     ret = mbedtls_x509_crt_parse(&cacert, (const unsigned char *)certificate, size);
     if (ret < 0)
     {
+        char error_buf[100];
+        mbedtls_strerror(ret, error_buf, sizeof(error_buf));
+        TRACE_ERROR("Certificate parsing failed: %s\n", error_buf);
         mbedtls_x509_crt_free(&cacert);
         return false;
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a912343 and 1f3b8b8.

📒 Files selected for processing (11)
  • src/DeviceInterfaces/System.Net/sys_net_native.cpp (2 hunks)
  • src/DeviceInterfaces/System.Net/sys_net_native.h (1 hunks)
  • src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp (1 hunks)
  • src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager_stubs.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_parse_certificate_internal.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/ssl.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/ssl_functions.h (1 hunks)
  • src/PAL/COM/sockets/ssl/ssl_stubs.cpp (1 hunks)
  • src/PAL/Include/nanoPAL_Sockets.h (2 hunks)
  • targets/AzureRTOS/ST/_common/drivers/wifi/inventek/ssl_ISM43362.cpp (3 hunks)
  • targets/TI_SimpleLink/_common/ssl_simplelink.cpp (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/DeviceInterfaces/System.Net/sys_net_native.h
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ST_NUCLEO64_F091RC)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (11)
src/PAL/COM/sockets/ssl/ssl.cpp (1)

87-97: LGTM!

The implementation follows the established pattern in the file and properly handles SSL initialization.

src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager_stubs.cpp (1)

18-26: LGTM!

The implementation follows the established pattern in the file and properly uses NotImplementedStub().

targets/AzureRTOS/ST/_common/drivers/wifi/inventek/ssl_ISM43362.cpp (2)

26-34: Implementation follows the established pattern for stub functions.

The stub implementation correctly follows the pattern used throughout the file for unsupported operations, properly handling unused parameters and providing a clear comment explaining the return value.


234-234: LGTM! Improved comment formatting.

The added space after // improves readability and maintains consistency with the codebase's comment style.

src/DeviceInterfaces/System.Net/sys_net_native.cpp (2)

198-199: LGTM! Method handler properly added to the lookup table.

The new method handler for GetDevicePublicKeyRaw is correctly placed in the method_lookup array.


350-352: Version numbers properly updated.

Version identifier and version info are correctly incremented to reflect the addition of new functionality.

targets/TI_SimpleLink/_common/ssl_simplelink.cpp (1)

34-42: LGTM! Implementation maintains cross-platform consistency.

The stub implementation matches the one in ssl_ISM43362.cpp, maintaining consistency across different platform implementations.

src/PAL/Include/nanoPAL_Sockets.h (2)

41-45: LGTM! Well-designed structure for raw certificate data.

The _X509RawData structure is properly designed with appropriate fields for handling raw certificate data:

  • len: Size of the raw data
  • p: Pointer to the raw data buffer

723-723: LGTM! Function declaration follows the API pattern.

The SSL_GetPublicKeyRaw function declaration properly follows the established API pattern with clear parameter names and appropriate types.

src/PAL/COM/sockets/ssl/ssl_functions.h (1)

39-39: LGTM! Verify function declaration consistency.

The new function declaration follows the established pattern and matches the implementation.

Let's verify the consistency of this function declaration across different implementations:

✅ Verification successful

Function declaration is consistent across all implementations

The ssl_get_public_key_raw_internal function signature matches perfectly in all platform-specific implementations (MbedTLS, Inventek WiFi, and TI SimpleLink), with consistent parameter types, order, and return type.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all implementations of ssl_get_public_key_raw_internal
rg -l "ssl_get_public_key_raw_internal" | grep -v "ssl_functions.h"

Length of output: 281


Script:

#!/bin/bash
# Check implementations of ssl_get_public_key_raw_internal
echo "=== Main SSL Implementation ==="
rg "ssl_get_public_key_raw_internal" "src/PAL/COM/sockets/ssl/ssl.cpp" -A 2

echo -e "\n=== MbedTLS Implementation ==="
rg "ssl_get_public_key_raw_internal" "src/PAL/COM/sockets/ssl/MbedTLS/ssl_parse_certificate_internal.cpp" -A 2

echo -e "\n=== Inventek WiFi Implementation ==="
rg "ssl_get_public_key_raw_internal" "targets/AzureRTOS/ST/_common/drivers/wifi/inventek/ssl_ISM43362.cpp" -A 2

echo -e "\n=== TI SimpleLink Implementation ==="
rg "ssl_get_public_key_raw_internal" "targets/TI_SimpleLink/_common/ssl_simplelink.cpp" -A 2

Length of output: 1148

src/PAL/COM/sockets/ssl/MbedTLS/ssl_parse_certificate_internal.cpp (1)

55-78: Add unit tests for the new functionality.

Ensure comprehensive test coverage for the new public key extraction functionality.

Let's check for existing tests:

Would you like me to help create unit tests for this new functionality?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp (2)

94-114: Optimize success path and error handling.

The nested if conditions can be flattened for better readability and error handling.

Apply this diff to optimize the code structure:

-    if (deviceCert)
+    X509RawData rawData;
+    bool success = SSL_GetPublicKeyRaw((const char *)deviceCert->Certificate, deviceCert->CertificateSize, &rawData);
+    
+    // Free device cert as soon as possible
+    platform_free(deviceCert);
+    
+    if (success)
     {
-        X509RawData rawData;
-        bool success = SSL_GetPublicKeyRaw((const char *)deviceCert->Certificate, deviceCert->CertificateSize, &rawData);
+        CLR_RT_HeapBlock_Array *array;
-        platform_free(deviceCert);
+        NANOCLR_CHECK_HRESULT(
+            CLR_RT_HeapBlock_Array::CreateInstance(ret, rawData.len, g_CLR_RT_WellKnownTypes.m_UInt8));
-        if (success)
-        {
-            CLR_RT_HeapBlock_Array *array;
+        array = ret.DereferenceArray();
+        memcpy(array->GetFirstElement(), rawData.p, rawData.len);
+        platform_free(rawData.p);
+    }
-            NANOCLR_CHECK_HRESULT(
-                CLR_RT_HeapBlock_Array::CreateInstance(ret, rawData.len, g_CLR_RT_WellKnownTypes.m_UInt8));
-
-            array = ret.DereferenceArray();
-
-            memcpy(array->GetFirstElement(), rawData.p, rawData.len);
-
-            platform_free(rawData.p);
-        }
-    }

116-116: Update cleanup macro to match error handling.

Since we're not using any cleanup labels, use NANOCLR_NOCLEANUP_NOLABEL() instead.

Apply this diff:

-    NANOCLR_NOCLEANUP();
+    NANOCLR_NOCLEANUP_NOLABEL();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1f3b8b8 and 55abccd.

📒 Files selected for processing (2)
  • src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_parse_certificate_internal.cpp (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ST_NUCLEO64_F091RC)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALX)
  • GitHub Check: nf-interpreter (Nightly build) (Build_STM32_targets ORGPAL_PALTHREE)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (3)
src/PAL/COM/sockets/ssl/MbedTLS/ssl_parse_certificate_internal.cpp (2)

70-79: ⚠️ Potential issue

Add bounds checking and document memory ownership.

The implementation needs:

  1. Size validation before allocation
  2. Documentation about memory ownership

Apply this diff to add size validation and documentation:

+    // Validate certificate size before allocation
+    if (cacert.raw.len == 0 || cacert.raw.len > MAX_CERTIFICATE_SIZE)
+    {
+        mbedtls_x509_crt_free(&cacert);
+        return false;
+    }
+
     x509->len = cacert.raw.len;
+    // Note: Caller takes ownership of the allocated memory and must free it using platform_free
     x509->p = (unsigned char *)platform_malloc(x509->len);
     if (x509->p == NULL)
     {
         mbedtls_x509_crt_free(&cacert);
         return false;
     }

     memcpy(x509->p, cacert.raw.p, x509->len);

Likely invalid or redundant comment.


55-58: ⚠️ Potential issue

Add input parameter validation.

The function should validate input parameters before proceeding with operations.

Apply this diff to add parameter validation:

 bool ssl_get_public_key_raw_internal(void *certificate, size_t size, void *x509RawData)
 {
     int ret;
+    if (certificate == NULL || x509RawData == NULL || size == 0)
+    {
+        return false;
+    }
+
     X509RawData *x509 = (X509RawData *)x509RawData;

Likely invalid or redundant comment.

src/DeviceInterfaces/System.Net/sys_net_native_System_Net_Security_CertificateManager.cpp (1)

91-93: ⚠️ Potential issue

Add error handling for device certificate retrieval.

The code should validate the device certificate retrieval result using FAULT_ON_NULL.

Apply this diff to add proper error handling:

     CLR_RT_HeapBlock &ret = stack.PushValueAndClear();
     HAL_Configuration_X509DeviceCertificate *deviceCert = ConfigurationManager_GetDeviceCertificate();
+    FAULT_ON_NULL(deviceCert);

Likely invalid or redundant comment.

@aromaa
Copy link
Contributor Author

aromaa commented Jan 25, 2025

Rebased and updated the System.Net native bindings. Everything seems to still work just fine on my ESP32.

@josesimoes josesimoes force-pushed the main branch 2 times, most recently from eeab92b to 1da6e94 Compare January 30, 2025 11:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: dependencies Pull requests that update a dependency file(s) or version Type: enhancement
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants