Skip to content

Commit 7c4961e

Browse files
Add basic canary check to BSSL stack thunk (#6156)
On return from a BSSL call, check that the last element of the stack is still untouched. If it is modified, print an error and abort(). Will catch problems like #6143 many times with an informative error message instead of corrupting the heap and having a random crash sometime later.
1 parent d83eabe commit 7c4961e

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

cores/esp8266/StackThunk.cpp

+8-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ uint32_t *stack_thunk_top = NULL;
3636
uint32_t *stack_thunk_save = NULL; /* Saved A1 while in BearSSL */
3737
uint32_t stack_thunk_refcnt = 0;
3838

39-
#define _stackSize (5750/4)
39+
#define _stackSize (5748/4)
4040
#define _stackPaint 0xdeadbeef
4141

4242
/* Add a reference, and allocate the stack if necessary */
@@ -124,4 +124,11 @@ void stack_thunk_dump_stack()
124124
ets_printf("<<<stack<<<\n");
125125
}
126126

127+
/* Called when the stack overflow is detected by a thunk. Main memory is corrupted at this point. Do not return. */
128+
void stack_thunk_fatal_overflow()
129+
{
130+
ets_printf("FATAL ERROR: BSSL stack overflow\n");
131+
abort();
132+
}
133+
127134
};

cores/esp8266/StackThunk.h

+10
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ extern uint32_t stack_thunk_get_stack_bot();
4141
extern uint32_t stack_thunk_get_cont_sp();
4242
extern uint32_t stack_thunk_get_max_usage();
4343
extern void stack_thunk_dump_stack();
44+
extern void stack_thunk_fatal_overflow();
4445

4546
// Globals required for thunking operation
4647
extern uint32_t *stack_thunk_ptr;
@@ -53,6 +54,7 @@ extern uint32_t stack_thunk_refcnt;
5354
__asm("\n\
5455
.text\n\
5556
.literal_position\n\
57+
.literal .LC_STACK_VALUE"#fcnToThunk", 0xdeadbeef\n\
5658
\n\
5759
.text\n\
5860
.global thunk_"#fcnToThunk"\n\
@@ -67,6 +69,14 @@ thunk_"#fcnToThunk":\n\
6769
movi a15, stack_thunk_top /* Load A1(SP) with thunk stack */\n\
6870
l32i.n a1, a15, 0\n\
6971
call0 "#fcnToThunk" /* Do the call */\n\
72+
/* Check the stack canary wasn't overwritten */\n\
73+
movi a15, stack_thunk_ptr\n\
74+
l32i.n a15, a15, 0 /* A15 now has the pointer to stack end*/ \n\
75+
l32i.n a15, a15, 0 /* A15 now has contents of last stack entry */\n\
76+
l32r a0, .LC_STACK_VALUE"#fcnToThunk" /* A0 now has the check value */\n\
77+
beq a0, a15, .L1"#fcnToThunk"\n\
78+
call0 stack_thunk_fatal_overflow\n\
79+
.L1"#fcnToThunk":\n\
7080
movi a15, stack_thunk_save /* Restore A1(SP) */\n\
7181
l32i.n a1, a15, 0\n\
7282
l32i.n a15, a1, 8 /* Restore the saved registers */\n\

0 commit comments

Comments
 (0)