blob: 7a6e099d22733e2199620ef935e656720684e21e [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
2 * Copyright 2004 The WebRTC Project Authors. All rights reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_OPENSSLSTREAMADAPTER_H_
12#define RTC_BASE_OPENSSLSTREAMADAPTER_H_
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000013
Benjamin Wright19aab2e2018-04-05 15:39:06 -070014#include <openssl/ossl_typ.h>
15
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <string>
17#include <memory>
18#include <vector>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/buffer.h"
21#include "rtc_base/opensslidentity.h"
22#include "rtc_base/sslstreamadapter.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000023
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024namespace rtc {
25
26// This class was written with OpenSSLAdapter (a socket adapter) as a
27// starting point. It has similar structure and functionality, but uses a
28// "peer-to-peer" mode, verifying the peer's certificate using a digest
29// sent over a secure signaling channel.
30//
31// Static methods to initialize and deinit the SSL library are in
32// OpenSSLAdapter. These should probably be moved out to a neutral class.
33//
34// In a few cases I have factored out some OpenSSLAdapter code into static
35// methods so it can be reused from this class. Eventually that code should
36// probably be moved to a common support class. Unfortunately there remain a
37// few duplicated sections of code. I have not done more restructuring because
38// I did not want to affect existing code that uses OpenSSLAdapter.
39//
40// This class does not support the SSL connection restart feature present in
41// OpenSSLAdapter. I am not entirely sure how the feature is useful and I am
42// not convinced that it works properly.
43//
44// This implementation is careful to disallow data exchange after an SSL error,
45// and it has an explicit SSL_CLOSED state. It should not be possible to send
46// any data in clear after one of the StartSSL methods has been called.
47
48// Look in sslstreamadapter.h for documentation of the methods.
49
50class OpenSSLIdentity;
51
52///////////////////////////////////////////////////////////////////////////////
53
54class OpenSSLStreamAdapter : public SSLStreamAdapter {
55 public:
56 explicit OpenSSLStreamAdapter(StreamInterface* stream);
57 ~OpenSSLStreamAdapter() override;
58
59 void SetIdentity(SSLIdentity* identity) override;
60
61 // Default argument is for compatibility
62 void SetServerRole(SSLRole role = SSL_SERVER) override;
63 bool SetPeerCertificateDigest(
64 const std::string& digest_alg,
65 const unsigned char* digest_val,
66 size_t digest_len,
67 SSLPeerCertificateDigestError* error = nullptr) override;
68
Jian Cui0a8798b2017-11-16 16:58:02 -080069 std::unique_ptr<SSLCertChain> GetPeerSSLCertChain() const override;
70
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020071 // Goes from state SSL_NONE to either SSL_CONNECTING or SSL_WAIT, depending
72 // on whether the underlying stream is already open or not.
73 int StartSSL() override;
74 void SetMode(SSLMode mode) override;
75 void SetMaxProtocolVersion(SSLProtocolVersion version) override;
76 void SetInitialRetransmissionTimeout(int timeout_ms) override;
77
78 StreamResult Read(void* data,
79 size_t data_len,
80 size_t* read,
81 int* error) override;
82 StreamResult Write(const void* data,
83 size_t data_len,
84 size_t* written,
85 int* error) override;
86 void Close() override;
87 StreamState GetState() const override;
88
89 // TODO(guoweis): Move this away from a static class method.
90 static std::string SslCipherSuiteToName(int crypto_suite);
91
92 bool GetSslCipherSuite(int* cipher) override;
93
94 int GetSslVersion() const override;
95
96 // Key Extractor interface
97 bool ExportKeyingMaterial(const std::string& label,
98 const uint8_t* context,
99 size_t context_len,
100 bool use_context,
101 uint8_t* result,
102 size_t result_len) override;
103
104 // DTLS-SRTP interface
105 bool SetDtlsSrtpCryptoSuites(const std::vector<int>& crypto_suites) override;
106 bool GetDtlsSrtpCryptoSuite(int* crypto_suite) override;
107
108 bool IsTlsConnected() override;
109
110 // Capabilities interfaces.
111 static bool IsBoringSsl();
112
113 static bool IsAcceptableCipher(int cipher, KeyType key_type);
114 static bool IsAcceptableCipher(const std::string& cipher, KeyType key_type);
115
116 // Use our timeutils.h source of timing in BoringSSL, allowing us to test
117 // using a fake clock.
118 static void enable_time_callback_for_testing();
119
120 protected:
121 void OnEvent(StreamInterface* stream, int events, int err) override;
122
123 private:
124 enum SSLState {
125 // Before calling one of the StartSSL methods, data flows
126 // in clear text.
127 SSL_NONE,
128 SSL_WAIT, // waiting for the stream to open to start SSL negotiation
129 SSL_CONNECTING, // SSL negotiation in progress
130 SSL_CONNECTED, // SSL stream successfully established
131 SSL_ERROR, // some SSL error occurred, stream is closed
132 SSL_CLOSED // Clean close
133 };
134
135 enum { MSG_TIMEOUT = MSG_MAX+1};
136
137 // The following three methods return 0 on success and a negative
138 // error code on failure. The error code may be from OpenSSL or -1
139 // on some other error cases, so it can't really be interpreted
140 // unfortunately.
141
142 // Prepare SSL library, state is SSL_CONNECTING.
143 int BeginSSL();
144 // Perform SSL negotiation steps.
145 int ContinueSSL();
146
147 // Error handler helper. signal is given as true for errors in
148 // asynchronous contexts (when an error method was not returned
149 // through some other method), and in that case an SE_CLOSE event is
150 // raised on the stream with the specified error.
151 // A 0 error means a graceful close, otherwise there is not really enough
152 // context to interpret the error code.
153 // |alert| indicates an alert description (one of the SSL_AD constants) to
154 // send to the remote endpoint when closing the association. If 0, a normal
155 // shutdown will be performed.
156 void Error(const char* context, int err, uint8_t alert, bool signal);
157 void Cleanup(uint8_t alert);
158
159 // Override MessageHandler
160 void OnMessage(Message* msg) override;
161
162 // Flush the input buffers by reading left bytes (for DTLS)
163 void FlushInput(unsigned int left);
164
165 // SSL library configuration
166 SSL_CTX* SetupSSLContext();
167 // Verify the peer certificate matches the signaled digest.
168 bool VerifyPeerCertificate();
David Benjamindc246562017-09-29 12:14:08 -0400169 // SSL certificate verification callback. See
170 // SSL_CTX_set_cert_verify_callback.
171 static int SSLVerifyCallback(X509_STORE_CTX* store, void* arg);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200172
173 bool waiting_to_verify_peer_certificate() const {
174 return client_auth_enabled() && !peer_certificate_verified_;
175 }
176
177 bool has_peer_certificate_digest() const {
178 return !peer_certificate_digest_algorithm_.empty() &&
179 !peer_certificate_digest_value_.empty();
180 }
181
182 SSLState state_;
183 SSLRole role_;
184 int ssl_error_code_; // valid when state_ == SSL_ERROR or SSL_CLOSED
185 // Whether the SSL negotiation is blocked on needing to read or
186 // write to the wrapped stream.
187 bool ssl_read_needs_write_;
188 bool ssl_write_needs_read_;
189
190 SSL* ssl_;
191 SSL_CTX* ssl_ctx_;
192
193 // Our key and certificate.
194 std::unique_ptr<OpenSSLIdentity> identity_;
Taylor Brandstetterc3928662018-02-23 13:04:51 -0800195 // The certificate chain that the peer presented. Initially null, until the
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200196 // connection is established.
Jian Cui0a8798b2017-11-16 16:58:02 -0800197 std::unique_ptr<SSLCertChain> peer_cert_chain_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198 bool peer_certificate_verified_ = false;
199 // The digest of the certificate that the peer must present.
200 Buffer peer_certificate_digest_value_;
201 std::string peer_certificate_digest_algorithm_;
202
203 // The DtlsSrtp ciphers
204 std::string srtp_ciphers_;
205
206 // Do DTLS or not
207 SSLMode ssl_mode_;
208
209 // Max. allowed protocol version
210 SSLProtocolVersion ssl_max_version_;
211
212 // A 50-ms initial timeout ensures rapid setup on fast connections, but may
213 // be too aggressive for low bandwidth links.
214 int dtls_handshake_timeout_ms_ = 50;
215};
216
217/////////////////////////////////////////////////////////////////////////////
218
219} // namespace rtc
220
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200221#endif // RTC_BASE_OPENSSLSTREAMADAPTER_H_