engine_passthrough.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. *
  3. * Copyright 2020 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // This is a sample openSSL engine which tests the openSSL
  19. // engine plugability with gRPC.
  20. // This sample engine expects KeyId to be actual PEM encoded
  21. // key itself and just calls standard openSSL functions.
  22. #include <openssl/bio.h>
  23. #include <openssl/engine.h>
  24. #include <openssl/pem.h>
  25. #ifndef OPENSSL_IS_BORINGSSL
  26. #include <stdio.h>
  27. #include <string.h>
  28. extern "C" {
  29. static const char engine_id[] = "libengine_passthrough";
  30. static const char engine_name[] = "A passthrough engine for private keys";
  31. static int e_passthrough_idx = -1;
  32. static int e_passthrough_init(ENGINE* e) {
  33. if (e_passthrough_idx < 0) {
  34. e_passthrough_idx = ENGINE_get_ex_new_index(0, NULL, NULL, NULL, 0);
  35. if (e_passthrough_idx < 0) return 0;
  36. }
  37. return 1;
  38. }
  39. EVP_PKEY* e_passthrough_load_privkey(ENGINE* eng, const char* key_id,
  40. UI_METHOD* ui_method,
  41. void* callback_data) {
  42. EVP_PKEY* pkey = NULL;
  43. BIO* pem = BIO_new_mem_buf((void*)key_id, (int)(strlen(key_id)));
  44. if (pem == NULL) return NULL;
  45. pkey = PEM_read_bio_PrivateKey(pem, NULL, NULL, (void*)"");
  46. BIO_free(pem);
  47. return pkey;
  48. }
  49. int passthrough_bind_helper(ENGINE* e, const char* id) {
  50. if (id && strcmp(id, engine_id)) {
  51. return 0;
  52. }
  53. if (!ENGINE_set_id(e, engine_id) || !ENGINE_set_name(e, engine_name) ||
  54. !ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL) ||
  55. !ENGINE_set_init_function(e, e_passthrough_init) ||
  56. !ENGINE_set_load_privkey_function(e, e_passthrough_load_privkey)) {
  57. return 0;
  58. }
  59. return 1;
  60. }
  61. IMPLEMENT_DYNAMIC_BIND_FN(passthrough_bind_helper)
  62. IMPLEMENT_DYNAMIC_CHECK_FN()
  63. }
  64. #endif // OPENSSL_IS_BORINGSSL