1# Seccomp Policy Development 2 3## Overview 4 5### Introduction 6 7Secure computing mode (Seccomp) is a security mechanism provided by the Linux kernel. In the Linux system, a large number of system calls can be opened to user-mode programs without any restrictions. However, not all of these system calls are necessarily needed for user-mode programs. In this case, abuse of system calls can lead to system threats. For example, if a process has a security vulnerability, an attacker can run a shellcode segment to trigger system calls that are not triggered during normal execution, resulting in privilege escalation or private information leakage. To prevent such security risks, Seccomp limits the scope of system calls that can be used by programs, so as to reduce system exposure and improve security. 8 9### Operating Mechanism 10 111. Basic mechanism 12 13 Seccomp policies exist in the form of policy files. During compilation and building, a policy file is parsed to generate a source file that contains the BPF instruction policies, and then the source file is compiled into a dynamic policy library. During startup of a user-mode process, Seccomp system calls are invoked to load the BPF instruction policies into the kernel through the dynamic policy library. 14 152. Basic features 16 - A child process inherits the Seccomp policies of its parent process. 17 - After a Seccomp policy is loaded to the kernel during process running, the policy exists in the memory as a singly linked list and cannot be modified. 18 - Seccomp policies can be set for a process for multiple times. When a process executes a system call, the kernel traverses the policies specified for the nodes in the singly linked list, and then compares the policies to obtain the policy with the highest priority. 19 20 21### Constraints 22 23- System restrictions<br>The system used must be a standard system, and the options listed below must be enabled in the kernel. You can find the kernel option configuration file of the product in **//kernel/linux/config/{linux_version}/arch/{target_cpu}/configs/**. 24 ```shell 25 CONFIG_HAVE_ARCH_SECCOMP=y 26 CONFIG_HAVE_ARCH_SECCOMP_FILTER=y 27 CONFIG_SECCOMP=y 28 CONFIG_SECCOMP_FILTER=y 29 ``` 30 31- Feature restrictions 32 - The Seccomp policy for non-privileged processes complies with the baseline blocklist mechanism. 33 - If a process needs to use system calls in the baseline blocklist, the system calls must be declared in the privileged process policy file. 34 - The same Seccomp policy is enabled for all application processes. 35 - The same Seccomp policy is enabled for most of system service processes. 36 - Personalized Seccomp policies can be enabled for the native service processes incubated by the init process. 37 38## Enabling Seccomp 39 40### When to Use 41 42To meet product security requirements, you can enable Seccomp to limit the scope of system calls that can be invoked by processes. The development procedure below describes how to enable the basic functions and policies of Seccomp. Note that the basic functions must meet the feature restrictions described in [Constraints](#constraints). For details about the basic policy file, see [Policy File Overview](#policy-file-overview). 43 44### How to Develop 45 461. Add the following field to **vendor/Product vendor/Product name/config.json**: 47 ```c 48 "build_seccomp": true 49 ``` 50 The following is an example of adding the **build_seccomp** field to the product configuration file: 51 ```c 52 { 53 "product_name": "MyProduct", 54 "version": "3.0", 55 "type": "standard", 56 "target_cpu": "arm", 57 "ohos_version": "OpenHarmony 1.0", 58 "device_company": "MyProductVendor", 59 "board": "MySOC", 60 "enable_ramdisk": true, 61 "build_seccomp": true 62 "subsystems": [ 63 { 64 "subsystem": "ace", 65 "components": [ 66 { "component": "ace_engine_lite","features":[""] } 67 ] 68 }, 69 ... 70 ] 71 } 72 ``` 732. Perform a full build on the product code to generate an image. 74 ``` 75 ./build.sh --product-name *product name* --ccache --build-target make_all --target-cpu *specified CPU* 76 ``` 773. Burn the image into the device. 78 79### Debugging and Verification 80 81Check whether Seccomp is enabled for application processes and system service processes. 821. Run the shell command to obtain the process ID (that is, **target pid**) of the target process. 83 ``` 84 ps -ef | grep xxx 85 ``` 86 Information similar to the following is displayed, in which **target pid** is **1686**: 87 ``` 88 media 1686 1 0 08:16:12 ? 00:00:00 xxx 89 root 1869 1678 4 10:32:29 pts/0 00:00:00 grep xxx 90 ``` 91 922. Check the process status to determine whether Seccomp is enabled. 93 ```shell 94 cat /proc/[target pid]/status | grep Seccomp 95 ``` 96 Information similar to the following is displayed: 97 ``` 98 Seccomp: 2 99 Seccomp_filters: 1 100 ``` 101 **Table 1** Description of the Seccomp status 102 | Parameter | Description | 103 | --- | --- | 104 | Seccomp | - **0**: disabled.<br>- **1**: enabled with the strict mode. Only the read, write, exit, and sigreturn system calls are allowed.<br>- **2**: enabled with the filter mode. The customized policies can be enabled by loading BPF instruction sets. | 105 | Seccomp_filters | Number of Seccomp policies set for a process. | 106 107## Customizing Seccomp Policies for a Process 108 109### When to Use 110 111If the basic Seccomp policy has been enabled for a product, you can customize Seccomp policies for native service processes incubated by the init process to adapt to diversified security requirements. In this case, the Seccomp policies of other native service processes remain unchanged. 112 113### How to Develop 114 1151. Collect statistics on the system calls required by the 32-bit and 64-bit systems by using the static analysis and Strace statistics methods described in [System Call Statistic Methods](#system-call-statistic-methods). In this way, you will obtain the initial Seccomp policy. 1162. Write a policy file. For details, see [How to Write a Common Policy File](#how-to-write-a-common-policy-file). 1173. Write and build the **BUILD.gn** file. 118 119 1. Store the policy file in the code repository of the service subsystem and create a **BUILD.gn** file. For example, create the **seccomp_policy** folder in the service code repository, and create the policy file and **BUILD.gn** file in the folder. 120 121 ```shell 122 //path/to/code/seccomp_policy 123 ├── BUILD.gn 124 └── example.seccomp.policy 125 ``` 126 2. To parse the policy file and build the policy dynamic library, use the **ohos_prebuilt_seccomp** template to declare the Seccomp policy file path of the process in the **BUILD.gn** file. The **ohos_prebuilt_seccomp** template is defined in the **//base/startup/init/services/modules/seccomp/scripts/seccomp_policy_fixer.gni** file. The following table describes the parameters in the template. 127 128 **Table 2** Parameters in the ohos_prebuilt_seccomp template 129 | Parameter | Description | 130 | --- | --- | 131 | sources | Path of the policy configuration file, mandatory.| 132 | filtername | Filter name, mandatory. The value must be the same as the value of **Services name** in the [boot configuration file](subsys-boot-init-cfg.md) of the process. Otherwise, the attempt to enable Seccomp will fail. This parameter determines the name of the dynamic policy library generated after the build. For example, if **filtername** is set to **xxx**, the name of the dynamic policy library is **libxxx_filter.z.so**. | 133 | process_type | Process type, mandatory. If the process is one incubated by the init process, set this parameter to **system**; if the process is an application process, set this parameter to **app**.| 134 | part_name | Part name, mandatory. | 135 | subsystem_name | Subsystem name, mandatory. | 136 | install_enable | Option specifying whether to install the policy file to the image, mandatory. Set the value to **true**. | 137 | install_images | Installation location in the image, mandatory. | 138 139 Example 140 ```python 141 #Import the template file. 142 import("//base/startup/init/services/modules/seccomp/scripts/seccomp_policy_fixer.gni") 143 144 #Use the ohos_prebuilt_seccomp template. 145 ohos_prebuilt_seccomp("xxxx_seccomp_filter") { 146 sources = [ "xxxx.seccomp.policy" ] 147 148 filtername = "xxx" 149 150 process_type = "system" 151 152 part_name = "xx_part_name" 153 subsystem_name = "x_subsystem_name" 154 155 install_enable = true 156 install_images = [ "xxxxx" ] 157 } 158 ``` 159 3. Add the build target of **xxxx_seccomp_filter** to other **BUILD.gn** files. 160 ```python 161 if (build_seccomp) { 162 deps += [ "path:xxxx_seccomp_filter" ] 163 } 164 ``` 1654. Build the dynamic policy library **libxxx_filter.z.so**. 166 ```shell 167 ./build.sh --product-name *product name* --ccache --build-target xxxx_seccomp_filter --target-cpu *specified CPU* 168 ``` 169 If an error message that contains the following information is reported, the process needs to use the system calls in the baseline blocklist. In such a case, you need to declare the corresponding system call in **privileged_process.seccomp.policy**. For details, see [How to Write a Privileged Process Policy File](#how-to-write-a-privileged-process-policy-file). After the declaration is done, try again until the build is successful. 170 ```shell 171 xx of allow list is in block list 172 ``` 1735. Use the hdc tool to push the dynamic policy library to the device and restart the device. 174 ```shell 175 # Push an appropriate library path based on the installation location in the image. For example, if the image is **system** and the system architecture is 32-bit, the path of the dynamic policy library is **/system/lib/seccomp/**. 176 hdc shell mount -rw -o remount / 177 hdc file send /path/to/libxxx_filter.z.so /path/to/lib(or lib64)/seccomp/ 178 hdc shell reboot 179 ``` 1806. Use the [audit statistics](#audit-statistics) method to check and supplement the Seccomp policies. Repeat steps 4 to 6 until the process can run properly. 181 182### Debugging and Verification 183 1841. If Seccomp is not enabled for the target process, [check the Seccomp status](#debugging-and-verification) of the target process. 1852. If the process is terminated and audit log information is present in the kernel logs, the Seccomp policy is enabled but the policy list is incomplete. You can find an example audit log in [Audit Statistics](#audit-statistics). 1863. If the process is not terminated, comment out the system calls (for example, **setuid**) related to the specified uid in the Seccomp policy file. Rebuild the dynamic policy library, push the library to the image, and restart the process. Then, check whether the process is terminated by Seccomp. If the process is terminated, Seccomp has been enabled. 187 188## FAQs 189 190### How do I determine whether a process termination is caused by Seccomp? 191 192**Symptom** 193 194If a process is terminated under certain conditions, how do I determine whether the issue is caused by Seccomp? 195 196**Solution** 197 198Use either of the following methods: 199 200- Check the crash stack backtrace log of the process. If the signal in the log is **SIGSYS**, the process termination is caused by the Seccomp mechanism. To view the crash stack backtrace content, run the following shell command: 201 ```shell 202 cat /data/log/faultlog/faultlogger/crash stack backtrace log 203 ``` 204 Example output: 205 ```shell 206 Generated by HiviewDFX@OpenHarmony 207 ================================================================ 208 Device info:xxx 209 Build info:xxx 210 Module name:xxx 211 Pid:xxxx 212 Uid:xxxxx 213 Reason:Signal:SIGSYS(UNKNOWN) 214 ... 215 ``` 216- Check whether the process is still terminated after Seccomp is disabled. If the process runs properly after Seccomp is disabled, the process termination is caused by Seccomp. 217 218 Seccomp is enabled by default. When the device operation mode is set to **root**, you can run the shell command to set the corresponding system parameter to disable Seccomp of the entire system. 219 ```shell 220 # Set the system parameter to disable Seccomp and restart the process. 221 param set persist.init.debug.seccomp.enable 0; reboot 222 # Set the system parameter to enable Seccomp and restart the process. 223 param set persist.init.debug.seccomp.enable 1; reboot 224 ``` 225 226## Reference 227 228### Seccomp source code directory 229``` 230base/startup/init/services/modules/seccomp 231├── BUILD.gn 232├── gen_syscall_name_nrs.c 233├── scripts 234│ ├── generate_code_from_policy.py # Policy file parsing script 235│ ├── seccomp_policy_fixer.gni # Template definition in the BUILD.gn file for generating the dynamic policy library 236│ └── tools # Scripts for collecting system call statistics 237├── seccomp_policy # Basic policy files 238│ ├── app.blocklist.seccomp.policy 239│ ├── app.seccomp.policy 240│ ├── privileged_process.seccomp.policy 241│ ├── renderer.seccomp.policy 242│ ├── spawn.seccomp.policy 243│ ├── system.blocklist.seccomp.policy 244│ └── system.seccomp.policy 245├── seccomp_policy.c # Core Seccomp implementation code 246└── seccomp_policy_static.c # Seccomp plug-in code 247``` 248 249### Policy File Overview 250 251- Location<br>Basic policy files are stored in **//base/startup/init/services/modules/seccomp/seccomp_policy**. 252- Basic policy files 253 254 **Table 3** Description of policy files 255 | Policy File | Description | 256 | --- | --- | 257 | system.seccomp.policy | Seccomp policy enabled for most of system service processes.| 258 | system.blocklist.seccomp.policy | System call baseline blocklist for system processes, that is, the list of system calls that cannot be invoked by non-privileged processes.| 259 | app.seccomp.policy | Seccomp policy enabled for all application processes.| 260 | app.blocklist.seccomp.policy | System call baseline blocklist for application processes, that is, the list of system calls that cannot be invoked by application processes.| 261 | spawn.seccomp.policy | Seccomp policy enabled for the appspawn and nwebspawn processes.| 262 | renderer.seccomp.policy | Seccomp policy enabled for the rendering processes incubated by the nwebspawn process.| 263 | privileged_process.seccomp.policy | Privileged process policy file. If certain processes need to use the system calls on the baseline blocklist, you need to declare the corresponding process identifiers and baseline blocklists in this file.| 264 265### How to Write a Common Policy File 266 267- To declare a configuration item, write **@** followed by the configuration item, for example, **@returnValue**. 268- Add the content of a configuration item from the next line of this configuration item to the beginning of the next configuration item. 269- To comment out a line, add a pound sign (#) at the beginning of this line. 270- Set the system architecture to **arm** or **arm64**. Only these two system architectures are supported currently. 271- Separate system calls from the system architecture by a semicolon (;). The value **all** indicates that the system calls will be used by all supported system architectures. 272- Set other parameters as needed. Except **returnValue**, all the other parameters are optional. 273 274**Table 4** Configuration items in the policy file 275 276| Item | Description | Configuration Rule | 277| --- | --- | -- | 278| returnValue | Return value. | This parameter is mandatory. Value range:<br>- **LOG**: tolerant mode, in which only audit logs are recorded and the process is not terminated.<br>- **TRAP**: a mode in which the process is terminated and can be passed on to the faultloggerd process.<br>- **KILL_PROCESS**: a mode in which the process is terminated.<br>- **KILL_THREAD**: a mode in which the thread is terminated. | 279| headFiles | Header file, which is used to declare the macros in the **allowListWithArgs** and **priorityWithArgs** parameters.| Use **""** and **<>** to include the file name, for example, **<abc.h>** and **"cde.h"**. The default header files are **<linux/filter.h>**, **<stddef.h>**, **<linux/seccomp.h>**, and **<audit.h>**. | 280| priority | Allowlist of frequently used system calls. | System calls on the list are treated with a higher priority to improve the performance. | 281| priorityWithArgs | Allowlist of frequently used system calls with arguments. | System calls on the list are treated with a higher priority to improve the performance. | 282| allowList | Allowlist | List of system calls that can be invoked by a process. | 283| allowListWithArgs | List of system calls with arguments that can be invoked by a process. | Separate the system call name and argument by a colon (:). Supported relational operators include **<**, **<=**, **>**, **>=**, **==**, **!=**, and **&**, and supported logical operators include **&&** and \.|\|.<br>Use **arg***n* to specify the SN of the argument in the system. The value of **n** ranges from **0** to **5**. A judgment statement starts with **if** and ends with **else**. Declare the return value after the statement ends, and use a semicolon (;) to separate the judgment statement from the return value.<br>The return value must be in the format of **return xxx**, where the value range of **xxx** is the same as that of **returnValue**. If there are multiple conditions in the judgment statement, separate them with **elif**.| 284| blockList | Blocklist of system calls. | Before generating BPF instructions during policy file parsing, the system checks whether the system calls on the allowlist exist in the blocklist. If yes, a parsing error occurs.| 285| selfDefineSyscall | Customized system call. | Set the value of this parameter to a number. | 286 287Example: example.seccomp.policy 288 289``` 290@returnValue 291TRAP 292 293@headFiles 294"time.h" 295 296@priority 297ioctl;all 298 299@allowList 300openat;all 301close;all 302lseek;all 303read;all 304write;all 305setresuid;arm64 306setresgid;arm64 307setresuid32;arm 308setresgid32;arm 309 310@allowListWithArgs 311clock_getres:if arg0 >= CLOCK_REALTIME && arg0 <= CLOCK_BOOTTIME; return ALLOW; else return TRAP;all 312 313@blockList 314swapon;all 315 316@selfDefineSyscall 317787 318``` 319 320### How to Write a Privileged Process Policy File 321 322- To declare a configuration item, write **@** followed by the configuration item, for example, **@allowBlockList**. 323- Add the content of a configuration item from the next line of this configuration item to the beginning of the next configuration item. 324- To comment out a line, add a pound sign (#) at the beginning of this line. 325- Set the system architecture to **arm** or **arm64**. Only these two system architectures are supported currently. 326- Separate system calls from the system architecture by a semicolon (;). The value **all** indicates that the system calls will be used by all supported system architectures. 327 328**Table 5** Configuration items in the privileged process policy file 329| Item | Description | Configuration Rule | 330| --- | --- | -- | 331| privilegedProcessName | Process name identifier. | Character string corresponding to **name** in the **services** parameter in the boot file of the native service process.| 332| allowBlockList | Available baseline blocklist. | Fill in the system call and the system architecture.| 333 334The following example shows how to enable process1 and process2 to use the swapon system call in the baseline blocklist. 335``` 336@privilegedProcessName 337process1 338 339@allowBlockList 340swapon;all 341 342@privilegedProcessName 343process2 344 345@allowBlockList 346swapon;all 347``` 348 349### System Call Statistic Methods 350 351**Table 6** Comparison of statistic methods 352| Statistic Method | Description | Advantage | Disadvantage | 353| --- | --- | --- | --- | 354| <div style="width: 50pt">Static analysis | <div style="width: 300pt">Analyze the ELF disassembly code to obtain the call relationship, collect statistics on the APIs that call the libc library, and then parse the LibC library to obtain the call relationship between the LibC APIs and the system call numbers. In this way, you will obtain the system call numbers used by the ELF file.| <div style="width: 100pt">Statistics collection is supported for system calls in abnormal branches. | <div style="width: 100pt">Parsing of call relationship is not supported for pointer functions. | 355| Strace statistics | Use Strace to trace service processes when the device is running. During the trace, the invoked system calls are recorded into logs. Collect the logs after the trace is complete, and use a script to parse the logs and generate a Seccomp policy file.| Easy to use. | System calls can be completely collected only when all code branches are traversed. | 356| Audit statistics | After the Seccomp policy is enabled for a process, Seccomp intercepts invalid system calls and records audit log information containing the system call numbers into kernel logs. Collect the logs after the trace is complete, and use a script to parse the logs and generate a Seccomp policy file.| This method can be used as a supplement to the preceding methods. | Logs may be lost.<br>System calls can be completely collected only when all code branches are traversed. | 357 358#### Static Analysis 359 3601. Prepare the environment. 361 1. Prepare a Linux environment. 362 2. Download the cross compilers arm-linux-musleabi and aarch64-linux-musl. 363 ```shell 364 wget https://musl.cc/arm-linux-musleabi-cross.tgz 365 wget https://musl.cc/aarch64-linux-musl-cross.tgz 366 367 tar -zxvf arm-linux-musleabi-cross.tgz 368 tar -zxvf aarch64-linux-musl-cross.tgz 369 370 # Add the tool execution path to the environment variable. 371 export PATH=$PATH:/path/to/arm-linux-musleabi-cross/bin 372 export PATH=$PATH:/path/to/aarch64-linux-musl-cross/bin 373 ``` 374 375 3. Download the OpenHarmony source code. For details, see [Obtaining Source Code](../get-code/sourcecode-acquire.md). 376 3772. Compile **seccomp_filter** to obtain the dependency files **libsyscall_to_nr_arm** and **libsyscall_to_nr_arm64**. 378 379 **seccomp_filter** is declared in **base/startup/init/services/modules/seccomp/BUILD.gn** and is used to build the basic dynamic policy library of Seccomp. After the compilation is complete, dependency files are generated in **//out/Product name /gen/base/startup/init/services/modules/seccomp/gen_system_filter/**. 380 ```shell 381 ./build.sh --product-name *product name* --ccache --build-target seccomp_filter --target-cpu *specified CPU* 382 383 # Copy the dependency files to the tool folder for later use. 384 cp out/*product name* /gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/ 385 ``` 386 3873. Copy the **generate_code_from_policy.py** script file to the tool folder. This script file is available at **//base/startup/init/services/modules/seccomp/scripts/**. 388 ```shell 389 # Go to the root directory of the OpenHarmony source code. 390 cd /root/to/OpenHarmonyCode; 391 # Go to the directory where the **generate_code_from_policy.py** script file is located. 392 cd base/startup/init/services/modules/seccomp/scripts/; 393 # Copy the **generate_code_from_policy.py** script file. 394 cp generate_code_from_policy.py tools/; 395 ``` 396 3974. Compile ELF files related to the service code. In the 32-bit architecture, the implementation of disassembly code redirection for ELF files is complex. Therefore, ELF files are all compiled into 64-bit ELF files to parse the function call relationship. 398 ```shell 399 ./build.sh --product-name *product file* --ccache --target-cpu arm64 --build-target *target file* 400 ``` 401 4025. If full build has not been performed before and the dependent dynamic libraries for step 4 are not in the **//out** directory, copy the related dynamic libraries to the **//out** directory. The following code is for reference only. If other dynamic libraries are involved, copy them in a similar way. 403 ```shell 404 # Go to the root directory of the source code. 405 cd /root/to/OpenHarmonyCode 406 # Create the **aarch64-linux-ohos** folder in **out/*product name*/lib.unstripped/** to store the dependent dynamic libraries. 407 mkdir out/*product name*/lib.unstripped/aarch64-linux-ohos 408 # Copy the related dynamic libraries to the //out directory. 409 cp prebuilts/clang/ohos/${host_platform_dir}/llvm/lib/clang/${clang_version}/lib/aarch64-linux-ohos/*.so out/*product name*/lib.unstripped/aarch64-linux-ohos/ 410 cp prebuilts/clang/ohos/${host_platform_dir}/${clang_version}/llvm/lib/aarch64-linux-ohos/*.so out/*product name*/lib.unstripped/aarch64-linux-ohos/ 411 ``` 412 4136. Modify the **collect_elf_syscall.py** script file, and change the paths of the objdump and readelf tools to their absolute paths in the Linux environment. This script file is available at **base/startup/init/services/modules/seccomp/scripts/tools/**. The **objdump** and **readelf** tools available at **//prebuilts**. 414 ```python 415 #modified the path of objdump and readelf path 416 def get_obj_dump_path(): 417 obj_dump_path = '/path/to/llvm-objdump' 418 return obj_dump_path 419 420 421 def get_read_elf_path(): 422 read_elf_path = '/path/to/llvm-readelf' 423 return read_elf_path 424 ``` 425 4267. Use the **collect_elf_syscall.py** script file to parse and generate the corresponding policy file **xxx.seccomp.policy**. 427 428 **Table 7** Parameters in the collect_elf_syscall.py script file 429 | Parameter | Description | 430 | --- | --- | 431 | --src-elf-path | Folder where the ELF file is located, for example, **~/ohcode/out/rk3568**. Do not end the value with a slash (/).| 432 | --elf-name| ELF file name, for example, **libmedia_service.z.so**.| 433 | --src-syscall-path | **libsyscall_to_nr_arm** or **libsyscall_to_nr_arm64**, which corresponds to the architecture specified by **--target-cpu**. | 434 | --target-cpu | CPU architecture, that is, the architecture for which system calls are collected. This parameter determines the architecture for libC file parsing. Its value can be **arm** or **arm64**. | 435 | --filter-name | Name of the generated policy file. For example, if the input value is **test**, the generated file name is **test.seccomp.policy**. | 436 437 Use **collect_elf_syscall.py** to parse ELF files. 438 439 ``` 440 # The following example considers **rk3568** as the product and **libmedia_service.z.so** as the ELF file. 441 python3 collect_elf_syscall.py --src-elf-path ~/ohcode/out/rk3568 --elf-name libmedia_service.z.so --src-syscall-path libsyscall_to_nr_arm64 --target-cpu arm64 --filter-name media_service 442 ``` 443 444 Example result of xxx.seccomp.policy 445 ``` 446 @allowList 447 getcwd;arm64 448 eventfd2;arm64 449 epoll_create1;arm64 450 epoll_ctl;arm64 451 dup;arm64 452 dup3;arm64 453 fcntl;arm64 454 ioctl;arm64 455 ... 456 ``` 457 458#### Strace Statistics 459 4601. Use the cross compilers arm-linux-musleabi and aarch64-linux-musl to build the Strace tool for the 32-bit and 64-bit architectures, respectively. 4612. [Trace the service process](#tracing-the-service-process) to obtain the Strace logs. 4623. [Parse Strace logs](#parsing-strace-logs) by using scripts to obtain the Seccomp policy file. 463 464##### Tracing the Service Process 465 4661. Modify the embedded code in the init repository. Specifically, add the following content to **//base/startup/init/services/init/init_common_service.c** before executing the **SetSystemseccompPolicy** function to set the Seccomp policy. If the line starts with a plus sign (+), the line is added; if the line starts with a hyphen (-), the line is deleted. **xxxx** must be the same as the value of **Services name** in the [boot configuration file](subsys-boot-init-cfg.md) of the process. 467 ```c 468 --- a/services/init/init_common_service.c 469 +++ b/services/init/init_common_service.c 470 @@ -155,7 +155,19 @@ static int SetPerms(const Service *service) 471 // set seccomp policy before setuid 472 INIT_ERROR_CHECK(SetSystemseccompPolicy(service) == SERVICE_SUCCESS, return SERVICE_FAILURE, 473 "set seccomp policy failed for service %s", service->name); 474 - 475 + if (strncmp(service->name, "xxxx", strlen("xxxx")) == 0) { 476 + pid_t pid = getpid(); 477 + pid_t pid_child = fork(); 478 + if (pid_child == 0) { 479 + char pidStr[9] = {0}; 480 + sprintf_s(pidStr, 6, "%d", pid); 481 + if (execl("/system/bin/strace", "/system/bin/strace", "-p", (const char *)pidStr, "-ff", "-o", "/data/strace/xxxx.strace.log", NULL) !=0 ) { 482 + INIT_LOGE("strace failed"); 483 + } 484 + } 485 + sleep(5); 486 + } 487 if (service->servPerm.uID != 0) { 488 if (setuid(service->servPerm.uID) != 0) { 489 INIT_LOGE("setuid of service: %s failed, uid = %d", service->name, service->servPerm.uID); 490 ``` 4912. Perform a full build, and burn the image. 4923. Disable SElinux, and push Strace to the device. 493 ```shell 494 hdc shell setenforce 0 495 hdc shell mount -rw -o remount / 496 hdc file send /path/to/strace /system/bin/ 497 hdc shell chmod a+x /system/bin/strace 498 ``` 4994. Create a folder for storing Strace logs. 500 ```shell 501 hdc shell mkdir -p /data/strace 502 ``` 5035. Terminate the service process, and restart it. In the following command, **xxx** indicates the service process name. 504 ```shell 505 kill -9 $(pidof xxx) 506 ``` 5076. Perform service operations on the device. Make sure that all code is covered. 5087. Obtain Strace logs from **/data/strace** on the device, and save them to the directory where the parsing script is located. 509 ```shell 510 hdc file recv /data/strace /path/to/base/startup/init/services/modules/seccomp/scripts/tools/ 511 ``` 512 513##### Parsing Strace Logs 514 5151. Copy the dependency files to the Strace log folder for later use. The dependency files are those generated in step 2 in [Static Analysis](#static-analysis). 516 ```shell 517 cp out/*product name* /gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/strace/ 518 ``` 519 5202. Use the **strace_log_analysis.py** script file to parse and generate the corresponding policy file **xxx.seccomp.policy**. 521 522 The script file is available at **//base/startup/init/services/modules/seccomp/scripts/tools/**. 523 524 **Table 8** Parameters in the strace_log_analysis.py script file 525 | Parameter | Description | 526 | --- | --- | 527 | --src-path | Folder for storing log files. It must contain **libsyscall_to_nr_arm** and **libsyscall_to_nr_arm64**. The folder name must not end with a slash (/), for example, **./strace**.| 528 | --target-cpu | CPU architecture, which is the same as that of the traced process. Its value can be **arm** or **arm64**. | 529 | --filter-name | Name of the generated policy file. For example, if the input value is **test**, the generated file name is **test.seccomp.policy**. | 530 531 Use the **strace_log_analysis.py** script file to parse Strace logs. 532 ```shell 533 cd base/startup/init/services/modules/seccomp/scripts/tools; 534 python3 strace_log_analysis.py --src-path strace --target-cpu *specified CPU* --filter-name xxx 535 ``` 536 Example result of xxx.seccomp.policy 537 ``` 538 @allowList 539 getcwd;arm64 540 eventfd2;arm64 541 epoll_create1;arm64 542 epoll_ctl;arm64 543 dup;arm64 544 dup3;arm64 545 fcntl;arm64 546 ioctl;arm64 547 ... 548 ``` 549 550#### Audit Statistics 551 5521. Enable the initial Seccomp policy. For details, see [Customizing Seccomp Policies for a Process](#customizing-seccomp-policies-for-a-process). 5532. Obtain logs. 554 1. Create a folder for storing logs. 555 ```shell 556 mkdir -p /data/audit 557 ``` 558 2. Obtain Seccomp-related audit log information from kernel logs. The logs end with **.audit.log**. 559 ```shell 560 cat /proc/kmsg | grep type=1326 > /data/audit/media_service.audit.log 561 ``` 5623. Perform service-related operations and segment fault triggering operations. 563 1. To trigger a segment fault, add the following code to the service code to call **TriggerSegmentFault** at a certain point to rebuild and burn the image: 564 ```c 565 static void TriggerSegmentFault(void) 566 { 567 pid_t pid_child = fork(); 568 if (pid_child == 0) { 569 char *test = (char *)0x1234; 570 *test = 1; 571 } 572 } 573 ``` 574 2. After the device is started, run the following shell command to temporarily shut down SELinux and terminate the service process. The process then automatically restarts. 575 ```shell 576 setenforce 0 577 ``` 578 5794. Run the hdc command to obtain audit logs from the **/data/audit** on of the device, and save them to the directory where the parsing script is located. 580 ```shell 581 hdc file recv /data/audit /path/to/base/startup/init/services/modules/seccomp/scripts/tools/ 582 ``` 5835. Parse the audit logs. 584 585 Example audit log: 586 ```shell 587 <5>[ 198.963101] audit: type=1326 audit(1659528178.748:27): auid=4294967295 uid=0 gid=1000 ses=4294967295 subj=u:r:appspawn:s0 pid=2704 comm="config_dialog_s" exe="/system/bin/appspawn" sig=31 arch=40000028 syscall=208 compat=1 ip=0xf7b79400 code=0x80000000 588 ``` 589 **Table 9** Key parameters in audit logs 590 | Parameter | Description | 591 | --- | --- | 592 | type | Type. The value **1326** indicates that the log is of the Seccomp type. | 593 | sig | Semaphore. The value **31** indicates **SIGSYS**, which is the signal sent to the process when Seccomp interception occurs. | 594 | arch | Architecture ID. The value **40000028** indicates **arm**, and the value **c00000b7** indicates **arm64**. | 595 | syscall | System call ID. | 596 | compat | The value **1** indicates the compatibility mode, that is, the arm64 kernel uses arm system calls.| 597 598 599 1. Copy the dependency files to the log folder for later use. The dependency files are those generated in step 2 in [Static Analysis](#static-analysis). 600 ```shell 601 cp out/*product name* /gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/audit/ 602 ``` 603 2. Run the **audit_log_analysis.py** script to parse logs and generate **xxx.seccomp.policy**. The tool is available at **//base/startup/init/services/modules/seccomp/scripts/tools/**. 604 605 **Table 10** Parameters in the audit_log_analysis.py script file 606 | Parameter | Description | 607 | --- | --- | 608 | --src-path | Folder for storing log files. It must contain **libsyscall_to_nr_arm** and **libsyscall_to_nr_arm64**. The folder name must not end with a slash (/), for example, **./audit**.| 609 | --filter-name | Name of the generated policy file. For example, if the input value is **test**, the generated file name is **test.seccomp.policy**.| 610 611 ```shell 612 cd base/startup/init/services/modules/seccomp/scripts/tools 613 python3 audit_log_analysis.py --src-path audit --filter-name xxx 614 ``` 615 616### Combining Multiple Policy Files 617 618During [colltatistics on system calls](#system-call-statistic-methods), multiple policy files may be generated. In these policy files, system calls may be repeated or disordered. To solve these problems, you can combine policy files to sort system calls by arm64/arm and by system call number in ascending order. 619 620**Table 11** Parameters in the merge_policy.py script file 621| Parameter | Description | 622| --- | --- | 623| --src-files | Files to be processed, including **libsyscall_to_nr_arm** and **libsyscall_to_nr_arm64**.| 624| --filter-name | Name of the generated policy file. For example, if the input value is **test**, the generated file name is **test.seccomp.policy**. | 6251. Copy the dependency files to the log folder for later use. 626 ```shell 627 cp out/*product name* /gen/base/startup/init/services/modules/seccomp/gen_system_filter/libsyscall_to_nr_arm* base/startup/init/services/modules/seccomp/scripts/tools/ 628 ``` 6292. Run the **merge_policy.py** script to merge **policy1.seccomp.policy** and **policy2.seccomp.policy** into **xxxx.seccomp.policy**. 630 ```shell 631 python3 merge_policy.py --src-files libsyscall_to_nr_arm --src-files libsyscall_to_nr_arm64 --src-files policy1.seccomp.policy --src-files policy2.seccomp.policy --filter-name xxxx 632 ``` 633