tls_certificate_verifier.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. //
  2. // Copyright 2021 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. #ifndef GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H
  17. #define GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H
  18. #include <functional>
  19. #include <map>
  20. #include <memory>
  21. #include <utility>
  22. #include <vector>
  23. #include <grpc/grpc_security_constants.h>
  24. #include <grpc/status.h>
  25. #include <grpc/support/log.h>
  26. #include <grpcpp/impl/grpc_library.h>
  27. #include <grpcpp/impl/sync.h>
  28. #include <grpcpp/support/config.h>
  29. #include <grpcpp/support/status.h>
  30. #include <grpcpp/support/string_ref.h>
  31. // TODO(yihuazhang): remove the forward declaration here and include
  32. // <grpc/grpc_security.h> directly once the insecure builds are cleaned up.
  33. typedef struct grpc_tls_custom_verification_check_request
  34. grpc_tls_custom_verification_check_request;
  35. typedef struct grpc_tls_certificate_verifier grpc_tls_certificate_verifier;
  36. typedef struct grpc_tls_certificate_verifier_external
  37. grpc_tls_certificate_verifier_external;
  38. typedef void (*grpc_tls_on_custom_verification_check_done_cb)(
  39. grpc_tls_custom_verification_check_request* request, void* callback_arg,
  40. grpc_status_code status, const char* error_details);
  41. extern "C" grpc_tls_certificate_verifier*
  42. grpc_tls_certificate_verifier_external_create(
  43. grpc_tls_certificate_verifier_external* external_verifier);
  44. namespace grpc {
  45. namespace experimental {
  46. // Contains the verification-related information associated with a connection
  47. // request. Users should not directly create or destroy this request object, but
  48. // shall interact with it through CertificateVerifier's Verify() and Cancel().
  49. class TlsCustomVerificationCheckRequest {
  50. public:
  51. explicit TlsCustomVerificationCheckRequest(
  52. grpc_tls_custom_verification_check_request* request);
  53. ~TlsCustomVerificationCheckRequest() {}
  54. grpc::string_ref target_name() const;
  55. grpc::string_ref peer_cert() const;
  56. grpc::string_ref peer_cert_full_chain() const;
  57. grpc::string_ref common_name() const;
  58. // The subject name of the root certificate used to verify the peer chain
  59. // If verification fails or the peer cert is self-signed, this will be an
  60. // empty string. If verification is successful, it is a comma-separated list,
  61. // where the entries are of the form "FIELD_ABBREVIATION=string"
  62. // ex: "CN=testca,O=Internet Widgits Pty Ltd,ST=Some-State,C=AU"
  63. // ex: "CN=GTS Root R1,O=Google Trust Services LLC,C=US"
  64. grpc::string_ref verified_root_cert_subject() const;
  65. std::vector<grpc::string_ref> uri_names() const;
  66. std::vector<grpc::string_ref> dns_names() const;
  67. std::vector<grpc::string_ref> email_names() const;
  68. std::vector<grpc::string_ref> ip_names() const;
  69. grpc_tls_custom_verification_check_request* c_request() { return c_request_; }
  70. private:
  71. grpc_tls_custom_verification_check_request* c_request_ = nullptr;
  72. };
  73. // The base class of all internal verifier implementations, and the ultimate
  74. // class that all external verifiers will eventually be transformed into.
  75. // To implement a custom verifier, do not extend this class; instead,
  76. // implement a subclass of ExternalCertificateVerifier. Note that custom
  77. // verifier implementations can compose their functionality with existing
  78. // implementations of this interface, such as HostnameVerifier, by delegating
  79. // to an instance of that class.
  80. class CertificateVerifier {
  81. public:
  82. explicit CertificateVerifier(grpc_tls_certificate_verifier* v);
  83. ~CertificateVerifier();
  84. // Verifies a connection request, based on the logic specified in an internal
  85. // verifier. The check on each internal verifier could be either synchronous
  86. // or asynchronous, and we will need to use return value to know.
  87. //
  88. // request: the verification information associated with this request
  89. // callback: This will only take effect if the verifier is asynchronous.
  90. // The function that gRPC will invoke when the verifier has already
  91. // completed its asynchronous check. Callers can use this function
  92. // to perform any additional checks. The input parameter of the
  93. // std::function indicates the status of the verifier check.
  94. // sync_status: This will only be useful if the verifier is synchronous.
  95. // The status of the verifier as it has already done it's
  96. // synchronous check.
  97. // return: return true if executed synchronously, otherwise return false
  98. bool Verify(TlsCustomVerificationCheckRequest* request,
  99. std::function<void(grpc::Status)> callback,
  100. grpc::Status* sync_status);
  101. // Cancels a verification request previously started via Verify().
  102. // Used when the connection attempt times out or is cancelled while an async
  103. // verification request is pending.
  104. //
  105. // request: the verification information associated with this request
  106. void Cancel(TlsCustomVerificationCheckRequest* request);
  107. // Gets the core verifier used internally.
  108. grpc_tls_certificate_verifier* c_verifier() { return verifier_; }
  109. private:
  110. static void AsyncCheckDone(
  111. grpc_tls_custom_verification_check_request* request, void* callback_arg,
  112. grpc_status_code status, const char* error_details);
  113. grpc_tls_certificate_verifier* verifier_ = nullptr;
  114. grpc::internal::Mutex mu_;
  115. std::map<grpc_tls_custom_verification_check_request*,
  116. std::function<void(grpc::Status)>>
  117. request_map_ Y_ABSL_GUARDED_BY(mu_);
  118. };
  119. // The base class of all external, user-specified verifiers. Users should
  120. // inherit this class to implement a custom verifier.
  121. // Note that while implementing the custom verifier that extends this class, it
  122. // is possible to compose an existing ExternalCertificateVerifier or
  123. // CertificateVerifier, inside the Verify() and Cancel() function of the new
  124. // custom verifier.
  125. class ExternalCertificateVerifier {
  126. public:
  127. // A factory method for creating a |CertificateVerifier| from this class. All
  128. // the user-implemented verifiers should use this function to be converted to
  129. // verifiers compatible with |TlsCredentialsOptions|.
  130. // The resulting CertificateVerifier takes ownership of the newly instantiated
  131. // Subclass.
  132. template <typename Subclass, typename... Args>
  133. static std::shared_ptr<CertificateVerifier> Create(Args&&... args) {
  134. auto* external_verifier = new Subclass(std::forward<Args>(args)...);
  135. return std::make_shared<CertificateVerifier>(
  136. grpc_tls_certificate_verifier_external_create(
  137. external_verifier->base_));
  138. }
  139. // The verification logic that will be performed after the TLS handshake
  140. // completes. Implementers can choose to do their checks synchronously or
  141. // asynchronously.
  142. //
  143. // request: the verification information associated with this request
  144. // callback: This should only be used if your check is done asynchronously.
  145. // When the asynchronous work is done, invoke this callback function
  146. // with the proper status, indicating the success or the failure of
  147. // the check. The implementer MUST NOT invoke this |callback| in the
  148. // same thread before Verify() returns, otherwise it can lead to
  149. // deadlocks.
  150. // sync_status: This should only be used if your check is done synchronously.
  151. // Modifies this value to indicate the success or the failure of
  152. // the check.
  153. // return: return true if your check is done synchronously, otherwise return
  154. // false
  155. virtual bool Verify(TlsCustomVerificationCheckRequest* request,
  156. std::function<void(grpc::Status)> callback,
  157. grpc::Status* sync_status) = 0;
  158. // Cancels a verification request previously started via Verify().
  159. // Used when the connection attempt times out or is cancelled while an async
  160. // verification request is pending. The implementation should abort whatever
  161. // async operation it is waiting for and quickly invoke the callback that was
  162. // passed to Verify() with a status indicating the cancellation.
  163. //
  164. // request: the verification information associated with this request
  165. virtual void Cancel(TlsCustomVerificationCheckRequest* request) = 0;
  166. protected:
  167. ExternalCertificateVerifier();
  168. virtual ~ExternalCertificateVerifier();
  169. private:
  170. struct AsyncRequestState {
  171. AsyncRequestState(grpc_tls_on_custom_verification_check_done_cb cb,
  172. void* arg,
  173. grpc_tls_custom_verification_check_request* request)
  174. : callback(cb), callback_arg(arg), cpp_request(request) {}
  175. grpc_tls_on_custom_verification_check_done_cb callback;
  176. void* callback_arg;
  177. TlsCustomVerificationCheckRequest cpp_request;
  178. };
  179. static int VerifyInCoreExternalVerifier(
  180. void* user_data, grpc_tls_custom_verification_check_request* request,
  181. grpc_tls_on_custom_verification_check_done_cb callback,
  182. void* callback_arg, grpc_status_code* sync_status,
  183. char** sync_error_details);
  184. static void CancelInCoreExternalVerifier(
  185. void* user_data, grpc_tls_custom_verification_check_request* request);
  186. static void DestructInCoreExternalVerifier(void* user_data);
  187. // TODO(yihuazhang): after the insecure build is removed, make this an object
  188. // member instead of a pointer.
  189. grpc_tls_certificate_verifier_external* base_ = nullptr;
  190. grpc::internal::Mutex mu_;
  191. std::map<grpc_tls_custom_verification_check_request*, AsyncRequestState>
  192. request_map_ Y_ABSL_GUARDED_BY(mu_);
  193. };
  194. // A CertificateVerifier that doesn't perform any additional checks other than
  195. // certificate verification, if specified.
  196. // Note: using this solely without any other authentication mechanisms on the
  197. // peer identity will leave your applications to the MITM(Man-In-The-Middle)
  198. // attacks. Users should avoid doing so in production environments.
  199. class NoOpCertificateVerifier : public CertificateVerifier {
  200. public:
  201. NoOpCertificateVerifier();
  202. };
  203. // A CertificateVerifier that will perform hostname verification, to see if the
  204. // target name set from the client side matches the identity information
  205. // specified on the server's certificate.
  206. class HostNameCertificateVerifier : public CertificateVerifier {
  207. public:
  208. HostNameCertificateVerifier();
  209. };
  210. } // namespace experimental
  211. } // namespace grpc
  212. #endif // GRPCPP_SECURITY_TLS_CERTIFICATE_VERIFIER_H