1 // Copyright 2021 gRPC authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef GRPC_SRC_CORE_TSI_SSL_KEY_LOGGING_SSL_KEY_LOGGING_H 16 #define GRPC_SRC_CORE_TSI_SSL_KEY_LOGGING_SSL_KEY_LOGGING_H 17 18 #include <grpc/grpc_security.h> 19 #include <grpc/slice.h> 20 #include <grpc/support/port_platform.h> 21 #include <grpc/support/sync.h> 22 #include <openssl/ssl.h> 23 24 #include <iostream> 25 #include <map> 26 27 #include "absl/base/thread_annotations.h" 28 #include "src/core/util/memory.h" 29 #include "src/core/util/ref_counted.h" 30 #include "src/core/util/sync.h" 31 32 namespace tsi { 33 34 class TlsSessionKeyLoggerCache 35 : public grpc_core::RefCounted<TlsSessionKeyLoggerCache> { 36 public: 37 TlsSessionKeyLoggerCache(); 38 ~TlsSessionKeyLoggerCache() override; 39 40 // A helper class which facilitates appending Tls session keys into a file. 41 // The instance is bound to a file meaning only one instance of this object 42 // can ever exist for a given file path. 43 class TlsSessionKeyLogger 44 : public grpc_core::RefCounted<TlsSessionKeyLogger> { 45 public: 46 // Instantiates a TlsSessionKeyLogger instance bound to a specific path. 47 TlsSessionKeyLogger( 48 std::string tls_session_key_log_file_path, 49 grpc_core::RefCountedPtr<TlsSessionKeyLoggerCache> cache); 50 ~TlsSessionKeyLogger() override; 51 52 // Not copyable nor assignable. 53 TlsSessionKeyLogger(const TlsSessionKeyLogger&) = delete; 54 TlsSessionKeyLogger& operator=(const TlsSessionKeyLogger&) = delete; 55 // Writes session keys into the file in the NSS key logging format. 56 // This is called upon completion of a handshake. The associated ssl_context 57 // is also provided here to support future extensions such as logging 58 // keys only when connections are made by certain IPs etc. 59 void LogSessionKeys(SSL_CTX* ssl_context, 60 const std::string& session_keys_info); 61 62 private: 63 grpc_core::Mutex lock_; // protects appends to file 64 FILE* fd_ ABSL_GUARDED_BY(lock_); 65 std::string tls_session_key_log_file_path_; 66 grpc_core::RefCountedPtr<TlsSessionKeyLoggerCache> cache_; 67 }; 68 // Creates and returns a TlsSessionKeyLogger instance. 69 static grpc_core::RefCountedPtr<TlsSessionKeyLogger> Get( 70 std::string tls_session_key_log_file_path); 71 72 private: 73 std::map<std::string, TlsSessionKeyLogger*> tls_session_key_logger_map_; 74 }; 75 76 } // namespace tsi 77 78 #endif // GRPC_SRC_CORE_TSI_SSL_KEY_LOGGING_SSL_KEY_LOGGING_H 79