Monitor Mode in ARM Architecture (Context Switching - Monitor Mode and Secure World) (Part 4)

Monitor Mode in ARM Architecture (Context Switching - Monitor Mode and Secure World) (Part 4)

Reproduced from: https://2wisebit.wordpress.com/2025/01/09/monitor-mode-in-arm-architecture-context-switching-monitor-mode-and-secure-world-part-4/

In the world of ARM TrustZone, Monitor Mode is the critical gatekeeper that carefully manages transitions between the Secure World and the Normal World. This mechanism is important for ensuring system security as only authorized transitions are allowed. When entering from the Normal World into Monitor Mode, the process is strictly controlled and often triggered by specific events such as interrupts or SMCs (secure monitor calls). In contrast, entry from the Secure World is more flexible but remains secure and allows direct manipulation of the processor state. Processor's state is carefully saved and restores so that the system's security configuration registers, such as the Secure Configuration Register (SCR), are appropriately updated. The robust checks that should prevent unauthorized access to the system involve checking trigger sources and sanitization of inputs. Implementation of these is important because one weakness can cause vulnerability and access.

3. Secure World to Monitor Mode

Entry into Monitor Mode from the Secure World is more flexible and can be initiated through exceptions or direct manipulation of the processor state.

Conditions for Entry:

  1. Exceptions: a. Interrupts (IRQ/FIQ: Any interrupt has the capability of moving the processor out of the Secure World and into Monitor Mode to initiate a switch in mode.) b. External Aborts: Memory violations or errors in Secure World can push the processor out of the Secure World and into Monitor Mode for its own secure resolution
  2. Direct Manipulation of CPSR: The Secure World can natively control the CPSR in order to switch to Monitor Mode, which is done for particular secure operations or context switches.

Security Considerations: Although more flexible, transitions from the Secure World to Monitor Mode still adhere to strict security policies. Monitor Mode validates the requested transition to prevent unintended behavior or system corruption.

Process of Entry:

  1. Context Saving: The processor saves the current context of the Secure World, including: General-Purpose Registers (R0-R12):?Saved to preserve the working data. Stack Pointer (SP):?Saved to ensure the correct stack is used when returning to the Secure World. Program Counter (PC):?Saved to resume execution at the correct point after the transition. CPSR (Current Program Status Register):?Saved to capture the processor's current state (mode, interrupt status, condition flags).
  2. Update of Security State: The?Secure Configuration Register (SCR)?is updated to reflect the transition to Monitor Mode. The?NS (Non-secure) bit?remains 0, as the processor is already in a Secure state. Before updating the SCR, Monitor Mode validates the requested transition to ensure it adheres to the system’s security policies. Invalid transitions are rejected, and the processor may generate an error or fault. The SCR also includes additional fields that may control specific behaviors during the transition: IRQ/FIQ Control: Determines whether interrupts are enabled or disabled after the switch. Secure Access Permissions: Configures access permissions for memory or peripherals.
  3. Exception Handling: If the entry was triggered by an exception (e.g., interrupt or abort), the exception state is saved, and the processor switches to Monitor Mode to handle the exception securely.
  4. Execution in Monitor Mode: The processor begins executing the Monitor Mode handler, which manages the transition to the Normal World or handles the exception.


+-----------------------------+
|       Context Saving        |
|-----------------------------|
| - Save General-Purpose      |
|   Registers (R0-R12)        |
| - Save Stack Pointer (SP)   |
| - Save Program Counter (PC) |
| - Save CPSR                 |
+-----------------------------+
               |
               v
+-----------------------------+
|   Update of Security State  |
|-----------------------------|
| - Update Secure Config      |
|   Register (SCR)            |
| - NS bit remains 0 (Secure) |
+-----------------------------+
               |
               v
+-----------------------------+
|     Exception Handling      |
|-----------------------------|
| - Save exception state      |
| - Switch to Monitor Mode    |
|   for secure handling       |
+-----------------------------+
               |
               v
+-----------------------------+
| Execution in Monitor Mode   |
|-----------------------------|
| - Execute Monitor Mode      |
|   handler                   |
| - Manage transition to      |
|   Normal World or handle    |
|   exception                 |
+-----------------------------+        

4. Exit from Monitor Mode to Secure World

