1 //
2 //
3 // Copyright 2018 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 
19 #ifndef GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_TLS_TLS_SECURITY_CONNECTOR_H
20 #define GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_TLS_TLS_SECURITY_CONNECTOR_H
21 
22 #include <grpc/support/port_platform.h>
23 
24 #include <map>
25 #include <string>
26 
27 #include "absl/base/thread_annotations.h"
28 #include "absl/status/status.h"
29 #include "absl/strings/string_view.h"
30 #include "absl/types/optional.h"
31 
32 #include <grpc/grpc.h>
33 #include <grpc/grpc_security.h>
34 
35 #include "src/core/lib/channel/channel_args.h"
36 #include "src/core/lib/gprpp/ref_counted_ptr.h"
37 #include "src/core/lib/gprpp/sync.h"
38 #include "src/core/lib/iomgr/closure.h"
39 #include "src/core/lib/iomgr/endpoint.h"
40 #include "src/core/lib/iomgr/error.h"
41 #include "src/core/lib/iomgr/iomgr_fwd.h"
42 #include "src/core/lib/promise/arena_promise.h"
43 #include "src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.h"
44 #include "src/core/lib/security/security_connector/security_connector.h"
45 #include "src/core/lib/security/security_connector/ssl_utils.h"
46 #include "src/core/lib/transport/handshaker.h"
47 #include "src/core/tsi/ssl/key_logging/ssl_key_logging.h"
48 #include "src/core/tsi/ssl_transport_security.h"
49 #include "src/core/tsi/transport_security_interface.h"
50 
51 using TlsSessionKeyLogger = tsi::TlsSessionKeyLoggerCache::TlsSessionKeyLogger;
52 
53 namespace grpc_core {
54 
55 // Channel security connector using TLS as transport security protocol.
56 class TlsChannelSecurityConnector final
57     : public grpc_channel_security_connector {
58  public:
59   // static factory method to create a TLS channel security connector.
60   static RefCountedPtr<grpc_channel_security_connector>
61   CreateTlsChannelSecurityConnector(
62       RefCountedPtr<grpc_channel_credentials> channel_creds,
63       RefCountedPtr<grpc_tls_credentials_options> options,
64       RefCountedPtr<grpc_call_credentials> request_metadata_creds,
65       const char* target_name, const char* overridden_target_name,
66       tsi_ssl_session_cache* ssl_session_cache);
67 
68   TlsChannelSecurityConnector(
69       RefCountedPtr<grpc_channel_credentials> channel_creds,
70       RefCountedPtr<grpc_tls_credentials_options> options,
71       RefCountedPtr<grpc_call_credentials> request_metadata_creds,
72       const char* target_name, const char* overridden_target_name,
73       tsi_ssl_session_cache* ssl_session_cache);
74 
75   ~TlsChannelSecurityConnector() override;
76 
77   void add_handshakers(const ChannelArgs& args,
78                        grpc_pollset_set* interested_parties,
79                        HandshakeManager* handshake_mgr) override;
80 
81   void check_peer(tsi_peer peer, grpc_endpoint* ep, const ChannelArgs& /*args*/,
82                   RefCountedPtr<grpc_auth_context>* auth_context,
83                   grpc_closure* on_peer_checked) override;
84 
85   void cancel_check_peer(grpc_closure* on_peer_checked,
86                          grpc_error_handle error) override;
87 
88   int cmp(const grpc_security_connector* other_sc) const override;
89 
90   ArenaPromise<absl::Status> CheckCallHost(
91       absl::string_view host, grpc_auth_context* auth_context) override;
92 
ClientHandshakerFactoryForTesting()93   tsi_ssl_client_handshaker_factory* ClientHandshakerFactoryForTesting() {
94     MutexLock lock(&mu_);
95     return client_handshaker_factory_;
96   };
97 
RootCertsForTesting()98   absl::optional<absl::string_view> RootCertsForTesting() {
99     MutexLock lock(&mu_);
100     return pem_root_certs_;
101   }
102 
KeyCertPairListForTesting()103   absl::optional<PemKeyCertPairList> KeyCertPairListForTesting() {
104     MutexLock lock(&mu_);
105     return pem_key_cert_pair_list_;
106   }
107 
108  private:
109   // A watcher that watches certificate updates from
110   // grpc_tls_certificate_distributor. It will never outlive
111   // |security_connector_|.
112   class TlsChannelCertificateWatcher : public grpc_tls_certificate_distributor::
113                                            TlsCertificatesWatcherInterface {
114    public:
TlsChannelCertificateWatcher(TlsChannelSecurityConnector * security_connector)115     explicit TlsChannelCertificateWatcher(
116         TlsChannelSecurityConnector* security_connector)
117         : security_connector_(security_connector) {}
118     void OnCertificatesChanged(
119         absl::optional<absl::string_view> root_certs,
120         absl::optional<PemKeyCertPairList> key_cert_pairs) override;
121     void OnError(grpc_error_handle root_cert_error,
122                  grpc_error_handle identity_cert_error) override;
123 
124    private:
125     TlsChannelSecurityConnector* security_connector_ = nullptr;
126   };
127 
128   // Use "new" to create a new instance, and no need to delete it later, since
129   // it will be self-destroyed in |OnVerifyDone|.
130   class ChannelPendingVerifierRequest {
131    public:
132     ChannelPendingVerifierRequest(
133         RefCountedPtr<TlsChannelSecurityConnector> security_connector,
134         grpc_closure* on_peer_checked, tsi_peer peer, const char* target_name);
135 
136     ~ChannelPendingVerifierRequest();
137 
138     void Start();
139 
request()140     grpc_tls_custom_verification_check_request* request() { return &request_; }
141 
142    private:
143     void OnVerifyDone(bool run_callback_inline, absl::Status status);
144     // The request will keep a reference of the security connector to make sure
145     // it won't be destroyed while the request is still ongoing.
146     RefCountedPtr<TlsChannelSecurityConnector> security_connector_;
147     grpc_tls_custom_verification_check_request request_;
148     grpc_closure* on_peer_checked_;
149   };
150 
151   // Updates |client_handshaker_factory_| when the certificates that
152   // |certificate_watcher_| is watching get updated.
153   grpc_security_status UpdateHandshakerFactoryLocked()
154       ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
155 
156   Mutex mu_;
157   // We need a separate mutex for |pending_verifier_requests_|, otherwise there
158   // would be deadlock errors.
159   Mutex verifier_request_map_mu_;
160   RefCountedPtr<grpc_tls_credentials_options> options_;
161   grpc_tls_certificate_distributor::TlsCertificatesWatcherInterface*
162       certificate_watcher_ = nullptr;
163   std::string target_name_;
164   std::string overridden_target_name_;
165   tsi_ssl_client_handshaker_factory* client_handshaker_factory_
166       ABSL_GUARDED_BY(mu_) = nullptr;
167   tsi_ssl_session_cache* ssl_session_cache_ ABSL_GUARDED_BY(mu_) = nullptr;
168   RefCountedPtr<TlsSessionKeyLogger> tls_session_key_logger_;
169   absl::optional<absl::string_view> pem_root_certs_ ABSL_GUARDED_BY(mu_);
170   absl::optional<PemKeyCertPairList> pem_key_cert_pair_list_
171       ABSL_GUARDED_BY(mu_);
172   std::map<grpc_closure* /*on_peer_checked*/, ChannelPendingVerifierRequest*>
173       pending_verifier_requests_ ABSL_GUARDED_BY(verifier_request_map_mu_);
174 };
175 
176 // Server security connector using TLS as transport security protocol.
177 class TlsServerSecurityConnector final : public grpc_server_security_connector {
178  public:
179   // static factory method to create a TLS server security connector.
180   static RefCountedPtr<grpc_server_security_connector>
181   CreateTlsServerSecurityConnector(
182       RefCountedPtr<grpc_server_credentials> server_creds,
183       RefCountedPtr<grpc_tls_credentials_options> options);
184 
185   TlsServerSecurityConnector(
186       RefCountedPtr<grpc_server_credentials> server_creds,
187       RefCountedPtr<grpc_tls_credentials_options> options);
188   ~TlsServerSecurityConnector() override;
189 
190   void add_handshakers(const ChannelArgs& args,
191                        grpc_pollset_set* interested_parties,
192                        HandshakeManager* handshake_mgr) override;
193 
194   void check_peer(tsi_peer peer, grpc_endpoint* ep, const ChannelArgs& /*args*/,
195                   RefCountedPtr<grpc_auth_context>* auth_context,
196                   grpc_closure* on_peer_checked) override;
197 
198   void cancel_check_peer(grpc_closure* /*on_peer_checked*/,
199                          grpc_error_handle error) override;
200 
201   int cmp(const grpc_security_connector* other) const override;
202 
ServerHandshakerFactoryForTesting()203   tsi_ssl_server_handshaker_factory* ServerHandshakerFactoryForTesting() {
204     MutexLock lock(&mu_);
205     return server_handshaker_factory_;
206   };
207 
RootCertsForTesting()208   const absl::optional<absl::string_view>& RootCertsForTesting() {
209     MutexLock lock(&mu_);
210     return pem_root_certs_;
211   }
212 
KeyCertPairListForTesting()213   const absl::optional<PemKeyCertPairList>& KeyCertPairListForTesting() {
214     MutexLock lock(&mu_);
215     return pem_key_cert_pair_list_;
216   }
217 
218  private:
219   // A watcher that watches certificate updates from
220   // grpc_tls_certificate_distributor. It will never outlive
221   // |security_connector_|.
222   class TlsServerCertificateWatcher : public grpc_tls_certificate_distributor::
223                                           TlsCertificatesWatcherInterface {
224    public:
TlsServerCertificateWatcher(TlsServerSecurityConnector * security_connector)225     explicit TlsServerCertificateWatcher(
226         TlsServerSecurityConnector* security_connector)
227         : security_connector_(security_connector) {}
228     void OnCertificatesChanged(
229         absl::optional<absl::string_view> root_certs,
230         absl::optional<PemKeyCertPairList> key_cert_pairs) override;
231 
232     void OnError(grpc_error_handle root_cert_error,
233                  grpc_error_handle identity_cert_error) override;
234 
235    private:
236     TlsServerSecurityConnector* security_connector_ = nullptr;
237   };
238 
239   // Use "new" to create a new instance, and no need to delete it later, since
240   // it will be self-destroyed in |OnVerifyDone|.
241   class ServerPendingVerifierRequest {
242    public:
243     ServerPendingVerifierRequest(
244         RefCountedPtr<TlsServerSecurityConnector> security_connector,
245         grpc_closure* on_peer_checked, tsi_peer peer);
246 
247     ~ServerPendingVerifierRequest();
248 
249     void Start();
250 
request()251     grpc_tls_custom_verification_check_request* request() { return &request_; }
252 
253    private:
254     void OnVerifyDone(bool run_callback_inline, absl::Status status);
255     // The request will keep a reference of the security connector to make sure
256     // it won't be destroyed while the request is still ongoing.
257     RefCountedPtr<TlsServerSecurityConnector> security_connector_;
258     grpc_tls_custom_verification_check_request request_;
259     grpc_closure* on_peer_checked_;
260   };
261 
262   // Updates |server_handshaker_factory_| when the certificates that
263   // |certificate_watcher_| is watching get updated.
264   grpc_security_status UpdateHandshakerFactoryLocked()
265       ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_);
266 
267   Mutex mu_;
268   // We need a separate mutex for |pending_verifier_requests_|, otherwise there
269   // would be deadlock errors.
270   Mutex verifier_request_map_mu_;
271   RefCountedPtr<grpc_tls_credentials_options> options_;
272   grpc_tls_certificate_distributor::TlsCertificatesWatcherInterface*
273       certificate_watcher_ = nullptr;
274   tsi_ssl_server_handshaker_factory* server_handshaker_factory_
275       ABSL_GUARDED_BY(mu_) = nullptr;
276   absl::optional<absl::string_view> pem_root_certs_ ABSL_GUARDED_BY(mu_);
277   absl::optional<PemKeyCertPairList> pem_key_cert_pair_list_
278       ABSL_GUARDED_BY(mu_);
279   RefCountedPtr<TlsSessionKeyLogger> tls_session_key_logger_;
280   std::map<grpc_closure* /*on_peer_checked*/, ServerPendingVerifierRequest*>
281       pending_verifier_requests_ ABSL_GUARDED_BY(verifier_request_map_mu_);
282 };
283 
284 }  // namespace grpc_core
285 
286 #endif  // GRPC_SRC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_TLS_TLS_SECURITY_CONNECTOR_H
287