Skip to content

Fix handling of own certificate in SSL context #3140

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

Merged
merged 1 commit into from
Apr 4, 2025

Conversation

josesimoes
Copy link
Member

@josesimoes josesimoes commented Apr 1, 2025

Description

  • Rename CA cert element in SSL context (for clarity).
  • Add new element for own certificate.
  • Update code to use new element in context instead of local variable.
  • Add code to free memory of own certificate.
  • Update comments in HAL_Configuration_X509DeviceCertificate to match intend usage.

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/declarations (update dependencies or assembly declarations 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

  • Refactor
    • Improved certificate handling by clearly distinguishing between device and authority certificates.
    • Enhanced memory management and error handling during secure communication processes to prevent resource issues.

@josesimoes josesimoes added the Area: Common libs Everything related with common libraries label Apr 1, 2025
@nfbot nfbot added the Type: bug label Apr 1, 2025
Copy link

coderabbitai bot commented Apr 1, 2025

Walkthrough

This pull request updates the handling of X.509 device certificates. The comments in the device certificate structure were revised to better reflect their purpose. In the MbedTLS files, the certificate management has been refactored by replacing a single certificate pointer with two distinct members (ca_cert and own_cert), and all relevant references have been updated in initialization, parsing, configuration, and cleanup routines. Memory deallocation now includes null checks for improved safety.

Changes

Files Change Summary
src/HAL/Include/nanoHAL_Network.h Updated comments in HAL_Configuration_X509DeviceCertificate to indicate the fields refer to device certificates rather than CA Root certificates.
src/PAL/COM/sockets/ssl/MbedTLS/mbedtls.h, ssl_add_cert_auth_internal.cpp, ssl_exit_context_internal.cpp, ssl_generic_init_internal.cpp Refactored certificate management in mbedTLS_NFContext: removed x509_crt and added ca_cert and own_cert. Updated certificate parsing, configuration, and cleanup functions to use the new members with enhanced memory deallocation checks.

Sequence Diagram(s)

sequenceDiagram
    participant Init as ssl_generic_init_internal
    participant Parse as ssl_add_cert_auth_internal
    participant Cleanup as ssl_exit_context_internal

    Init->>Parse: Allocate and assign ca_cert and own_cert
    Parse->>Parse: Parse certificate using ca_cert
    Parse->>Init: Return updated SSL context
    Cleanup->>Cleanup: Check for non-null pointers (ca_cert, own_cert, etc.)
    Cleanup->>Cleanup: Free ca_cert and own_cert safely
Loading

Assessment against linked issues

Objective Addressed Explanation
Ensure that SSL context resources, including certificate memory, are freed correctly (#1619)

📜 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 bac1a78 and 57a24b3.

📒 Files selected for processing (5)
  • src/HAL/Include/nanoHAL_Network.h (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/mbedtls.h (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_add_cert_auth_internal.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_exit_context_internal.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_generic_init_internal.cpp (8 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_add_cert_auth_internal.cpp
  • src/HAL/Include/nanoHAL_Network.h
  • src/PAL/COM/sockets/ssl/MbedTLS/mbedtls.h
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_exit_context_internal.cpp
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_generic_init_internal.cpp
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: nf-interpreter (Check_Code_Style)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@josesimoes josesimoes requested a review from AdrianSoundy April 1, 2025 23:52
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ba3a86 and bac1a78.

📒 Files selected for processing (5)
  • src/HAL/Include/nanoHAL_Network.h (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/mbedtls.h (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_add_cert_auth_internal.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_exit_context_internal.cpp (1 hunks)
  • src/PAL/COM/sockets/ssl/MbedTLS/ssl_generic_init_internal.cpp (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: nf-interpreter (Nightly build) (Check_Build_Options)
  • GitHub Check: nf-interpreter (Check_Build_Options)
🔇 Additional comments (14)
src/HAL/Include/nanoHAL_Network.h (2)

303-303: Improved clarity in certificate documentation

The comment change better reflects that this structure is for a device certificate, which aligns with its actual usage. This enhances code readability and reduces potential confusion.


306-306: Consistent terminology for certificate documentation

This comment update maintains consistency with the field name change above, properly identifying this as a device certificate rather than a CA root certificate bundle.

src/PAL/COM/sockets/ssl/MbedTLS/ssl_add_cert_auth_internal.cpp (2)

30-30: Updated certificate reference to use new structure member

The change from context->x509_crt to context->ca_cert properly reflects the structure update in mbedtls.h and improves code clarity by explicitly indicating this is a CA certificate.


33-33: Consistent use of new certificate member name

This update ensures consistency with the structural changes made to the SSL context, correctly using the CA certificate member for the certificate chain configuration.

src/PAL/COM/sockets/ssl/MbedTLS/mbedtls.h (1)

37-38: Enhanced certificate management with explicit member types

Splitting the single certificate pointer into separate CA certificate and own certificate pointers improves code clarity and aligns with the PR objective to better handle the device's own certificate.

This change:

  1. Makes the code's intent clearer
  2. Properly separates concerns between CA certificates and device certificates
  3. Provides a more maintainable structure for certificate handling
src/PAL/COM/sockets/ssl/MbedTLS/ssl_exit_context_internal.cpp (2)

33-34: Proper cleanup for both certificate types

Adding a separate call to free the device's own certificate ensures proper resource management and prevents memory leaks. This is a necessary change to support the new certificate structure.


41-84: Enhanced memory safety with null checks

Adding null checks before freeing memory is an excellent improvement that prevents potential crashes when attempting to free NULL pointers. This defensive programming approach is particularly important in embedded systems.

The code now safely:

  • Checks each pointer before freeing
  • Handles the new certificate members properly
  • Maintains a consistent pattern for all resource cleanup
src/PAL/COM/sockets/ssl/MbedTLS/ssl_generic_init_internal.cpp (7)

133-138: Variable renaming improves clarity

Renaming from x509_crt to ca_cert makes the purpose of this certificate clearer, differentiating it from the user's own certificate. This aligns well with the PR objective to enhance clarity in certificate handling.


215-215: Good practice: NULL assignment after free

Setting the pointer to NULL after freeing helps prevent potential use-after-free issues and makes debugging easier by ensuring invalid memory accesses would be null pointer dereferences rather than accessing freed memory.


263-273: Improved certificate management through context structure

This change properly allocates and initializes the user's own certificate directly within the context structure rather than using a local variable. This approach is more maintainable as it keeps all related certificate data together and ensures proper cleanup through the context's lifecycle.


289-289: Good practice: NULL assignment after free

Setting deviceCert to NULL after freeing it prevents potential use-after-free issues if the pointer is accidentally used later in the function.


300-300: Updated function call with renamed certificate variable

Function call has been correctly updated to use the renamed ca_cert variable, maintaining consistency with the earlier variable renaming.


349-350: Memory management for both certificate types

The code now properly frees both types of certificates (ca_cert and own_cert) in the error handling path, which prevents memory leaks.


380-388: Improved error handling with NULL checks

The error handling has been enhanced to check for NULL before freeing both certificate types, which is a good defensive programming practice to prevent null pointer dereferences.

- Rename CA cert element in SSL context (for clarity).
- Add new element for own certificate.
- Update code to use new element in context instead of local variable.
- Add code to free memory of own certificate.
- Update comments in HAL_Configuration_X509DeviceCertificate to match intend usage.
Copy link
Member

@Ellerbach Ellerbach left a comment

Choose a reason for hiding this comment

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

looks good!

@networkfusion
Copy link
Member

My only comment is that own certificate is not self (context) descriptive enough.

@josesimoes
Copy link
Member Author

My only comment is that own certificate is not self (context) descriptive enough.

For the naming I've followed the hint of mbedTLS API mbedtls_ssl_conf_own_cert() name in order to make it clear on what was the variable and the intention to use when calling it. What would you suggest?

@josesimoes
Copy link
Member Author

@networkfusion any follow-up on the above, or OK to merge?

@networkfusion
Copy link
Member

@networkfusion any follow-up on the above, or OK to merge?

OK to merge 👍

@josesimoes josesimoes merged commit 75ce2fd into nanoframework:main Apr 4, 2025
25 checks passed
@josesimoes josesimoes deleted the fix-1619 branch April 4, 2025 10:49
TerryFogg pushed a commit to TerryFogg/nf-interpreter that referenced this pull request Apr 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Area: Common libs Everything related with common libraries Type: bug
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Memory not correctly freed after an SSL request on ESP32_S3
4 participants