Exiting Monitor Mode to the Secure World involves restoring the Secure state context and ensuring that the Secure world resumes execution securely.

  1. Restoration of Secure Context: The processor restores the saved context of the Secure state, including: General-Purpose Registers (R0-R12):?Restored to their values before entering Monitor Mode. Stack Pointer (SP):?The Secure stack pointer is restored to ensure the correct stack is used. Program Counter (PC):?The saved PC value is restored to resume execution at the point where the transition to Monitor Mode occurred. CPSR (Current Program Status Register):?The saved CPSR is restored to reinstate the processor's mode, interrupt status, and condition flags.
  2. Update of Security State: The?Secure Configuration Register (SCR)?is updated to set the?NS (Non-secure) bit?to 0, indicating that the processor is transitioning to the Secure state. The?SPSR_mon (Saved Program Status Register for Monitor Mode)?is used to restore the CPSR of the Secure state.
  3. Memory Partitioning: The?MMU?or?MPU?is reconfigured to enforce Secure memory access permissions. Non-secure memory regions may be restricted depending on the system's configuration.
  4. Exception Handling: If the entry into Monitor Mode was triggered by an exception (e.g., interrupt or abort), the exception state is cleared, and the processor resumes normal execution in the Secure state.
  5. Execution Resume: The processor exits Monitor Mode and resumes execution in the Secure state at the point indicated by the restored PC.


+-----------------------------+
|      Restoration of         |
|      Secure Context         |
|-----------------------------|
| - Restore General-Purpose   |
|   Registers (R0-R12)        |
| - Restore Stack Pointer (SP)|
| - Restore Program Counter   |
|   (PC)                      |
| - Restore CPSR              |
+-----------------------------+
               |
               v
+-----------------------------+
|   Update of Security State  |
|-----------------------------|
| - Update SCR to set NS bit  |
|   to 0 (Secure state)       |
| - Restore CPSR using        |
|   SPSR_mon                  |
+-----------------------------+
               |
               v
+-----------------------------+
|   Memory Partitioning       |
|-----------------------------|
| - Reconfigure MMU/MPU to    |
|   enforce Secure memory     |
|   access permissions        |
| - Restrict Non-secure memory|
|   regions if required       |
+-----------------------------+
               |
               v
+-----------------------------+
|     Exception Handling      |
|-----------------------------|
| - Clear exception state if  |
|   triggered by an exception |
|   (e.g., interrupt or abort)|
+-----------------------------+
               |
               v
+-----------------------------+
|     Execution Resume        |
|-----------------------------|
| - Exit Monitor Mode         |
| - Resume execution in Secure|
|   state at restored PC      |
+-----------------------------+        

Key Differences Between Normal and Secure World Entry

--------------------------------------------------------
| Aspect          | Normal World Entry                 |
|-----------------|------------------------------------|
| Triggers        | Interrupts, External Aborts, SMC   |
|                 | Instruction                        |
| Flexibility     | Strictly controlled                |
| Security Checks | Rigorously enforced to prevent     |
|                 | unauthorized access                |
| Primary Use Case| Requesting secure services,        |
|                 | handling exceptions                |
|                 |                                    |
| Aspect          | Secure World Entry                 |
|-----------------|------------------------------------|
| Triggers        | Interrupts, External Aborts, CPSR  |
|                 | Manipulation                       |
| Flexibility     | More flexible                      |
| Security Checks | Assumes a trusted environment, but |
|                 | checks still apply                 |
| Primary Use Case| Managing Secure World state or     |
|                 | handling exceptions                |
--------------------------------------------------------        
+-------------------+-----------------+------------------+
| Trigger Source    | Trigger         | Use Case         |
|                   | Mechanism       |                  |
+-------------------+-----------------+------------------+
| From Non-secure   | SMC Instruction | Request Secure   |
| World             |                 | services or      |
|                   |                 | resources.       |
|                   |-----------------+------------------|
|                   | IRQ/FIQ         | Handle urgent    |
|                   | Interrupts      | events needing   |
|                   |                 | Secure access.   |
|                   |-----------------+------------------|
|                   | External Abort  | Resolve memory   |
|                   |                 | violations or    |
|                   |                 | faults.          |
+-------------------+-----------------+------------------+
| From Secure World | Exceptions      | Handle Secure    |
|                   |                 | World faults or  |
|                   |                 | events.          |
|                   |-----------------+------------------|
|                   | Direct CPSR     | Perform Secure   |
|                   | Manipulation    | ops or debugging.|
+-------------------+-----------------+------------------+        

Security Checks

Before proceeding with a state transition,?Monitor Mode?performs a set of?security checks?to verify the request and ensure it complies with the system's security policies. This step is critical in preventing unauthorized access to sensitive data or resources in the?Secure World.

