# Hardware/Software-Based Security
###### tags: `Security` `Linux` `Kernel` `Operating System` `Computer Architecture` `Hardware` `Embedded System` `Software` `ASM` `ABI` `x86` `ARM` `System Design`
A set of topics for information securities supported by hardware/software upon the applications.
> ***"Trust and mistrust are often separated by a fine line."***
> 《孫子.謀攻》:「知彼知己者,百戰不殆。」
> "If you know the enemy and know yourself, you need not fear the result of a hundred battles. If you know yourself but not the enemy, for every victory gained you will also suffer a defeat. If you know neither the enemy nor yourself, you will succumb in every battle." ---- *The Art of War*
## Hardware-Based Security
### Intel Control Flow Enforcement Technology (CET)
Avoiding control-flow hijacking attacks (e.g., ROP) by validating the control flow of a program during runtime.
More:
- [What does the endbr64 instruction actually do? - StackOverflow](https://stackoverflow.com/questions/56905811/what-does-the-endbr64-instruction-actually-do)
- [Linux May Flip On Indirect Branch Tracking By Default (IBT) - Phoronix](https://www.phoronix.com/news/Linux-x86-IBT-Default-Patch)
![image](https://hackmd.io/_uploads/HJZJJt6-A.png =500x)
### Intel Converged Security and Manageability Engine (CSME)
Intel® CSME, a controller embedded in every PCH (chipset, 南橋), is an embedded subsystem and a PCIe (Peripheral Component Interconnect Express) device. Intel® CSME aims to implement a computing environment isolated from the main, CPU-executing, host software (SW) like BIOS (Basic Input Output System), OS (Operating System) and applications.
> Intel ME is restricted to specific softwares that are signed by Intel and runs with the highest privilege possible. In contrast, SGX enclaves are running in unprivileged user mode.
Intel® CSME can access a limited number of interfaces, such as GPIO (General Purpose Input/Output) and LAN/Wireless LAN (WLAN), in order to perform its intended operations. As designed, Intel® CSME’s firmware and configuration files are stored in NVRAM (Non-Volatile, Random-Access Memory), such as flash memory on the SPI (Serial-Peripheral-Interface) bus.
[Intel Management Engine & **Security Bug Vulnerabilities** - Wiki](https://en.wikipedia.org/wiki/Intel_Management_Engine)
![active-management-technology-fig1](https://hackmd.io/_uploads/HJbhP1DfC.png =400x)
![active-management-technology-fig2](https://hackmd.io/_uploads/BJ6IY1DGA.png =400x)
**Note:**
- Intel Active Management Technology (AMT) allowing a system administrator to remote access, control, update, reformat, KVM, etc., can be enabled by using Intel CSME as implemented by the PC manufacturer.
- Flash memory stores the firmware image, BIOS hardware config, manufacturer custom config such as passwords, network, certificates, access control lists (ACLs), etc.
- On power-up, the firmware image is copied into the DDR RAM. The firmware then executes on the Intel® processor with Intel® ME and uses a small portion of the DDR RAM (Slot 0) for storage during execution. RAM slot 0 must be populated and powered on for the firmware to run.
Refs:
- [Getting Started with Intel® AMT - Intel](https://www.intel.com/content/www/us/en/developer/articles/guide/getting-started-with-active-management-technology.html)
- [[White Paper] Intel® CSME Security - Intel](https://www.intel.com/content/dam/www/public/us/en/security-advisory/documents/intel-csme-security-white-paper.pdf)
- [FIRMWARE SECURITY REALIZATIONS - PART 1 - SECURE BOOT AND DBX - Eclypsium](https://eclypsium.com/blog/firmware-security-realizations-part-1-secure-boot-and-dbx/)
- [FIRMWARE SECURITY REALIZATIONS - PART 2 - START YOUR MANAGEMENT ENGINE - Eclypsium](https://eclypsium.com/blog/firmware-security-realizations-part-2/)
- [FIRMWARE SECURITY REALIZATIONS - PART 3 - SPI WRITE PROTECTIONS - Eclypsium](https://eclypsium.com/blog/firmware-security-realizations-part-3-spi-write-protections/)
:::info
**[CVE-2017-5705] Exploiting Intel’s Management Engine**
**Summary of the Exploit:**
1. The ME firmware consists of multiple "partitions", one of them being the ++MFS partition (ME File System)++ which contains various configuration files. A file in the ++MFS partition++ named "/home/bup/ct" is used to initiatize the Trace Hub Configuration of the ME and **is user-modifiable**.
> While most "partitions" are signed and cannot be modified as they contain code, the ++MFS partition++ is not and can therefore be modified by us mortals. There are additional restrictions in it that makes not all of the files user-modifiable.
2. **The ME process BUP (Hardware Bring-UP) reads the entire "/home/bup/ct" file into a buffer of size 808 without checking that the file will fit** - we have a buffer overflow exploit here.
![image](https://hackmd.io/_uploads/r15goxa5C.png)
> There is a ++security-cookie/stack-guard++ (with hardware-randomized number) before returning the funciton that protects the ME against buffer overflows, making the buffer overflow exploit useless.
> ![image](https://hackmd.io/_uploads/S1fjrxacC.png)
3. It is then read in "chunks" of 64 bytes & copied into a shared memory block. This write operation (with `sys_write_shared_mem` function) gets address of
destination buffer from the shared memory block descriptor that resides in the `syslib_context` structure, and the `syslib_context` pointer resides in the TLS (Thread Local Storage) strucuture at the bottom of the stack (0x00 ~ 0x18), where we can affect it by buffer overflow.
4. Overwriting the stack all the way to the bottom in order to overwrite the `syslib_context`, & **pointing it to a custom-made shared memory block containing the destination address pointing to the memcpy‘s return address, which allows us to control the return address of next chunk memcpy**, bypasses the ++security-cookie/stack-guard++ protection that is in place.
![image](https://hackmd.io/_uploads/r1chRMp50.png)
![image](https://hackmd.io/_uploads/SJHKFGT5R.png)
By using both the buffer overflow (2, 3) and the TLS/syslib-context/shared-memory (4) exploits, we can control the code that gets executed using ROPs - running our own unsigned code.
> The absence of ASLR enables us to overwrite a return address using the arbitrary write primitive and hijack the program control flow. But here lies an unpleasant surprise for the attacker—the stack is not executable.
>
> However, that BUP can spawn new processes and is responsible for checking module signatures. So with Return-Oriented Programming (ROP), we can create a new process with the rights we need.
**Exploit Flow:**
`bup_init_trace_hub` > `bup_dfs_read_file` > `bup_read_mfs_file` > `sys_write_shared_mem`
![image](https://hackmd.io/_uploads/SywWul65R.png)
**Infection:**
The most important finding of our research was a vulnerability that allows running arbitrary code in Intel ME. Such a vulnerability has the potential to jeopardize a number of technologies, including **Intel Protected Audio Video Path (PAVP)**, **Intel Platform Trust Technology (PTT / fTPM)**, **Intel Boot Guard**, & **Intel Software Guard Extension (SGX)**, as it takes care of:
- Hardware Initialization
- Bootstrap Processor (BSP) Boot-up
- Control of the Clock Registers
- DRM Management for Audio/Video
- Software-Based TPM
These extra tasks of ME may be the reason why it cannot be deactivated for consumer products.
Refs:
- :+1: [[White Paper] How to Hack a Turned-Off Computer, or Running Unsigned Code in Intel Management Engine - Maxim Goryachy, Mark Ermolov](https://www.blackhat.com/docs/eu-17/materials/eu-17-Goryachy-How-To-Hack-A-Turned-Off-Computer-Or-Running-Unsigned-Code-In-Intel-Management-Engine-wp.pdf)
- :+1: [[Slides] How to Hack a Turned-Off Computer, or Running Unsigned Code in Intel Management Engine - Maxim Goryachy, Mark Ermolov](https://www.blackhat.com/docs/eu-17/materials/eu-17-Goryachy-How-To-Hack-A-Turned-Off-Computer-Or-Running-Unsigned-Code-In-Intel-Management-Engine.pdf)
- [Exploiting Intel’s ME – Part 1: Understanding PT’s TXE PoC (INTEL-SA-00086) - KaKaRoTo's Blog](https://kakaroto.ca/2019/11/exploiting-intels-management-engine-part-1-understanding-pts-txe-poc/)
:::
### Secure Enclaves
*aka Trusted Execution Environments (TEE)*
Secure Enclaves are sets of security-related instruction codes built into new CPUs. They protect data in use, because the enclave is decrypted on the fly only within the CPU, and then only for code and data running within the enclave itself.
[What is a Secure Enclave? - anjuna.io](https://www.anjuna.io/resources/what-is-a-secure-enclave#secure-enclaves-deliver-high-level-hardware-security)
![image](https://hackmd.io/_uploads/S1s0DY6ZA.png =400x)
#### Intel Software Guard Extensions (SGX)
Intel SGX encrypts sections of memory using security instructions native to the CPU. It’s a form of hardware-based encryption that allows users to protect their most-sensitive data by placing it into a highly secured environment within memory.
[What is Intel SGX? - Trenton Systems](https://www.trentonsystems.com/en-us/resource-hub/blog/what-is-intel-sgx)
![image](https://hackmd.io/_uploads/BkVbSKT-R.png =400x)
Applications:
- [Secure Network Interface with SGX - Felix Kirchengast](https://diglib.tugraz.at/download.php?id=6144a2678500a&location=browse) with [MACSec (Media Access Control Security)](https://info.support.huawei.com/info-finder/encyclopedia/zh/MACsec.html)
The (untrusted) host OS passes an outgoing packet to the enclave. The enclave executes a sequence of protocol-specific validations. If passed, then the enclave transforms the packet into a cryptographically authenticated MACSec packet. The MACSec gateway verifies the authenticity of an outgoing MACSec packet. Then the MACSec gateway transforms the MACSec packet back into its original packet representation and forwards the packet to the local network.
![image](https://hackmd.io/_uploads/r1EBNi6ZC.png =300x)
### ARM TrustZone
Providing physical hardware-level isolation (not instruction's ring) in the processors, and using a firmware-level bridge for communicating between normal & safe zone.
> :+1: [整合RTOS運行防護 TrustZone強化物聯網安全 - Joseph Yiu](https://www.2cm.com.tw/2cm/zh-tw/tech/C99CAB2F8A9944D080ECFDC7348AA3F1)
![image](https://hackmd.io/_uploads/SkGBuK6b0.png =200x)
- [ARM Open Source Trusted Firmware-M (TF-M) & Platform Security Architecture (PSA) - Risheng - HackMD](https://hackmd.io/@Risheng/ARM-TFM)
![image](https://hackmd.io/_uploads/B1vg50tEA.png =500x)
### Trusted Platform Module (TPM)
![image](https://hackmd.io/_uploads/r1_pPj6ZC.png)
> [For Security, How Bad are TPMs and How Good is the Apple T2 Chip? - Prof Bill Buchanan OBE FRSE - Medium](https://medium.com/asecuritysite-when-bob-met-alice/for-security-how-bad-are-tpms-and-how-good-is-the-apple-t2-chip-a561bda34e6)
### Virtualization Based Security (VBS) & Hypervisor Enforced Code Integrity (HVCI)
![image](https://hackmd.io/_uploads/SkdSdsa-0.png =500x)
> [What is Virtualization Based Security (VBS) and Hypervisor Enforced Code Integrity (HVCI)? - microsoft](https://techcommunity.microsoft.com/t5/windows-insider-program/virtualization-based-security-vbs-and-hypervisor-enforced-code/td-p/240571)
### Classic Strategies
- [[電子書] Intel Architecture 保護模式架構 - 陳秉哲 - ntu.edu](https://www.csie.ntu.edu.tw/~wcchen/asm98/asm/proj/b85506061/cover.html)
## Software-Based Security
All Software Vulnerable Nightmares come from:
:::warning
***Executables** (e.g., return address, jump address, callback handler) can potentially be tampered with malicious **user-mutable memory areas** (e.g., stack, heap).*
:::
### Data Execution Prevention (DEP)
*Preventing certain memory sectors, e.g. the stack, from being executed.*
$Executable \iff ~Writable$
#### No-eXecute bit (NX bit) -- Hardware DEP
*Setting the Virtual Address Space READONLY.*
> By utilising the *NX* feature of the CPU, the OS can mark pages as non-executable and if an attacker tries to point *EIP (Extended Instruction Pointer for the stack in x86)* to some memory inside that page the CPU will refuse to fetch instructions from it and raise a hardware exception.
### Address Space Layout Randomization (ASLR)
*Randomly offsetting the location of modules and certain in-memory structures to prevent shellcode from being successful.*
:arrow_right: [ELF Header - Linux Kernel Debugging - shibarashinu](https://hackmd.io/@shibarashinu/ryyKT2wZR#Program-Info)
#### Position Independent Executables (PIE) -- Linux ASLR
> A *PIE* binary and all of its dependencies are loaded into random locations within virtual memory each time the application is executed. This makes *Return Oriented Programming (ROP)* attacks much more difficult to execute reliably.
> :+1: [Position Independent Executables (PIE) - Red Hat](https://www.redhat.com/en/blog/position-independent-executables-pie)
### RELocation Read Only (RELRO)
*RELRO ensures that the Lazy Loading GOT cannot be overwritten in vulnerable ELF binaries.*
> The linker should resolve all dynamically linked functions at the beginning of the execution, and then makes the GOT READONLY.
> - **Partial RELRO:** The .got section is READONLY, but .got.plt is still writeable.
> - **Full RELRO:** Both .got and .got.plt are READONLY. (Only this prevent buffer-overflow from overwriting the GOT entry to get control of program execution)
> [Hardening ELF binaries using Relocation Read-Only (RELRO) - Red Hat](https://www.redhat.com/de/blog/hardening-elf-binaries-using-relocation-read-only-relro)
### Stack Canaries
*Preventing buffer overflow attacks.*
Stack canaries work by modifying every function's prologue and epilogue regions to place and check a value on the stack respectively. As such, if a stack buffer is overwritten during a strcpy(), an exception is raised.
![1120b-93ba3-2017-09-20_173104](https://hackmd.io/_uploads/HkRVEUBMA.png =300x)
- Example of Stack Canary on Linux
```asm=
; Place canary value from fs:0x28 onto Stack
; $fs is a reg pointing to thread-specific data segment
mov rax, QWORD PTR fs:0x28
mov QWORD PTR [rbp-0x8], rax
xor eax, eax
...
; Check if stack canary value changed
mov rdx,QWORD PTR [rbp-0x8]
sub rdx,QWORD PTR fs:0x28
je 0x55555555518f <main+70>
call 0x555555555050 <__stack_chk_fail@plt>
```
:::warning
:warning: The Linux kernel v4.19 (released in October 2018) adopts two canary designs to protect kernel stacks:
- Global canary for ARM64
- Per task canary for x86_64
For both the global canary as well as the per-task canary design, the attacker can leverage the leaked stack canary to craft the overflow payload so that stack canary will be overflowed by the correct canary value. In other words, with the leaked canary value, the overflow attack can be conducted without being detected as the stack canary value after overflow is correct.
Ref: [PESC: A Per System-Call Stack Canary Design for Linux Kernel - J Sun, 2020](https://yajin.org/papers/pesc.pdf)
:::
#### GCC Supports (User Space Only)
```sh
gcc -fstack-protector-explicit ...
```
- GNU Extension
```clike=
__attribute__((stack_protect)) test()
{
...
}
```
> [Stack buffer overflow protection 學習筆記 – Stack canaries mechanism in User space - SZ Lin](https://szlin.me/2017/12/09/stack-buffer-overflow-stack-canaries/)
:::warning
**Discussion: Why doesn't the stack simply grow upwards to prevent buffer overflows?**
> In typical implementations, when allocating space on the stack, we decrement the stack pointer (rsp) to reserve a fixed size of memory for future use. This memory is then filled from low addresses to high addresses, potentially causing issues such as overwriting the return address.
>
> Would aligning the expansion direction of both local variables and the stack potentially mitigate the risks of return address overwrites?
**Answer:** Despite changing the direction of stack growth, buffer overflows can still occur by overwriting the memory space of the pointer that references a previous stack frame's buffer.
Refs:
- [Why don't stacks grow upwards (for security)? - StackOverflow](https://stackoverflow.com/questions/2744502/why-dont-stacks-grow-upwards-for-security)
- [Stacks that grow up - Stack buffer overflow - Wiki](https://en.wikipedia.org/wiki/Stack_buffer_overflow#Stacks_that_grow_up)
:::
:::success
**[Work in Process] Hardware-Support Lightweight Stack Canaries**: Discover a hardware machanism design for effectively detecting & preventing buffer overflows to replace software-based stack canaries.
*Mitigating conventional stack canaries' overhead; taking the shackles of canary values off; can be approached via both hardware or software; and is fully backward compatible on operating systems or compiler supports: Only need the operating system sets the custom stack overflow exception handler, or the compiler inserts a stack canary check function.*
:::
### VLA-Free in Kernel Stacks
> [The Linux Kernel Is Now VLA-Free: A Win For Security, Less Overhead & Better For Clang - Phoronix](https://www.phoronix.com/news/Linux-Kills-The-VLA)
### Image has Safe Exception Handlers (/SAFESEH)
*When /SAFESEH is specified, the linker only produces an image if it can also produce a table of the image's safe exception handlers. This table specifies to the operating system which exception handlers are valid for the image.*
> [/SAFESEH (Image has Safe Exception Handlers) - Microsoft Learn](https://learn.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers?view=msvc-170)
## Software/Hardware-Based Vulnerabilities
### Memory Exploit in JavaScript JIT Engine
The JIT compiler neglects some safety checks due to certain design flaws and generates vulnerable machine code, which causes memory corruption.
:+1: [Exploiting Logic Bugs in JavaScript JIT Engines - saelo](http://phrack.org/issues/70/9.html#article)
Solution:
- **Sandboxing:** A safe memory area for the untrusted process use.
ref: [V8 Sandbox - High-Level Design - Google Docs](https://docs.google.com/document/d/1FM4fQmIhEqPG8uGp5o9A-mnPB5BOeScZYpkHjo0KKA8/edit)
![a160e5ef-7081-4352-b8b4-cbd1b2af46aa](https://hackmd.io/_uploads/BJvXP-ENR.png =400x)
- **Strict Mode with Similar C *Volatile* Tag:** Prevent JIT compiler's redundancy elimination from inadvertently trimming necessary checking code.
- **Auditing JIT Compiler's Vulnerabilities in Advance:** When auditing complex software such as JIT compilers, it is often a sensible approach to determine specific vulnerability patterns in advance and look for instances of them.
### PPPOE Vulnerabilities on Play Station Consoles
*Vulnerabilities in the PS4/PS5 kernel's PPPOE networking function allow arbitrary sizes of memcpy() to a fixed-length memory, leading to a buffer overflow.*
```cpp=
...
buf = r = malloc ((len < 6? 6: len), M_TEMP, M_NOWAIT); // r is dst pointer
...
bcopy (p, r, p[1]); // p is src pointer (pointing to a header buffer)
...
```
> [CVE-2006-4304: Remote vulnerabilities in spp - hackerone](https://hackerone.com/reports/2177925)
#### PPPwn - PlayStation 4 PPPoE RCE
PPPwn is a kernel remote code execution exploit for PlayStation 4 up to FW 11.00. This is a proof-of-concept exploit for CVE-2006-4304 that was reported responsibly to PlayStation.
> [PPPwn - TheOfficialFloW - GitHub](https://github.com/TheOfficialFloW/PPPwn)
Steps:
1. **Initialization**
- Wait for and respond to PPPoE Discovery (PADI) and Offer (PADO) packets.
- Exchange LCP and IPCP configuration packets to establish a PPP connection.
- Prepare for further steps by grooming the heap.
2. **Memory Corruption**
- Pin the process to CPU 0 for consistency.
- Send specially crafted LCP configure request to trigger memory corruption.
- Scan for and identify the corrupted memory object.
3. **KASLR Defeat**
- Determine the Kernel Address Space Layout Randomization (KASLR) offset by analyzing the corrupted object.
- Calculate the offset to bypass KASLR protections.
4. **Remote Code Execution**
- Send an LCP terminate request to reset the connection.
- Re-establish the connection using new PPPoE Discovery (PADI) and Offer (PADO) packets.
- Send the packets necessary to trigger the remote code execution.
5. **Arbitrary Payload Execution**
- Send the stage 2 payload to execute arbitrary code.
### Hyper-V Virtualization Bug
*Vmswitch's virtual networking switch (a paravirtualized device) never validates the value of OidRequest and can thus dereference an invalid pointer.*
> [Critical 9.9 Vulnerability in Hyper-V Allowed Attackers to Exploit Azure - Akamai](https://www.akamai.com/blog/security/critical-vulnerability-in-hyper-v-allowed-attackers-to-exploit-azure)
![image](https://hackmd.io/_uploads/rkyislPf0.png =400x)
### Out-Of-Order Execution (Meltdown) & Branch Prediction (Spectre) Vulnerabilities
*Exploit "the easy operation, the first out" in an instruction parellelism mechanism. Attacker can cause an exception, & dump (flush & reload) the desired value from the cache.*
- [潛藏於CPU的漏洞:Meltdown & Spectre - NTU 計網中心](https://www.cc.ntu.edu.tw/chinese/epaper/0045/20180620_4508.html)
- [[情報] 新漏洞 AMD INCEPTION - PC_Shopping](https://www.ptt.cc/bbs/PC_Shopping/M.1691546794.A.CA7.html)
- [Inception: how a simple XOR can cause a Microarchitectural Stack Overflow - Computer Security Group](https://comsec.ethz.ch/research/microarch/inception/)
- [Spectre & Meltdown - Computerphile](https://www.youtube.com/watch?v=I5mRwzVvFGE)
#### Solution: Multiple Kernel Memory (MKM)
*Leveraging Kernel Page-Table Isolation (KPTI))*
> :+1: [Mitigation of Kernel Memory Corruption Using Multiple Kernel Memory Mechanism PDF - IEEE](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=9502080)
- MKM Design
![image](https://hackmd.io/_uploads/ByMI2iPGR.png)
The trampoline and security kernel address space achieve the segregation from the vulnerable kernel codes by performing kernel address space switching of the MKM.
- **Trampoline:** The trampoline kernel address space facilitates the switching functions. The main part of the trampoline kernel address space acts as a gateway for the transition between the user mode and kernel mode.
- **Security:** The security kernel address space employs features of kernel protection methods that contain specific sets of kernel codes and data. Only the security kernel address space can execute these kernel codes. The "in and out" transition is forcefully permitted with the trampoline kernel address space between the user and kernel modes.
### DMA Attack
DMA grants certain devices privileges to interact with computer’s physical systems. PCIe devices (like Thunderbolt™ 3 and Thunderbolt™ 4 ports) have access to your machine’s memory. This create the opportunity for an infected device to spread malicious code directly into your system memory.
Microsoft, Apple, and Intel provide advanced protection against the unauthorized access of device memory. With Thunderbolt™ 4, Intel VT-d DMA protection is now part of the specification, aiming to improve device safety going forward.
- [DMA 攻擊 - Wiki](https://zh.wikipedia.org/zh-tw/DMA%E6%94%BB%E5%87%BB)
- [What is Intel VT-d DMA Protection? - Kensington](https://www.kensington.com/news/docking-connectivity-blog/what-is-intel-vt-d-dma-protection/)
### OpenSSH "RegreSSHion" RCE Vulnerabilities
- **Logic error in OpenSSH's ObscureKeystrokeTiming feature:** Allows detection of real keystroke packets by passive observers, breaking a timing attack mitigation.
> Since OpenSSH 2.9.9 sshd(8) has sent fake keystoke echo packets for traffic received on TTYs in echo-off mode, such as when entering a password into su(8) or sudo(8). This bug rendered these fake keystroke echoes ineffective and could allow a passive observer of a SSH session to once again detect when echo was off and obtain fairly limited timing information about keystrokes in this situation (20ms granularity by default).
- **Race condition in sshd:** If a client does not authenticate within LoginGraceTime seconds (120 by default, 600 in old OpenSSH versions), then sshd's SIGALRM handler is called asynchronously, but this signal handler calls various functions that are not async-signal-safe (for example, malloc() and free() in the syslog()).
> This race condition affects sshd in its default configuration. Successful exploit has been demonstrated on 32-bit Linux/glibc systems with ASLR. Under lab conditions, the attack requires on average 6-8 hours of continuous connections up to the maximum the server will accept. Exploitation on 64-bit systems is believed to be possible but has not been demonstrated at this time.
:::info
**Signal-handling vulnerabilities**
This vulnerability is exploitable remotely on glibc-based Linux systems, where syslog() itself calls async-signal-unsafe functions: an unauthenticated remote code execution as root, because it affects sshd's privileged code, which is not sandboxed and runs with full privileges. We have not investigated any other libc or operating system.
> Notably, *OpenBSD* is not vulnerable, its SIGALRM handler calls syslog_r(), an **async-signal-safer version of syslog()** that was invented by *OpenBSD* in 2001.
Before discussing more generalized attack scenarios, here is a simple example of signal handler races. We would try to exploit non-atomic signal handler. The following code generalizes, in simplified way, very common bad coding practice (which is present, for example, in setuid root Sendmail program up to 8.11.3 and 8.12.0.Beta7):
```cpp=
/*********************************************************
* This is a generic verbose signal handler - does some *
* logging and cleanup, probably calling other routines. *
*********************************************************/
void sighndlr(int dummy) {
// malloc twice
syslog(LOG_NOTICE, user_dependent_data);
// Initial cleanup code, calling the following somewhere:
free(global_ptr2);
free(global_ptr1);
... // [1] Additional clean-up code: unlink tmp files, etc.
exit(0);
}
/**************************************************
* This is a signal handler declaration somewhere *
* at the beginning of main code. *
**************************************************/
int main(int argc, char *argv[]) {
...
signal(SIGHUP,sighndlr);
signal(SIGTERM,sighndlr);
// Other initialization routines, and global pointer assignment somewhere in the code
// (assume that nnn is partially user-dependent, yyy does not have to be):
global_ptr1=malloc(nnn);
global_ptr2=malloc(yyy);
... // [2] further processing, allocated memory is filled with any data, etc.
return 0;
}
```
This code seems to be pretty immune to any kind of security compromises. But this is just an illusion. By delivering one of the signals handled by sighndlr() function somewhere in the middle of main code execution (marked as [2]) code execution would reach handler function. Let's assume we delivered "SIGHUP". Syslog message is written, two pointers are freed, and some more clean-up is done before exiting (marked as [1]).
Now, by quickly delivering another signal "SIGTERM", **Attacker might cause sighndlr() function re-entry** due to a very common condition that all signals (e.g., SIGQUIT, SIGTERM, SIGINT, etc.) sharing the same handler.
> **Note:** The already delivered signal is masked and would not be delivered, so we cannot deliver "SIGHUP", but there is nothing against delivering "SIGTERM".
To exploit this vulnarability, we can target heap structures by exploiting free() and syslog() behavior. It is very important to understand how syslog() implementation works, focusing on Linux glibc code:
**syslog() creates a temporary copy of the logged message in so-called memory-buffer stream by using 2 malloc() calls**:
- **syslog's 1st malloc:** Allocates general stream description structures
- **syslog's 2nd malloc:** Creates actual buffer, which would contain logged message.
To achieve the exploit, the following conditions are necessary:
- **User-dependent syslog() data:** Ensure the syslog() data is influenced by user input (e.g., Sendmail log messages that describe transferred mail traffic).
- **Memory block alignment:** The 2nd global memory block (global_ptr2) must be aligned to be reused in the 2nd malloc() call of open_memstream() of syslog().
Steps for the exploit:
- **1st sighndlr() call:** The malloc() here should be interrupted by the 2nd sighndlr(), which the heap head doesn't update to the back of this allocated memory yet. This can cause the following malloc() uses the overlapped memory pointer.
- **2nd sighndlr() call:** If entering this situation, the malloc() of the 2nd sighndlr() would re-use this memory and overwrite this area, including system fuction call tables (e.g., __fread_unlocked()), which is manipulated via SSH operations to form a specific heap pattern, with user-dependent syslog() buffer.
> **Note:** The attack is not limited to two global buffers. It can involve any number of freed buffers, provided one is correctly aligned. Additional possibilities are related to interrupting free() chain by precise SIGTERM delivery and/or influencing buffer sizes / heap data order by using different input data patterns.
>
> Many classic memory management flaws may be exploitable with a little effort. Of particular note, calling free() twice on the same pointer is not uncommon. This will be an exploitable flaw if, after the first free() call, the memory is re-allocated and filled with user controlled data.
:::
Refs:
- :+1: [new SSH exploit is absolutely wild - Low Level Learning](https://www.youtube.com/watch?v=Rj3sTAMYNQk)
- :+1: [[Issues & Solutions] regreSSHion: RCE in OpenSSH's server, on glibc-based Linux systems - Qualys Security Advisory](https://www.qualys.com/2024/07/01/cve-2024-6387/regresshion.txt)
- [[Exploit Methods] Understanding, exploiting and preventing signal-handling related vulnerabilities - Michal Zalewski, 2001](https://lcamtuf.coredump.cx/signals.txt)
- [[Patches] OpenSSH 9.8 Release Notes - OpenSSH](https://www.openssh.com/txt/release-9.8)
### XZ
On 29 March 2024, Andres Freund, a PostgreSQL developer working at Microsoft, announced that he had found a backdoor in XZ Utils. Compressed test files had been added to the code for setting up the backdoor via additions to the configure script in the tar files. He started his investigation because "After observing a few odd symptoms around liblzma (part of the xz package)" as he found that ssh logins using sshd were "taking a lot of CPU, valgrind errors".
[secret backdoor found in open source software (xz situation breakdown) - Low Level Learning](https://www.youtube.com/watch?v=jqjtNDtbDNI)
### Cellular Cyber Attack
- :+1: [行動寬頻資安技術的剖析 - 蔡志明](https://ejournal.stpi.narl.org.tw/sd/download?source=10801-03.pdf&vlId=64ceef26377a48aa844a239cc06101c4&nd=1&ds=1)
- [黑帽駭客大會:3G/4G 網路協定漏洞可能洩露用戶行蹤,目前無解 - IThome](https://www.ithome.com.tw/news/115812)
## Capture the Flag (CTF)
### Overviews
- [Web Security / 拜託別 Pwn 我啦! - 黑糖不是碳 - IThome 系列文](https://ithelp.ithome.com.tw/users/20115060/ironman/2414)
- [How to play CTF - ktecv2000 - GitHub](https://github.com/ktecv2000/How-to-play-CTF)
### Practices
- [picoCTF](https://picoctf.org/)
- [OverTheWire: War Games](https://overthewire.org/wargames/)
- [pwnable.kr](https://pwnable.kr/)
### Useful Tools
- [checksec.sh - slimm609 - GitHub](https://github.com/slimm609/checksec.sh)
```sh
$ checksec --file=/bin/ls
RELRO STACK CANARY NX PIE RPATH RUNPATH FILE
Partial RELRO Canary found NX enabled No PIE No RPATH No RUNPATH /bin/ls
```
- [gdb-peda - GitHub](https://github.com/longld/peda)