-
Notifications
You must be signed in to change notification settings - Fork 2
/
stack.c
97 lines (82 loc) · 2.65 KB
/
stack.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "api.h"
#include "randombytes.h"
#include "stm32wrapper.h"
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 0x16000
static void send_stack_usage(const char *s, unsigned int c) {
char outs[120];
send_USART_str(s);
sprintf(outs, "%u\n", c);
send_USART_str(outs);
}
unsigned int canary_size = MAX_SIZE;
volatile unsigned char *p;
unsigned int c;
uint8_t canary = 0x42;
unsigned char key_a[CRYPTO_BYTES], key_b[CRYPTO_BYTES];
unsigned char pk[CRYPTO_PUBLICKEYBYTES];
unsigned char sendb[CRYPTO_CIPHERTEXTBYTES];
unsigned char sk_a[CRYPTO_SECRETKEYBYTES];
unsigned int stack_key_gen, stack_encaps, stack_decaps;
#define FILL_STACK() \
p = &a; \
while (p > &a - canary_size) \
*(p--) = canary;
#define CHECK_STACK() \
c = canary_size; \
p = &a - canary_size + 1; \
while (*p == canary && p < &a) { \
p++; \
c--; \
}
static int test_keys(void) {
volatile unsigned char a;
// Alice generates a public key
FILL_STACK()
crypto_kem_keypair(pk, sk_a);
CHECK_STACK()
if(c >= canary_size) return -1;
stack_key_gen = c;
// Bob derives a secret key and creates a response
FILL_STACK()
crypto_kem_enc(sendb, key_b, pk);
CHECK_STACK()
if(c >= canary_size) return -1;
stack_encaps = c;
// Alice uses Bobs response to get her secret key
FILL_STACK()
crypto_kem_dec(key_a, sendb, sk_a);
CHECK_STACK()
if(c >= canary_size) return -1;
stack_decaps = c;
if (memcmp(key_a, key_b, CRYPTO_BYTES)){
return -1;
} else {
send_stack_usage("key gen stack usage", stack_key_gen);
send_stack_usage("encaps stack usage", stack_encaps);
send_stack_usage("decaps stack usage", stack_decaps);
send_USART_str("OK KEYS\n");
return 0;
}
}
int main(void) {
clock_setup(CLOCK_FAST);
gpio_setup();
usart_setup(115200);
rng_enable();
// marker for automated benchmarks
send_USART_str("==========================");
canary_size = MAX_SIZE;
while(test_keys()){
canary_size -= 0x1000;
if(canary_size == 0) {
send_USART_str("failed to measure stack usage.\n");
break;
}
}
// marker for automated benchmarks
send_USART_str("#");
while (1);
return 0;
}