Created
December 4, 2021 03:13
-
-
Save FGasper/43758d13e987518009d18ec8951ffcbb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To compile: | |
// cc -I./include mbedtls_test.c library/libmbedtls.a library/libmbedx509.a library/libmbedcrypto.a | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <assert.h> | |
#include "mbedtls/net_sockets.h" | |
#include "mbedtls/ssl.h" | |
#include "mbedtls/entropy.h" | |
#include "mbedtls/ctr_drbg.h" | |
#include "mbedtls/error.h" | |
#include "mbedtls/version.h" | |
#include "mbedtls/x509.h" | |
#define HOSTNAME "google.com" | |
#define TRUST_PATH "/etc/ssl/cert.pem" | |
int main() { | |
mbedtls_entropy_context entropy; | |
mbedtls_entropy_init( &entropy ); | |
mbedtls_ctr_drbg_context ctr_drbg; | |
mbedtls_ctr_drbg_init( &ctr_drbg ); | |
int result = mbedtls_ctr_drbg_seed( | |
&ctr_drbg, | |
mbedtls_entropy_func, | |
&entropy, | |
NULL, 0 | |
); | |
assert(!result); | |
printf("seeded entropy\n"); | |
mbedtls_net_context net_context; | |
result = mbedtls_net_connect(&net_context, HOSTNAME, "443", 0); | |
assert(!result); | |
printf("mbedtls connected\n"); | |
mbedtls_ssl_config conf; | |
mbedtls_ssl_config_init( &conf ); | |
result = mbedtls_ssl_config_defaults( | |
&conf, | |
MBEDTLS_SSL_IS_CLIENT, | |
MBEDTLS_SSL_TRANSPORT_STREAM, | |
MBEDTLS_SSL_PRESET_DEFAULT | |
); | |
assert(!result); | |
mbedtls_ssl_conf_rng( &conf, mbedtls_ctr_drbg_random, &ctr_drbg ); | |
mbedtls_ssl_context ssl; | |
mbedtls_ssl_init(&ssl); | |
result = mbedtls_ssl_setup( &ssl, &conf ); | |
assert(!result); | |
mbedtls_x509_crt cacert; | |
mbedtls_x509_crt_init(&cacert); | |
result = mbedtls_x509_crt_parse_file(&cacert, TRUST_PATH); | |
assert(!result); | |
printf("trust loaded ok\n"); | |
mbedtls_ssl_conf_ca_chain(&conf, &cacert, NULL); | |
result = mbedtls_ssl_set_hostname(&ssl, HOSTNAME); | |
assert(!result); | |
printf("SNI set ok\n"); | |
mbedtls_ssl_set_bio( | |
&ssl, | |
&net_context, | |
mbedtls_net_send, | |
mbedtls_net_recv, | |
mbedtls_net_recv_timeout | |
); | |
result = mbedtls_ssl_handshake(&ssl); | |
printf("handshake tried\n"); | |
if (result) { | |
char errstr[200]; | |
mbedtls_strerror(result, errstr, sizeof(errstr)); | |
fprintf(stderr, "handshake: %s\n", errstr); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment