X509Bundle.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. #include "X509Bundle.h"
  2. #include <mbedtls/md.h> // for mbedtls_md, mbedtls_md_get_size
  3. #include <mbedtls/pk.h> // for mbedtls_pk_can_do, mbedtls_pk_pa...
  4. #include <mbedtls/ssl.h> // for mbedtls_ssl_conf_ca_chain, mbedt...
  5. #include <mbedtls/x509.h> // for mbedtls_x509_buf, MBEDTLS_ERR_X5...
  6. #include <stdlib.h> // for free, calloc
  7. #include <string.h> // for memcmp, memcpy
  8. #include <stdexcept> // for runtime_error
  9. #include "BellLogger.h" // for AbstractLogger, BELL_LOG
  10. using namespace bell::X509Bundle;
  11. typedef struct crt_bundle_t {
  12. const uint8_t** crts;
  13. uint16_t num_certs;
  14. size_t x509_crt_bundle_len;
  15. } crt_bundle_t;
  16. static std::vector<uint8_t> bundleBytes;
  17. static constexpr auto TAG = "X509Bundle";
  18. static constexpr auto CRT_HEADER_OFFSET = 4;
  19. static constexpr auto BUNDLE_HEADER_OFFSET = 2;
  20. static mbedtls_x509_crt s_dummy_crt;
  21. static bool s_should_verify_certs = false;
  22. static crt_bundle_t s_crt_bundle;
  23. #ifndef MBEDTLS_PRIVATE
  24. #define MBEDTLS_PRIVATE(member) member
  25. #endif
  26. int bell::X509Bundle::crtCheckCertificate(mbedtls_x509_crt* child,
  27. const uint8_t* pub_key_buf,
  28. size_t pub_key_len) {
  29. int ret = 0;
  30. mbedtls_x509_crt parent;
  31. const mbedtls_md_info_t* md_info;
  32. unsigned char hash[MBEDTLS_MD_MAX_SIZE];
  33. mbedtls_x509_crt_init(&parent);
  34. if ((ret = mbedtls_pk_parse_public_key(&parent.pk, pub_key_buf,
  35. pub_key_len)) != 0) {
  36. BELL_LOG(error, TAG, "PK parse failed with error 0x%04x, key len = %d", ret,
  37. pub_key_len);
  38. goto cleanup;
  39. }
  40. // Fast check to avoid expensive computations when not necessary
  41. if (!mbedtls_pk_can_do(&parent.pk, child->MBEDTLS_PRIVATE(sig_pk))) {
  42. BELL_LOG(error, TAG, "Simple compare failed");
  43. ret = -1;
  44. goto cleanup;
  45. }
  46. md_info = mbedtls_md_info_from_type(child->MBEDTLS_PRIVATE(sig_md));
  47. if ((ret = mbedtls_md(md_info, child->tbs.p, child->tbs.len, hash)) != 0) {
  48. BELL_LOG(error, TAG, "Internal mbedTLS error %X", ret);
  49. goto cleanup;
  50. }
  51. if ((ret = mbedtls_pk_verify_ext(
  52. child->MBEDTLS_PRIVATE(sig_pk), child->MBEDTLS_PRIVATE(sig_opts),
  53. &parent.pk, child->MBEDTLS_PRIVATE(sig_md), hash,
  54. mbedtls_md_get_size(md_info), child->MBEDTLS_PRIVATE(sig).p,
  55. child->MBEDTLS_PRIVATE(sig).len)) != 0) {
  56. BELL_LOG(error, TAG, "PK verify failed with error %X", ret);
  57. goto cleanup;
  58. }
  59. cleanup:
  60. mbedtls_x509_crt_free(&parent);
  61. return ret;
  62. }
  63. /* This callback is called for every certificate in the chain. If the chain
  64. * is proper each intermediate certificate is validated through its parent
  65. * in the x509_crt_verify_chain() function. So this callback should
  66. * only verify the first untrusted link in the chain is signed by the
  67. * root certificate in the trusted bundle
  68. */
  69. int bell::X509Bundle::crtVerifyCallback(void* buf, mbedtls_x509_crt* crt,
  70. int depth, uint32_t* flags) {
  71. mbedtls_x509_crt* child = crt;
  72. /* It's OK for a trusted cert to have a weak signature hash alg.
  73. as we already trust this certificate */
  74. uint32_t flags_filtered = *flags & ~(MBEDTLS_X509_BADCERT_BAD_MD);
  75. if (flags_filtered != MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
  76. return 0;
  77. }
  78. if (s_crt_bundle.crts == NULL) {
  79. BELL_LOG(error, TAG, "No certificates in bundle");
  80. return MBEDTLS_ERR_X509_FATAL_ERROR;
  81. }
  82. BELL_LOG(debug, TAG, "%d certificates in bundle", s_crt_bundle.num_certs);
  83. size_t name_len = 0;
  84. const uint8_t* crt_name;
  85. bool crt_found = false;
  86. int start = 0;
  87. int end = s_crt_bundle.num_certs - 1;
  88. int middle = (end - start) / 2;
  89. /* Look for the certificate using binary search on subject name */
  90. while (start <= end) {
  91. name_len = s_crt_bundle.crts[middle][0] << 8 | s_crt_bundle.crts[middle][1];
  92. crt_name = s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET;
  93. int cmp_res = memcmp(child->issuer_raw.p, crt_name, name_len);
  94. if (cmp_res == 0) {
  95. crt_found = true;
  96. break;
  97. } else if (cmp_res < 0) {
  98. end = middle - 1;
  99. } else {
  100. start = middle + 1;
  101. }
  102. middle = (start + end) / 2;
  103. }
  104. int ret = MBEDTLS_ERR_X509_FATAL_ERROR;
  105. if (crt_found) {
  106. size_t key_len =
  107. s_crt_bundle.crts[middle][2] << 8 | s_crt_bundle.crts[middle][3];
  108. ret = crtCheckCertificate(
  109. child, s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET + name_len,
  110. key_len);
  111. } else {
  112. BELL_LOG(error, TAG, "Certificate not found in bundle");
  113. }
  114. if (ret == 0) {
  115. BELL_LOG(info, TAG, "Certificate validated");
  116. *flags = 0;
  117. return 0;
  118. }
  119. BELL_LOG(info, TAG, "Failed to verify certificate");
  120. return MBEDTLS_ERR_X509_FATAL_ERROR;
  121. }
  122. /* Initialize the bundle into an array so we can do binary search for certs,
  123. the bundle generated by the python utility is already presorted by subject name
  124. */
  125. void bell::X509Bundle::init(const uint8_t* x509_bundle, size_t bundle_size) {
  126. if (bundle_size < BUNDLE_HEADER_OFFSET + CRT_HEADER_OFFSET) {
  127. throw std::runtime_error("Invalid certificate bundle");
  128. }
  129. uint16_t num_certs = (x509_bundle[0] << 8) | x509_bundle[1];
  130. const uint8_t** crts =
  131. (const uint8_t**)calloc(num_certs, sizeof(x509_bundle));
  132. if (crts == NULL) {
  133. throw std::runtime_error("Unable to allocate memory for bundle");
  134. }
  135. bundleBytes.resize(bundle_size);
  136. memcpy(bundleBytes.data(), x509_bundle, bundle_size);
  137. const uint8_t* cur_crt;
  138. /* This is the maximum region that is allowed to access */
  139. const uint8_t* bundle_end = bundleBytes.data() + bundle_size;
  140. cur_crt = bundleBytes.data() + BUNDLE_HEADER_OFFSET;
  141. for (int i = 0; i < num_certs; i++) {
  142. crts[i] = cur_crt;
  143. if (cur_crt + CRT_HEADER_OFFSET > bundle_end) {
  144. free(crts);
  145. throw std::runtime_error("Invalid certificate bundle");
  146. }
  147. size_t name_len = cur_crt[0] << 8 | cur_crt[1];
  148. size_t key_len = cur_crt[2] << 8 | cur_crt[3];
  149. cur_crt = cur_crt + CRT_HEADER_OFFSET + name_len + key_len;
  150. }
  151. if (cur_crt > bundle_end) {
  152. free(crts);
  153. throw std::runtime_error("Invalid certificate bundle");
  154. }
  155. /* The previous crt bundle is only updated when initialization of the
  156. * current crt_bundle is successful */
  157. /* Free previous crt_bundle */
  158. free(s_crt_bundle.crts);
  159. s_crt_bundle.num_certs = num_certs;
  160. s_crt_bundle.crts = crts;
  161. // Enable certificate verification
  162. s_should_verify_certs = true;
  163. }
  164. void bell::X509Bundle::attach(mbedtls_ssl_config* conf) {
  165. /* point to a dummy certificate
  166. * This is only required so that the
  167. * cacert_ptr passes non-NULL check during handshake
  168. */
  169. mbedtls_ssl_config* ssl_conf = (mbedtls_ssl_config*)conf;
  170. mbedtls_x509_crt_init(&s_dummy_crt);
  171. mbedtls_ssl_conf_ca_chain(ssl_conf, &s_dummy_crt, NULL);
  172. mbedtls_ssl_conf_verify(ssl_conf, crtVerifyCallback, NULL);
  173. }
  174. bool bell::X509Bundle::shouldVerify() {
  175. return s_should_verify_certs;
  176. }