Skip to content

FIDO supports BLE communication.#244

Merged
lihuanhuan merged 3 commits intoOneKeyHQ:mainfrom
lihuanhuan:pro_main
Feb 10, 2025
Merged

FIDO supports BLE communication.#244
lihuanhuan merged 3 commits intoOneKeyHQ:mainfrom
lihuanhuan:pro_main

Conversation

@lihuanhuan
Copy link
Copy Markdown
Contributor

@lihuanhuan lihuanhuan commented Feb 10, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced communication protocols by integrating advanced SPI and UART functionality.
    • Expanded FIDO2 authentication support to operate over multiple interfaces, boosting device interoperability.
    • Introduced dedicated memory regions for DMA operations, improving performance.
  • Refactor
    • Optimized memory management with dedicated buffers and improved interrupt handling for better responsiveness.
    • Revised configuration parameters, including credential length adjustments and updated interface identifiers.
    • Removed obsolete handlers and legacy interface checks to streamline system performance.

@lihuanhuan lihuanhuan requested a review from a team as a code owner February 10, 2025 03:02
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 10, 2025

Walkthrough

The pull request adds new source files and updates build scripts to include additional HAL and interrupt handlers. It introduces SRAM3 memory regions in linker scripts for DMA use. Several modules update SPI communication, including redefining interface constants and timeouts, adding DMA buffers, and revising callback and polling logic. Some obsolete interrupt handlers are removed and replaced with updated implementations. Changes also adjust UART DMA handling and update webauthn command handling to support both HID and SPI interfaces. Additionally, SPI configuration in utility code is revised.

Changes

File(s) Change Summary
core/SConscript.(bootloader, firmware) Added stm32h7xx_hal_exti.c to SOURCE_STMHAL; bootloader adds stm32_it_handler.c to SOURCE_TREZORHAL.
core/embed/.../memory*.ld Added SRAM3 region (0x30040000, 32K) and .sram3 section for DMA use.
core/embed/extmod/modtrezorio/* Updated SPI polling and write logic: SPI_IFACE changed from 6 to 100, added SPI_FIDO_IFACE (101); removed usb_connected_previously and added SPI_FACE identifiers.
core/embed/fp_sensor_wrapper/fpsensor_platform.c Removed EXTI15_10_IRQHandler; modified IRQ enable/disable to reset fp_touched flag.
core/embed/trezorhal/gt911.c Removed EXTI2_IRQHandler for touch panel.
core/embed/trezorhal/spi_legacy.[c,h] Refactored SPI communication with DMA buffers, new polling (spi_slave_poll_fido) and spi_cs_irq_handler functions; updated callbacks and state management; removed legacy DMA definitions.
core/embed/trezorhal/stm32_it_handler.c Added conditional compilation and extended EXTI callbacks to handle GPIO_PIN_11 via spi_cs_irq_handler.
core/embed/trezorhal/usart.c Added DMA support for UART; updated send/receive functions; introduced Tx/Rx complete callbacks.
core/src/apps/webauthn/* Modified imports and handle_reports call (init.py), reduced CRED_ID_MAX_LENGTH (credential.py), and updated FIDO2 command handling to support HID and SPI (fido2.py).
core/src/trezor/(utils.py, wire/init.py) Replaced SPI_IFACE_NUM with io.SPI_FACE; updated imports and SPI interface checks.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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
Copy Markdown

@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: 12

🧹 Nitpick comments (3)
core/embed/trezorhal/stm32_it_handler.c (1)

12-13: Comment needs more detail.

"fp sensor irq" is too vague.

-  // fp sensor irq
+  // Handle fingerprint sensor interrupt on GPIO_PIN_15
core/embed/trezorhal/spi_legacy.h (1)

13-17: Inconsistent macro naming.

SET_COMBUS vs ST_BLE_STATUS

-#define SET_COMBUS_HIGH()       HAL_GPIO_WritePin(GPIOK, GPIO_PIN_6, GPIO_PIN_SET)
-#define SET_COMBUS_LOW()        HAL_GPIO_WritePin(GPIOK, GPIO_PIN_6, GPIO_PIN_RESET)
+#define ST_BLE_COMBUS_HIGH()    HAL_GPIO_WritePin(GPIOK, GPIO_PIN_6, GPIO_PIN_SET)
+#define ST_BLE_COMBUS_LOW()     HAL_GPIO_WritePin(GPIOK, GPIO_PIN_6, GPIO_PIN_RESET)
core/embed/bootloader/memory.ld (1)

9-10: Fix comment style.

Use single-line comments to match file style.

-  /* SRAM3 is used for DMA */
+  // SRAM3 is used for DMA
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 34ee09e and 51802c1.

