]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - wimboot/wimboot-2.7.3/src/cookie.c
1.1.07 release
[Ventoy.git] / wimboot / wimboot-2.7.3 / src / cookie.c
1 /*
2 * Copyright (C) 2021 Michael Brown <mbrown@fensystems.co.uk>.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301, USA.
18 */
19
20 /**
21 * @file
22 *
23 * Stack cookie
24 *
25 */
26
27 #include "wimboot.h"
28
29 /** Stack cookie */
30 unsigned long __stack_chk_guard;
31
32 /**
33 * Construct stack cookie value
34 *
35 */
36 static __attribute__ (( noinline )) unsigned long make_cookie ( void ) {
37 union {
38 struct {
39 uint32_t eax;
40 uint32_t edx;
41 } __attribute__ (( packed ));
42 unsigned long tsc;
43 } u;
44 unsigned long cookie;
45
46 /* We have no viable source of entropy. Use the CPU timestamp
47 * counter, which will have at least some minimal randomness
48 * in the low bits by the time we are invoked.
49 */
50 __asm__ ( "rdtsc" : "=a" ( u.eax ), "=d" ( u.edx ) );
51 cookie = u.tsc;
52
53 /* Ensure that the value contains a NUL byte, to act as a
54 * runaway string terminator. Construct the NUL using a shift
55 * rather than a mask, to avoid losing valuable entropy in the
56 * lower-order bits.
57 */
58 cookie <<= 8;
59
60 return cookie;
61 }
62
63 /**
64 * Initialise stack cookie
65 *
66 * This function must not itself use stack guard
67 */
68 void init_cookie ( void ) {
69
70 /* Set stack cookie value
71 *
72 * This function must not itself use stack protection, since
73 * the change in the stack guard value would trigger a false
74 * positive.
75 *
76 * There is unfortunately no way to annotate a function to
77 * exclude the use of stack protection. We must therefore
78 * rely on correctly anticipating the compiler's decision on
79 * the use of stack protection.
80 */
81 __stack_chk_guard = make_cookie();
82 }
83
84 /**
85 * Abort on stack check failure
86 *
87 */
88 void __stack_chk_fail ( void ) {
89
90 /* Abort program */
91 die ( "Stack check failed\n" );
92 }