Key Steps in Security Checks:

  1. Validation of Trigger Source: Monitor Mode verifies the source of the transition trigger (e.g., an interrupt, an external abort, or an SMC instruction). Only valid triggers from trusted sources are allowed to continue. Invalid or unauthorized triggers are denied, and pre-defined error handling procedures are invoked (e.g., logging the event, raising an exception).
  2. Access Control Enforcement: The?Secure Configuration Register (SCR)?and other security-related registers are checked to ensure that the requested transition complies with the system's access control rules. For instance: An?SMC instruction?from the Non-secure World must only request allowed services. External aborts due to illegal memory access may be logged, with appropriate action being taken.
  3. Sanitization: Inputs or parameters provided with the transition request are sanitized to prevent malicious data injection. This ensures the prevention of security breaches such as?buffer overflows?or?privilege escalation attacks.
  4. Allow or Block Decision: If all the above checks pass, the transition is allowed to proceed. If a check fails, the transition is blocked, and the system may: Return an error code to the requesting entity. Trigger a secure interrupt or fault handler for further investigation.


Example minimal Monitor mode code

.section .text
.global monitor_entry

monitor_entry:
    /* Save the processor state (Secure or Non-secure) */
    MRS     r0, CPSR               /* Save Current Program Status Register */
    STMFD   sp!, {r0-r12, r14}    /* Save general-purpose registers and PC */
    MRS     r1, SPSR               /* Save the SPSR (Saved Program Status Register) */
    STMFD   sp!, {r1}              /* Save SPSR to the stack */

    /* Security configuration */
    MRC     p15, 0, r2, c1, c1, 0  /* Read SCR (Secure Configuration Register) */
    TST     r2, #1                 /* Check NS bit */
    BEQ     switch_to_secure       /* If NS=0, switch to Secure World */

switch_to_nonsecure:
    /* Prepare to switch to Non-secure state */
    ORR     r2, r2, #1             /* Set NS bit to 1 */
    MCR     p15, 0, r2, c1, c1, 0  /* Write back SCR */
    LDMFD   sp!, {r1}              /* Restore SPSR */
    MSR     SPSR, r1               /* Restore SPSR */
    LDMFD   sp!, {r0-r12, r14}    /* Restore general-purpose registers and PC */
    SUBS    PC, LR, #4             /* Return from exception to Non-secure World */

switch_to_secure:
    /* Prepare to switch to Secure state */
    BIC     r2, r2, #1             /* Clear NS bit to 0 */
    MCR     p15, 0, r2, c1, c1, 0  /* Write back SCR */
    LDMFD   sp!, {r1}              /* Restore SPSR */
    MSR     SPSR, r1               /* Restore SPSR */
    LDMFD   sp!, {r0-r12, r14}    /* Restore general-purpose registers and PC */
    SUBS    PC, LR, #4             /* Return from exception to Secure World */

.end        

  • Saving Processor State: The current value of the CPSR (Current Program Status Register) is read into register r0 to save the processor's status. The general-purpose registers r0 to r12 and r14 (which holds the return address, PC) are stored on the stack using?STMFD sp!, {r0-r12, r14}. The SPSR (Saved Program Status Register) is read into r1 and then saved on the stack.
  • Reading and Checking SCR: The SCR (Secure Configuration Register) is read into register r2 using the?MRC?instruction. The NS (Non-secure) bit of SCR is checked using?TST r2, #1. This bit determines the security state.
  • Conditional State Switching: If NS bit is 0 (Secure state): The code branches to?switch_to_secure. Here, it clears the NS bit by using?BIC r2, r2, #1?to ensure the Secure state. The modified SCR is written back using?MCR p15, 0, r2, c1, c1, 0. The SPSR is restored from the stack and loaded into the SPSR register. The general-purpose registers and PC are restored from the stack. The code returns to the Secure world by adjusting the PC from LR minus 4. If NS bit is 1 (Non-secure state): The code sets the NS bit to 1 (though it's already 1) using?ORR r2, r2, #1. The modified SCR is written back. The SPSR and general-purpose registers are restored similarly to the Secure case. The code returns to the Non-secure world in the same manner.
  • Exception Return Mechanism: The return from exception is handled by?SUBS PC, LR, #4, which adjusts the program counter to the correct return address.


Previous parts

Part 1 - Monitor Mode in ARM Architecture (Part 1)

https://www.dhirubhai.net/pulse/monitor-mode-arm-architecture-part-1-anupam-datta-tf4kc

Part 2 - Monitor Mode in ARM Architecture (Context Switching)

https://www.dhirubhai.net/pulse/monitor-mode-arm-architecture-context-switching-part-2-anupam-datta-qed4c

Part 3 - Monitor Mode in ARM Architecture (Context Switching - Monitor Mode and Normal World)

https://www.dhirubhai.net/pulse/monitor-mode-arm-architecture-context-switching-normal-anupam-datta-kacrc

要查看或添加评论,请登录

Anupam Datta的更多文章

社区洞察

其他会员也浏览了