#include #include #include #include #include #include #include #include #include "mbedtls/base64.h" #include "mbedtls/x509_crt.h" ssize_t i32read_file( uint8_t* pu8buffer, size_t size, uint8_t* pu8file ) { ssize_t r = -1; int fd = -1; do{ if( NULL == pu8file ) { break; } fd = open( pu8file, O_RDONLY ); if( -1 == fd ) { break; } r = read( fd, pu8buffer, size ); if( -1 == r ) { break; } }while(0); if( -1 != fd ) { close( fd ); } return( r ); } static int32_t i32parse_base64_cert( mbedtls_x509_crt* chain, uint8_t* pu8file ) { int32_t r = -1; do{ uint8_t pu8cert_base64[2048]; uint8_t pu8cert_der[2048]; size_t olen = i32read_file( pu8cert_base64, sizeof(pu8cert_base64), pu8file ); if( -1 == olen ) { printf( "failed! unable to read cert file\r\n" ); break; } mbedtls_x509_crt_init(chain); r = mbedtls_base64_decode( pu8cert_der, sizeof(pu8cert_der), &olen, pu8cert_base64, olen ); if( EXIT_SUCCESS != r ) { printf( "failed! unable to decode cert: 0x%04x\r\n", -r ); break; } r = mbedtls_x509_crt_parse_der( chain, pu8cert_der, olen ); if( EXIT_SUCCESS != r ) { printf( "failed! unable to parse cert: 0x%04x\r\n", -r ); break; } }while(0); return( r ); } void verify_cert_chain_driver( void ) { int32_t r = -1; mbedtls_x509_crt root_ca; mbedtls_x509_crt chain; do{ r = i32parse_base64_cert( &root_ca, "x509-level0.base64" ); if( EXIT_SUCCESS != r ) { printf( "failed! unable to read, parse L0: 0x%04x\r\n", -r ); break; } r = i32parse_base64_cert( &chain, "x509-level1.base64" ); if( EXIT_SUCCESS != r ) { printf( "failed! unable to read, parse L1: 0x%04x\r\n", -r ); break; } r = i32parse_base64_cert( &chain, "x509-level2.base64" ); if( EXIT_SUCCESS != r ) { printf( "failed! unable to read, parse L2: 0x%04x\r\n", -r ); break; } uint32_t flags = 0; r = mbedtls_x509_crt_verify( &chain, &root_ca, NULL, NULL, &flags, NULL, NULL ); if( EXIT_SUCCESS != r ) { printf( "failed! unable to verify Chain with CA: 0x%04x\r\n", -r ); printf( "flag: %u\r\n", flags ); break; } printf( "Verify OK\r\n" ); }while(0); } int main() { verify_cert_chain_driver(); return( 0 ); }