# Default Security Paper
**Something we will need to control for is for the repos that we are cloning that do not have MPUs**
## Related MPU Survey
NDSS BAR workshop paper presents "taxonomy" to evaluate MPU usage by the following criteria:
- **Code Integrity Protection (CIP)**: Code regions can be set as non-writable to prevent code injection and manipulation.
- **Data Execution Prevention (DEP)**: Data regions like stack or heap can be set as non-executable to prevent buffer overflow exploitation. CIP and DEP map to WˆX or executable-space protection in general computing platforms.
- **Coarse-grained StackGuard (CSG)**: An inaccessible memory hole is placed at the stack boundary to detect stack overflows. Note that CSG can only detect overflows to the entire stack region, not confusing with traditional StackGuard to function-level stack frames.
- **Kernel Memory Isolation (KMI)**: User mode (un-privileged) code cannot access any memory belonging to the kernel space without invoking system calls, which is similar to the user space and kernel space separation in modern OSs.
- **User Task Memory Isolation (TMI)**: User mode (unprivileged) tasks can only access its own memory except explicitly shared memory regions that belong to other tasks or kernel, which is similar to the process isolation in modern modern OSs.
- **Peripherals Isolation (PI)**: Peripheral access is re-stricted to tasks that actually need it.

## Zephyr
Zephyr uses a handful of config flags in the overlay `prj.conf` to enable the above security features.
1. `CONFIG_HW_STACK_PROTECTION`
2. `CONFIG_USERSPACE` (allows creation of unprivledged threads)
3. `CONFIG_MPU_STACK_GUARD`
[General Recommendations](https://docs.zephyrproject.org/latest/hardware/porting/board_porting.html#general-recommendations)
> It is recommended to enable the MPU by default, if there is support for it in hardware. For boards with limitedmemory resources it is acceptable to disable it. When the MPU is enabled, it is recommended to also enable hardware stack protection (CONFIG_HW_STACK_PROTECTION=y) and, thus, allow the kernel to detect stack overflows when the system is running in privileged mode.
**Zephyr provides a hardening guide with recommended security features:**
```
name | current | recommended || check result
================================================================================================
CONFIG_BOOT_BANNER | y | n || FAIL
CONFIG_BUILD_OUTPUT_STRIPPED | n | y || FAIL
CONFIG_FAULT_DUMP | 2 | 0 || FAIL
CONFIG_HW_STACK_PROTECTION | n | y || FAIL
CONFIG_MPU_STACK_GUARD | n | y || FAIL
CONFIG_OVERRIDE_FRAME_POINTER_DEFAULT | n | y || FAIL
CONFIG_STACK_SENTINEL | n | y || FAIL
CONFIG_EARLY_CONSOLE | y | n || FAIL
CONFIG_PRINTK | y | n || FAIL
```
**Zephyr design related to what we are doing:**
> - Access to thread stack buffers will be controlled with a policy which partially depends on the underlying memory protection > hardware.
> - A user thread will by default have read/write access to its own stack buffer.
> - A user thread will never by default have access to user thread stacks that are not members of the same memory domain.
> - A user thread will never by default have access to thread stacks owned by a supervisor thread, or thread stacks used to handle system call privilege elevations, interrupts, or CPU exceptions.
> - A user thread may have read/write access to the stacks of other user threads in the same memory domain, depending on hardware.
> - On MPU systems, threads may only access their own stack buffer.
> - On MMU systems, threads may access any user thread stack in the same memory domain. Portable code should not assume this.
> - By default, program text and read-only data are accessible to all threads on read-only basis, kernel-wide. This policy may be adjusted.
> - User threads by default are not granted default access to any memory except what is noted above
**Zephyr ensures for usermode threads**:
> - We ensure the detection and safe handling of user mode stack overflows.
> - We prevent invoking system calls to functions excluded by the kernel configuration.
> - We prevent disabling of or tampering with kernel-defined and hardware- enforced memory protections.
> - We prevent re-entry from user to supervisor mode except through the kernel- defined system calls and interrupt handlers.
> - We prevent the introduction of new executable code by user mode threads, except to the extent to which this is supported by kernel system calls.
_This is all entirely dependent on if the developer enables usermode for the given task_.
### Analysis of Intel's ECFW built on Zephyr
- Only mention of `CONFIG_USERSPACE` is in `doc/doxyfile.in`
- All tasks (defined in `misc/task_handler.c`) are started with [`K_INHERIT_PERMS`](https://docs.zephyrproject.org/latest/kernel/services/threads/index.html#c.K_INHERIT_PERMS), which inherits all permissions from the main thread. Threads can be later downgraded to user-mode threads, however that function [`k_thread_user_mode_enter`](https://docs.zephyrproject.org/latest/kernel/services/threads/index.html#group__thread__apis_1ga3fbe1c8a5f3ef1c25382c7d6fca35764) is not used anywhere.
- Skimming over the generated assembly, it does not seem like the MPU is configured or used at all. (The MPU registers do not seem to be referenced anywhere)
- Trying to enable `CONFIG_USERSPACE` complains about `ARCH_HAS_USERSPACE` not being enabled (which is weird, as that should be turned on for a Cortex-M, which the `mec1501_mtl_p` is)
Evidence for high coupling:
- Certain state is shared between multiple tasks, without any system call interface or other transition mechanism.
- Possible function call stack that crosses task boundary:
- `pwrseq_thread` (root of task, defined in `task_handler.c`) calls
- `pwrseq_update` calls
- `pwrseq_handle_transition_to_s0` calls
- `power_on` calls
- `soc_debug_consent_kbs` (if `CONFIG_SOC_DEBUG_AWARENESS`), calls
- `kbs_keyseq_boot_detect` (if `CONFIG_POWER_SEQUENCE_DISABLE_TIMEOUT_HOTKEY`),
- accesses `keyseq_det[type].detected`
- `keyseq_det` (`.detected`) is defined in `kbs_matrix.c`
- written by `fw_hotkeyseq_detection`,
- called by `kscan_callback`,
- called by `kbs_matrix_init`,
- called by `kbc_init`,
- called by `to_from_host_thread` (root of task, defined in `task_handler.c`)
## FreeRTOS
Summary: you can use MPU for task isolation if you use `xTaskCreateRestricted()` to create tasks. However, this is opt-in. Normal tasks (run with privilege and no MPU isolation) can be made with `xTaskCreate()`. A secure repo would create all tasks with `xTaskCreateRestricted()` to explictly say which tasks are (un)privileged. [almost no one is using restricted processes
](https://github.com/search?q=xTaskCreateRestricted+AND+language%3AC+AND+%28NOT+path[…]%3Aworkspace%29++AND+%28NOT+path%3Ampu_wrappers.c%29+&type=code)
- FreeRTOS is customised using a configuration file called FreeRTOSConfig.h. Every FreeRTOS application must have a FreeRTOSConfig.h header file https://www.freertos.org/a00110.html
- See: "`/* FreeRTOS MPU specific definitions. */`"
- I think option `configCHECK_FOR_STACK_OVERFLOW 3` has to be set for MPU stack overflow protection ([src](https://www.freertos.org/Stacks-and-stack-overflow-checking.html))
- functions to set MPU https://www.freertos.org/FreeRTOS-MPU-specific.html
- not sure what this is, but it shows up on github a lot `configENABLE_MPU`
- Can see the % occurrence of tasks which are started normally versus with MPU
- `FreeRTOS-MPU Specifics` section of https://www.freertos.org/FreeRTOS-MPU-memory-protection-unit.html explains all the details
- example in code: https://www.freertos.org/xTaskCreateRestricted.html
> Using FreeRTOS with Memory Protection Unit (MPU) Support
>
> Description
Memory Protection Unit (MPU) support in FreeRTOS ARMv8-M ports enables application tasks to execute in a privileged or unprivileged (user) mode, and provides fine grained memory and peripheral access control on a task by task basis.
>
>Unprivileged tasks:
>
> Are created using the xTaskCreateRestricted() API.
> Default to having no RAM access other than to their own stacks.
> Cannot execute code marked by the MPU as privileged access only.
> Can optionally be assigned access up to three additional memory regions, which can be changed at run-time.
>
>A memory fault is triggered any time an unprivileged task tries to access any memory region for which it has not been granted access. The fault handler gives the application writer a chance to take an appropriate action, which may be terminating the offending task.
>
>Do not confuse the privilege level of a task with the security domain it executes in. The secure and non-secure sides of an ARMv8-M core each have their own MPU - so it is possible to have both privileged and unprivileged execution on both the secure and non-secure sides.
>
from https://www.freertos.org/2020/04/using-freertos-on-armv8-m-microcontrollers.html
### Flags/Functions
`configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS`
`configCHECK_FOR_STACK_OVERFLOW`
`xTaskCreateRestricted` / `xTaskCreateRestrictedStatic` / `portSWITCH_TO_USER_MODE`
## RIOT
- [VERY GOOD UP-TO-DATE LIST OF ALL SECURITY FEATURES](https://forum.riot-os.org/t/energy-management-in-riot/4163/6)
- secure boot
- only boot signed firmware
- https://api.riot-os.org/group__pseudomodule__mpu__noexec__ram.html
- need to manually enable
- no results show up on GitHub
- there are zero github repos which use the riot mpu_noexec_ram . every riot repo uses mpu_stack_guard as it is on by default, and I do not see anyone who turns it off.
- https://github.com/search?q=%23define+MODULE_MPU_NOEXEC_RAM&type=code
- https://api.riot-os.org/group__pseudomodule__mpu__stack__guard.html
- Example usage https://github.com/RIOT-OS/RIOT/tree/master/tests/cpu/
- every board that has a `cortexm_mpu` (`FEATURES_PROVIDED += cortexm_mpu`) gets `c` [enabled by default](https://github.com/RIOT-OS/RIOT/blob/0ebb65710c7b0816fb17d8b913826a5ee7a3e58f/makefiles/pseudomodules.inc.mk#L284-L306)
- [`mpu_configure`](https://github.com/RIOT-OS/RIOT/blob/master/core/sched.c#L35-L37) is only called for the two flags linked above.
- cortexm_stack_limit
- RIOT doesn't have processes. There are threads and there is proper multithreading
- [No privilege levels kernel/user mode](https://forum.riot-os.org/t/running-riot-threads-as-unprivileged-user-mode/198) ([2](https://forum.riot-os.org/t/need-advice-for-research/3834))
- MODULE_MPU_STACK_GUARD only enabled by default in developer mode
- TODO: measure the actual overhead of software and hardware stack overflow checks
[supported boards](https://github.com/RIOT-OS/RIOT/tree/master/boards)
## Contiki-ng
- no memory protection
## Data Collection Methods
- perform github "repository search" for keyword (e.g. zephyr)
- perform github "code search" for filename (e.g. west.yml)
- manually confirm all repos with greater than 10 stars
- not forks
### Result
Zephyr results (w/o =y flag)
```
Total Repos Searched: 86
Total repos using hw_stack_protection: 19
Total repos using user_mode_threads: 17
Percentage of repos using hw_stack_protection: 21.8%
Percentage of repos using user_mode_threads: 19.5%
```
Zephyr results (w/ full flag)
```
Total Repos Searched: 87
Total repos using hw_stack_protection: 17
Total repos using mpu_stack_guard: 6
Total repos using user_mode_threads: 9
Percentage of repos using hw_stack_protection: 19.5%
Percentage of repos using mpu_stack_guard: 6.9%
Percentage of repos using user_mode_threads: 10.3%
```
----
FreeRTOS Results:
```
sw stack guard:
hw stack guard:
process isolation:
```
----
Contiki-ng Results:
```
sw stack guard:
hw stack guard:
process isolation:
```
----
RIOT Results:
```
sw stack guard:
hw stack guard:
process isolation:
```
---
## Other Notes
- Leon is building/looking into EC firmware.