標籤:
/* * Initialize the stackprotector canary value. * * NOTE: this must only be called from functions that never return, * and it must always be inlined. */static __always_inline void boot_init_stack_canary(void){ u64 canary; u64 tsc;#ifdef CONFIG_X86_64 BUILD_BUG_ON(offsetof(union irq_stack_union, stack_canary) != 40);#endif /* * We both use the random pool and the current TSC as a source * of randomness. The TSC only matters for very early init, * there it already has some randomness on most systems. Later * on during the bootup the random pool has true entropy too. */ get_random_bytes(&canary, sizeof(canary)); tsc = __native_read_tsc(); canary += tsc + (tsc << 32UL); current->stack_canary = canary;#ifdef CONFIG_X86_64 this_cpu_write(irq_stack_union.stack_canary, canary);#else this_cpu_write(stack_canary.canary, canary);#endif}
該函數主要用於初始化“金絲雀“——canary的值。
用於防止棧溢出攻擊。
關於棧溢出攻擊,有兩篇非常好的文章:http://www.ibm.com/developerworks/cn/linux/l-overflow/http://blog.aliyun.com/1126
get_random_bytes擷取一個核心隨機數,賦值給canary。
__native_read_tsc返回一個與TSC相關的數值。
TSC:Time Stamp Counter,是Linux下三種時鐘的一種,也是CPU裡面的一個64位的寄存器,每一個CPU刻度其數值加1.
canary += tsc + (tsc << 32UL);
終於得到canary的值,並將其賦值給current->stack_canary——當前進程的stack_canary成員。
通常採用兩種方法防止棧緩衝溢出:
1 發生棧緩衝溢出時將其檢測出來。從而阻止通過惡意代碼更改指令指標;
2 未直接檢測棧緩衝溢出的情況下,預防惡意代碼攻擊。
stack canary技術屬於第一中方法的一種。在惡意代碼運行前,可以發現棧緩衝溢出。
程式啟動時,canary的值被儲存在函數返回地址之前。大部分棧緩衝溢出攻擊是從記憶體的低位向高位覆寫記憶體,所以為了覆寫返回地址。必須覆寫canary。
所以在使用返回地址之前,查看canary的值。就行確認是否發生了棧緩衝溢出攻擊。
start_kernel——boot_init_stack_canary