1 #include "mbedtls/error.h"
2 #include <string.h>
3 #include <stdio.h>
4
5 // test_code checks that the provided code results in the provided error string for any size
6 // buffer. It calls mbedtls_strerror() to fill a buffer that is from 1 to 100 bytes in length
7 // and then checks that the buffer contents is OK and that a few guard bytes before and after
8 // the buffer were not overwritten.
test_code(int code,char * str)9 int test_code(int code, char *str) {
10 char buf[100];
11 int ok = 1;
12 int res;
13
14 // test zero-length buffer
15 memset(buf, -3, 100);
16 mbedtls_strerror(code, buf + 4, 0);
17 for (int i = 0; i < 10; i++) {
18 if (buf[i] != -3) {
19 printf("Error: guard overwritten buflen=0 i=%d buf[i]=%d\n", i, buf[i]);
20 ok = 0;
21 }
22 }
23
24 // test
25 for (size_t buflen = 1; buflen < 90; buflen++) {
26 memset(buf, -3, 100);
27 mbedtls_strerror(code, buf + 4, buflen);
28 for (int i = 0; i < 4; i++) {
29 if (buf[i] != -3) {
30 printf("Error: pre-guard overwritten buflen=%d i=%d buf[i]=%d\n", buflen, i, buf[i]);
31 ok = 0;
32 }
33 }
34 for (int i = 4 + buflen; i < 100; i++) {
35 if (buf[i] != -3) {
36 printf("Error: post-guard overwritten buflen=%d i=%d buf[i]=%d\n", buflen, i, buf[i]);
37 ok = 0;
38 }
39 }
40 char exp[100];
41 strncpy(exp, str, buflen);
42 exp[buflen - 1] = 0;
43 if (strcmp(buf + 4, exp) != 0) {
44 printf("Error: expected %s, got %s\n", exp, buf);
45 ok = 0;
46 }
47 }
48
49 printf("Test %x -> %s is %s\n", code, str, ok?"OK":"*** BAD ***");
50 }
51
main()52 int main() {
53 test_code(0x7200, "MBEDTLS_ERR_SSL_INVALID_RECORD");
54 test_code(0x7780, "MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE");
55 test_code(0x0074, "MBEDTLS_ERR_SHA256_BAD_INPUT_DATA");
56 test_code(0x6600 | 0x0074, "MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH+MBEDTLS_ERR_SHA256_BAD_INPUT_DATA");
57 test_code(103, "MBEDTLS_ERR_UNKNOWN (0x0067)");
58 }
59