⛔ Files ignored due to path filters (1)
  • core/mocks/generated/trezorio/__init__.pyi is excluded by !**/generated/**
📒 Files selected for processing (18)
  • core/SConscript.bootloader (2 hunks)
  • core/SConscript.firmware (1 hunks)
  • core/embed/bootloader/memory.ld (2 hunks)
  • core/embed/extmod/modtrezorio/modtrezorio-poll.h (4 hunks)
  • core/embed/extmod/modtrezorio/modtrezorio-spi.h (1 hunks)
  • core/embed/extmod/modtrezorio/modtrezorio.c (2 hunks)
  • core/embed/firmware/memory_H.ld (2 hunks)
  • core/embed/fp_sensor_wrapper/fpsensor_platform.c (0 hunks)
  • core/embed/trezorhal/gt911.c (0 hunks)
  • core/embed/trezorhal/spi_legacy.c (11 hunks)
  • core/embed/trezorhal/spi_legacy.h (2 hunks)
  • core/embed/trezorhal/stm32_it_handler.c (2 hunks)
  • core/embed/trezorhal/usart.c (7 hunks)
  • core/src/apps/webauthn/__init__.py (1 hunks)
  • core/src/apps/webauthn/credential.py (1 hunks)
  • core/src/apps/webauthn/fido2.py (25 hunks)
  • core/src/trezor/utils.py (2 hunks)
  • core/src/trezor/wire/__init__.py (2 hunks)
💤 Files with no reviewable changes (2)
  • core/embed/trezorhal/gt911.c
  • core/embed/fp_sensor_wrapper/fpsensor_platform.c
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Style check
  • GitHub Check: Defs check
  • GitHub Check: Gen check
🔇 Additional comments (12)
core/embed/firmware/memory_H.ld (2)

12-13: LGTM! Well-documented DMA memory region.


85-88: LGTM! Properly aligned section definition.

core/embed/extmod/modtrezorio/modtrezorio.c (2)

83-84: LGTM! Clear interface separation.


138-139: LGTM! Consistent interface mapping.

core/embed/extmod/modtrezorio/modtrezorio-poll.h (3)

39-40: LGTM! Clear interface numbering.


206-206: LGTM! Unified write handling for both interfaces.


184-184: Verify if 1024 bytes buffer is sufficient for FIDO/BLE operations.

✅ Verification successful

🌐 Web query:

What is the maximum packet size for FIDO2 over BLE?

💡 Result:

The maximum packet size for **FIDO2 over BLE** depends on protocol configurations and Bluetooth versions:

### Key Specifications
1. **Maximum ATT MTU**  
   - **512 bytes** is the theoretical upper limit for ATT (Attribute Protocol) MTU defined in Bluetooth specifications[3][5][8].  
   - Android supports up to **517 bytes** for ATT MTU[4], but FIDO2 implementations cap this at **512 bytes**[3][8].

2. **Data Length Extension (BLE 4.2+)**  
   - Increases payload capacity per packet from 27 bytes (pre-4.2) to **251 bytes** for data channel PDUs[4][6].  
   - Combined with larger MTUs, this reduces overhead and improves throughput[4][6].

3. **FIDO-Specific Fragmentation**  
   - FIDO2/BLE splits large messages into fragments due to inherent BLE limitations[8][10].  
   - Example: A 400-byte payload is transmitted in one frame if `maxLen` (negotiated MTU) is 512 bytes[8].

### Practical Limits
| Layer/Feature | Maximum Payload | Notes |
|---------------|-----------------|-------|
| **ATT MTU** | 512 bytes | Enforced by FIDO specs[3][5][8] |
| **Data Channel PDU (with DLE)** | 251 bytes | Requires Bluetooth 4.2+[4][6] |
| **Application Data per Packet** | ~244–507 bytes | After subtracting headers (L2CAP/ATT)[4][6] |

### Implementation Notes
- **MTU Negotiation**: FIDO2 clients should request the maximum supported MTU (up to 512 bytes)[3][5].  
- **Fragmentation**: Packets exceeding `maxLen` are split into initialization/continuation fragments[8][10].  
- **Throughput**: Using larger MTUs and DLE improves speed and reduces power consumption[4].

For example:  
- A 400-byte payload with a negotiated MTU of 512 is sent in one fragment[8].  
- Smaller MTUs (e.g., default 23 bytes) require splitting data into multiple packets[6].

In summary, while BLE’s physical layer limits per-packet payloads to ~251 bytes with DLE, FIDO2’s use of large MTUs allows application-layer payloads up to **512 bytes**[3][5][8].

Citations:

- 1: https://en.wikipedia.org/wiki/Bluetooth_Low_Energy
- 2: https://developerhelp.microchip.com/xwiki/bin/view/applications/ble/introduction/bluetooth-architecture/bluetooth-controller-layer/bluetooth-link-layer/Packet-Types/
- 3: https://fidoalliance.org/specs/fido-u2f-bt-protocol-id-20150514.pdf
- 4: https://punchthrough.com/ble-throughput-part-4/
- 5: https://fidoalliance.org/specs/u2f-specs-master/fido-u2f-bt-protocol.html
- 6: https://community.renesas.com/wireles-connectivity/f/bluetooth-low-energy/25075/maximum-payload-for-gatt-services
- 7: https://duo.com/blog/webauthn-passwordless-fido2-explained-componens-passwordless-architecture
- 8: https://fidoalliance.org/specs/u2f-specs-1.0-bt-nfc-id-amendment/fido-u2f-bt-protocol.html
- 9: https://e2e.ti.com/support/wireless-connectivity/bluetooth-group/bluetooth/f/bluetooth-forum/108807/max-packet-size-allowed-for-ble-communication
- 10: https://fidoalliance.org/specs/fido-u2f-v1.2-ps-20170411/fido-u2f-bt-protocol-v1.2-ps-20170411.html

Buffer Check: Sufficient

  • FIDO2 over BLE uses a maximum packet size of 512 bytes.
  • The 1024-byte buffer can hold two full packets.
core/SConscript.bootloader (1)

90-90: LGTM!

The additions of HAL and interrupt handler files are properly conditioned and support BLE communication.

Also applies to: 227-227

core/src/trezor/utils.py (1)

125-125: LGTM!

The SPI interface handling is properly standardized using the io module.

Also applies to: 223-223

core/src/trezor/wire/__init__.py (1)

380-380: LGTM!

The SPI interface check is properly updated to use io.SPI_FACE.

core/SConscript.firmware (1)

412-412: LGTM!

The addition of the EXTI HAL driver is appropriate for BLE support.

core/src/apps/webauthn/__init__.py (1)

1-10: LGTM! Clean and focused changes.

The modifications effectively add SPI interface support while maintaining code clarity and organization.

Copy link
Copy Markdown

@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: 3

♻️ Duplicate comments (5)
core/embed/trezorhal/usart.c (3)

91-91: ⚠️ Potential issue

Missing error checks after DMA initialization.

-  HAL_DMA_Init(&hdma_tx);
+  if (HAL_DMA_Init(&hdma_tx) != HAL_OK) {
+    ensure(secfalse, "DMA TX init failed");
+  }

-  HAL_DMA_Init(&hdma_rx);
+  if (HAL_DMA_Init(&hdma_rx) != HAL_OK) {
+    ensure(secfalse, "DMA RX init failed");
+  }

Also applies to: 107-107


144-158: ⚠️ Potential issue

Data loss on timeout.

   if (HAL_GetTick() - start > 500) {
+    HAL_UART_Abort(huart);
+    HAL_UART_Receive_DMA(huart, dma_uart_rev_buf, sizeof(dma_uart_rev_buf));
     return;
   }

206-240: ⚠️ Potential issue

Buffer overflow risk in packet parsing.

   while (len > 0) {
+    if (index >= len) {
+      return;
+    }
     if (buf[index] != 0xA5 || buf[index + 1] != 0x5A) {
core/embed/trezorhal/spi_legacy.c (2)

241-253: ⚠️ Potential issue

Missing EXTI error check.

-  HAL_EXTI_SetConfigLine(&hexti, &pExtiConfig);
+  if (HAL_EXTI_SetConfigLine(&hexti, &pExtiConfig) != HAL_OK) {
+    return -1;
+  }

424-444: ⚠️ Potential issue

Missing error handling for buffer overflow.

-  fifo_write_no_overflow(&spi_fifo_in, dma_recv_buf, recv_len);
+  if (!fifo_write_no_overflow(&spi_fifo_in, dma_recv_buf, recv_len)) {
+    // Handle overflow error
+    HAL_SPI_Abort(&spi);
+  }
🧹 Nitpick comments (3)
core/embed/trezorhal/spi_legacy.h (1)

16-17: Fix inconsistent abbreviation in macro names.

ST_BLE_STATUS_IO uses mixed abbreviation styles. Either use STATUS or ST consistently.

core/src/apps/webauthn/fido2.py (1)

2174-2181: Improve error message.

"Invalid interface type" is too vague.

core/embed/trezorhal/spi_legacy.c (1)

308-349: Define packet format constants.

+#define FIDO_MAGIC "fid"
+#define STANDARD_MAGIC '?'
+#define FIDO_HEADER_SIZE 3
+#define FIDO_LENGTH_SIZE 2

-  if (memcmp(header, "fid", 3) == 0)
+  if (memcmp(header, FIDO_MAGIC, FIDO_HEADER_SIZE) == 0)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 51802c1 and 23725a6.

⛔ Files ignored due to path filters (1)
  • core/mocks/generated/trezorio/__init__.pyi is excluded by !**/generated/**
📒 Files selected for processing (18)
  • core/SConscript.bootloader (2 hunks)
  • core/SConscript.firmware (1 hunks)
  • core/embed/bootloader/memory.ld (2 hunks)
  • core/embed/extmod/modtrezorio/modtrezorio-poll.h (4 hunks)
  • core/embed/extmod/modtrezorio/modtrezorio-spi.h (1 hunks)
  • core/embed/extmod/modtrezorio/modtrezorio.c (2 hunks)
  • core/embed/firmware/memory_H.ld (2 hunks)
  • core/embed/fp_sensor_wrapper/fpsensor_platform.c (0 hunks)
  • core/embed/trezorhal/gt911.c (0 hunks)
  • core/embed/trezorhal/spi_legacy.c (11 hunks)
  • core/embed/trezorhal/spi_legacy.h (2 hunks)
  • core/embed/trezorhal/stm32_it_handler.c (2 hunks)
  • core/embed/trezorhal/usart.c (7 hunks)
  • core/src/apps/webauthn/__init__.py (1 hunks)
  • core/src/apps/webauthn/credential.py (1 hunks)
  • core/src/apps/webauthn/fido2.py (25 hunks)
  • core/src/trezor/utils.py (2 hunks)
  • core/src/trezor/wire/__init__.py (2 hunks)
💤 Files with no reviewable changes (2)
  • core/embed/trezorhal/gt911.c
  • core/embed/fp_sensor_wrapper/fpsensor_platform.c
🚧 Files skipped from review as they are similar to previous changes (11)
  • core/embed/extmod/modtrezorio/modtrezorio-spi.h
  • core/src/apps/webauthn/init.py
  • core/src/trezor/wire/init.py
  • core/src/apps/webauthn/credential.py
  • core/embed/firmware/memory_H.ld
  • core/SConscript.bootloader
  • core/src/trezor/utils.py
  • core/embed/bootloader/memory.ld
  • core/embed/trezorhal/stm32_it_handler.c
  • core/embed/extmod/modtrezorio/modtrezorio-poll.h
  • core/SConscript.firmware
👮 Files not reviewed due to content moderation or server errors (1)
  • core/embed/extmod/modtrezorio/modtrezorio.c
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Gen check
  • GitHub Check: Defs check
  • GitHub Check: Style check

@lihuanhuan lihuanhuan merged commit 8dcc0d7 into OneKeyHQ:main Feb 10, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants