1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "remoting/protocol/ssl_hmac_channel_authenticator.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback_helpers.h"
10 #include "base/logging.h"
11 #include "crypto/secure_util.h"
12 #include "net/base/host_port_pair.h"
13 #include "net/base/io_buffer.h"
14 #include "net/base/net_errors.h"
15 #include "net/cert/cert_status_flags.h"
16 #include "net/cert/cert_verifier.h"
17 #include "net/cert/x509_certificate.h"
18 #include "net/http/transport_security_state.h"
19 #include "net/socket/client_socket_factory.h"
20 #include "net/socket/client_socket_handle.h"
21 #include "net/socket/ssl_client_socket.h"
22 #include "net/socket/ssl_client_socket_openssl.h"
23 #include "net/socket/ssl_server_socket.h"
24 #include "net/ssl/ssl_config_service.h"
25 #include "remoting/base/rsa_key_pair.h"
26 #include "remoting/protocol/auth_util.h"
33 // A CertVerifier which rejects every certificate.
34 class FailingCertVerifier
: public net::CertVerifier
{
36 FailingCertVerifier() {}
37 ~FailingCertVerifier() override
{}
39 int Verify(net::X509Certificate
* cert
,
40 const std::string
& hostname
,
41 const std::string
& ocsp_response
,
44 net::CertVerifyResult
* verify_result
,
45 const net::CompletionCallback
& callback
,
46 scoped_ptr
<Request
>* out_req
,
47 const net::BoundNetLog
& net_log
) override
{
48 verify_result
->verified_cert
= cert
;
49 verify_result
->cert_status
= net::CERT_STATUS_INVALID
;
50 return net::ERR_CERT_INVALID
;
57 scoped_ptr
<SslHmacChannelAuthenticator
>
58 SslHmacChannelAuthenticator::CreateForClient(
59 const std::string
& remote_cert
,
60 const std::string
& auth_key
) {
61 scoped_ptr
<SslHmacChannelAuthenticator
> result(
62 new SslHmacChannelAuthenticator(auth_key
));
63 result
->remote_cert_
= remote_cert
;
67 scoped_ptr
<SslHmacChannelAuthenticator
>
68 SslHmacChannelAuthenticator::CreateForHost(
69 const std::string
& local_cert
,
70 scoped_refptr
<RsaKeyPair
> key_pair
,
71 const std::string
& auth_key
) {
72 scoped_ptr
<SslHmacChannelAuthenticator
> result(
73 new SslHmacChannelAuthenticator(auth_key
));
74 result
->local_cert_
= local_cert
;
75 result
->local_key_pair_
= key_pair
;
79 SslHmacChannelAuthenticator::SslHmacChannelAuthenticator(
80 const std::string
& auth_key
)
81 : auth_key_(auth_key
) {
84 SslHmacChannelAuthenticator::~SslHmacChannelAuthenticator() {
87 void SslHmacChannelAuthenticator::SecureAndAuthenticate(
88 scoped_ptr
<net::StreamSocket
> socket
, const DoneCallback
& done_callback
) {
89 DCHECK(CalledOnValidThread());
90 DCHECK(socket
->IsConnected());
92 done_callback_
= done_callback
;
95 if (is_ssl_server()) {
97 // Client plugin doesn't use server SSL sockets, and so SSLServerSocket
98 // implementation is not compiled for NaCl as part of net_nacl.
100 result
= net::ERR_FAILED
;
102 scoped_refptr
<net::X509Certificate
> cert
=
103 net::X509Certificate::CreateFromBytes(
104 local_cert_
.data(), local_cert_
.length());
106 LOG(ERROR
) << "Failed to parse X509Certificate";
107 NotifyError(net::ERR_FAILED
);
111 net::SSLConfig ssl_config
;
112 ssl_config
.require_ecdhe
= true;
114 scoped_ptr
<net::SSLServerSocket
> server_socket
=
115 net::CreateSSLServerSocket(socket
.Pass(),
117 local_key_pair_
->private_key(),
119 net::SSLServerSocket
* raw_server_socket
= server_socket
.get();
120 socket_
= server_socket
.Pass();
121 result
= raw_server_socket
->Handshake(
122 base::Bind(&SslHmacChannelAuthenticator::OnConnected
,
123 base::Unretained(this)));
126 transport_security_state_
.reset(new net::TransportSecurityState
);
127 cert_verifier_
.reset(new FailingCertVerifier
);
129 net::SSLConfig::CertAndStatus cert_and_status
;
130 cert_and_status
.cert_status
= net::CERT_STATUS_AUTHORITY_INVALID
;
131 cert_and_status
.der_cert
= remote_cert_
;
133 net::SSLConfig ssl_config
;
134 // Certificate verification and revocation checking are not needed
135 // because we use self-signed certs. Disable it so that the SSL
136 // layer doesn't try to initialize OCSP (OCSP works only on the IO
138 ssl_config
.cert_io_enabled
= false;
139 ssl_config
.rev_checking_enabled
= false;
140 ssl_config
.allowed_bad_certs
.push_back(cert_and_status
);
142 net::HostPortPair
host_and_port(kSslFakeHostName
, 0);
143 net::SSLClientSocketContext context
;
144 context
.transport_security_state
= transport_security_state_
.get();
145 context
.cert_verifier
= cert_verifier_
.get();
146 scoped_ptr
<net::ClientSocketHandle
> socket_handle(
147 new net::ClientSocketHandle
);
148 socket_handle
->SetSocket(socket
.Pass());
151 // net_nacl doesn't include ClientSocketFactory.
152 socket_
.reset(new net::SSLClientSocketOpenSSL(
153 socket_handle
.Pass(), host_and_port
, ssl_config
, context
));
156 net::ClientSocketFactory::GetDefaultFactory()->CreateSSLClientSocket(
157 socket_handle
.Pass(), host_and_port
, ssl_config
, context
);
160 result
= socket_
->Connect(
161 base::Bind(&SslHmacChannelAuthenticator::OnConnected
,
162 base::Unretained(this)));
165 if (result
== net::ERR_IO_PENDING
)
171 bool SslHmacChannelAuthenticator::is_ssl_server() {
172 return local_key_pair_
.get() != nullptr;
175 void SslHmacChannelAuthenticator::OnConnected(int result
) {
176 if (result
!= net::OK
) {
177 LOG(WARNING
) << "Failed to establish SSL connection";
182 // Generate authentication digest to write to the socket.
183 std::string auth_bytes
= GetAuthBytes(
184 socket_
.get(), is_ssl_server() ?
185 kHostAuthSslExporterLabel
: kClientAuthSslExporterLabel
, auth_key_
);
186 if (auth_bytes
.empty()) {
187 NotifyError(net::ERR_FAILED
);
191 // Allocate a buffer to write the digest.
192 auth_write_buf_
= new net::DrainableIOBuffer(
193 new net::StringIOBuffer(auth_bytes
), auth_bytes
.size());
195 // Read an incoming token.
196 auth_read_buf_
= new net::GrowableIOBuffer();
197 auth_read_buf_
->SetCapacity(kAuthDigestLength
);
199 // If WriteAuthenticationBytes() results in |done_callback_| being
200 // called then we must not do anything else because this object may
201 // be destroyed at that point.
202 bool callback_called
= false;
203 WriteAuthenticationBytes(&callback_called
);
204 if (!callback_called
)
205 ReadAuthenticationBytes();
208 void SslHmacChannelAuthenticator::WriteAuthenticationBytes(
209 bool* callback_called
) {
211 int result
= socket_
->Write(
212 auth_write_buf_
.get(),
213 auth_write_buf_
->BytesRemaining(),
214 base::Bind(&SslHmacChannelAuthenticator::OnAuthBytesWritten
,
215 base::Unretained(this)));
216 if (result
== net::ERR_IO_PENDING
)
218 if (!HandleAuthBytesWritten(result
, callback_called
))
223 void SslHmacChannelAuthenticator::OnAuthBytesWritten(int result
) {
224 DCHECK(CalledOnValidThread());
226 if (HandleAuthBytesWritten(result
, nullptr))
227 WriteAuthenticationBytes(nullptr);
230 bool SslHmacChannelAuthenticator::HandleAuthBytesWritten(
231 int result
, bool* callback_called
) {
233 LOG(ERROR
) << "Error writing authentication: " << result
;
235 *callback_called
= false;
240 auth_write_buf_
->DidConsume(result
);
241 if (auth_write_buf_
->BytesRemaining() > 0)
244 auth_write_buf_
= nullptr;
245 CheckDone(callback_called
);
249 void SslHmacChannelAuthenticator::ReadAuthenticationBytes() {
252 socket_
->Read(auth_read_buf_
.get(),
253 auth_read_buf_
->RemainingCapacity(),
254 base::Bind(&SslHmacChannelAuthenticator::OnAuthBytesRead
,
255 base::Unretained(this)));
256 if (result
== net::ERR_IO_PENDING
)
258 if (!HandleAuthBytesRead(result
))
263 void SslHmacChannelAuthenticator::OnAuthBytesRead(int result
) {
264 DCHECK(CalledOnValidThread());
266 if (HandleAuthBytesRead(result
))
267 ReadAuthenticationBytes();
270 bool SslHmacChannelAuthenticator::HandleAuthBytesRead(int read_result
) {
271 if (read_result
<= 0) {
272 NotifyError(read_result
);
276 auth_read_buf_
->set_offset(auth_read_buf_
->offset() + read_result
);
277 if (auth_read_buf_
->RemainingCapacity() > 0)
280 if (!VerifyAuthBytes(std::string(
281 auth_read_buf_
->StartOfBuffer(),
282 auth_read_buf_
->StartOfBuffer() + kAuthDigestLength
))) {
283 LOG(WARNING
) << "Mismatched authentication";
284 NotifyError(net::ERR_FAILED
);
288 auth_read_buf_
= nullptr;
293 bool SslHmacChannelAuthenticator::VerifyAuthBytes(
294 const std::string
& received_auth_bytes
) {
295 DCHECK(received_auth_bytes
.length() == kAuthDigestLength
);
297 // Compute expected auth bytes.
298 std::string auth_bytes
= GetAuthBytes(
299 socket_
.get(), is_ssl_server() ?
300 kClientAuthSslExporterLabel
: kHostAuthSslExporterLabel
, auth_key_
);
301 if (auth_bytes
.empty())
304 return crypto::SecureMemEqual(received_auth_bytes
.data(),
305 &(auth_bytes
[0]), kAuthDigestLength
);
308 void SslHmacChannelAuthenticator::CheckDone(bool* callback_called
) {
309 if (auth_write_buf_
.get() == nullptr && auth_read_buf_
.get() == nullptr) {
310 DCHECK(socket_
.get() != nullptr);
312 *callback_called
= true;
314 base::ResetAndReturn(&done_callback_
).Run(net::OK
, socket_
.Pass());
318 void SslHmacChannelAuthenticator::NotifyError(int error
) {
319 base::ResetAndReturn(&done_callback_
).Run(error
, nullptr);
322 } // namespace protocol
323 } // namespace remoting