# HW Protection Here, "protection" does not mean protection on security-related issues(e.g. malwares, cyber attack, etc.). --- ## Dual-Mode Operation ### What to protect? - Sharing system resources requires OS to ensure that **any incorrect program cannot cause other programs to execute incorrectly** - Provide **hardware support** to differentiate between: - User Mode: execution done on behalf of user - Kernel Mode: execution done on behalf of OS ### How to differentiate? - <span style="color:orange">**Mode bit added to hardware to indicate the current mode: kernel(0) or user(1)**</span> - When an interrupt/trap or fault occurs, hardware switches to monitor mode - <span style="color:orange">**Privileged instructions**</span>: (特權指令,一個寫死的set) - <span style="color:orange">**Executed only in monitor mode**</span> - <span style="color:orange">Requested by users (must come through **system calls**)</span> 使用者一定要透過system call才能執行特權指令,如果直接在自己寫的program執行,OS會去檢查mode bit,如果不是kernel mode就會終止本次執行 --- ## I/O Protection - <span style="color:orange">**All I/O instructions are privileged instructions**</span> - Any I/O device is shared between users - Must ensure a user program could never gain control of the computer (i.e. a user program stores a new address in the interrupt vector) - 也就是說只保護I/O是不夠的 - 駭客有可能繞過I/O直接修改memory中interrupt vector裡面的地址,讓電腦去做其他指令,所以會需要memory protection --- ## Memory Protection - Proctect - interrupt vector and service routines - **data access and over-write from other programs** - HW support: <span style="color:orange">**two register for legal address determination**</span> 沒有透過OS就去access超出範圍的空間時,就會發生segmentation fault - **Base register**: 連續空間的起始點(smallest legal physical memory address) - **Limit register**: 這個空間size多少 ![image](https://hackmd.io/_uploads/rJsALo-ukl.png) --- ## Hardware Address Protection ![image](https://hackmd.io/_uploads/ry1VviWdkx.png) - **Load or change the values of base/limit register is privileged instructions** - Example: malloc() -> will invoke system call to change base/limit register --- ## CPU Protection - Prevent user program from not returning control - 避免程式霸佔CPU(包括OS) - HW support: <span style="color:orange">**Timer**</span> -- interrupts computer after specific period - Timer is decremented every clock tick. When timer reaches 0, an interrupt occurrs - Timer is commonly used to implement time-sharing - **Load(over-write)-timer** is a privileged instruction Timer到時間後就會丟出一個interrup來打斷目前執行的程式,然後OS就會接管並執行scheduling,決定下一支要執行的程式或是處理interrupt --- #### 如何判斷這個指令是否為特權指令? 如果user擅自去call這個指令,會危害到系統時,這些指令就是特權指令 #### References https://secinitiat.medium.com/%E7%89%B9%E6%AC%8A%E6%8C%87%E4%BB%A4-privileged-instruction-%E7%B3%BB%E7%B5%B1%E5%91%BC%E5%8F%AB-system-call-bead9402516