3 * Copyright 2018 gRPC authors.
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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <grpc/support/port_platform.h>
21 #include "src/core/tsi/ssl/session_cache/ssl_session.h"
23 #include <grpc/support/log.h>
25 #ifndef OPENSSL_IS_BORINGSSL
27 // OpenSSL invalidates SSL_SESSION on SSL destruction making it pointless
28 // to cache sessions. The workaround is to serialize (relatively expensive)
29 // session into binary blob and re-create it from blob on every handshake.
30 // Note that it's safe to keep serialized session outside of SSL lifetime
31 // as openssl performs all necessary validation while attempting to use a
32 // session and creates a new one if something is wrong (e.g. server changed
33 // set of allowed codecs).
38 class OpenSslCachedSession : public SslCachedSession {
40 OpenSslCachedSession(SslSessionPtr session) {
41 int size = i2d_SSL_SESSION(session.get(), nullptr);
43 grpc_slice slice = grpc_slice_malloc(size_t(size));
44 unsigned char* start = GRPC_SLICE_START_PTR(slice);
45 int second_size = i2d_SSL_SESSION(session.get(), &start);
46 GPR_ASSERT(size == second_size);
47 serialized_session_ = slice;
50 virtual ~OpenSslCachedSession() { grpc_slice_unref(serialized_session_); }
52 SslSessionPtr CopySession() const override {
53 const unsigned char* data = GRPC_SLICE_START_PTR(serialized_session_);
54 size_t length = GRPC_SLICE_LENGTH(serialized_session_);
55 SSL_SESSION* session = d2i_SSL_SESSION(nullptr, &data, length);
56 if (session == nullptr) {
57 return SslSessionPtr();
59 return SslSessionPtr(session);
63 grpc_slice serialized_session_;
68 grpc_core::UniquePtr<SslCachedSession> SslCachedSession::Create(
69 SslSessionPtr session) {
70 return grpc_core::UniquePtr<SslCachedSession>(
71 grpc_core::New<OpenSslCachedSession>(std::move(session)));
76 #endif /* OPENSSL_IS_BORINGSSL */