3 * Copyright 2004--2005, Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "talk/base/win32.h"
29 #define SECURITY_WIN32
36 #include "talk/base/common.h"
37 #include "talk/base/logging.h"
38 #include "talk/base/schanneladapter.h"
39 #include "talk/base/sec_buffer.h"
40 #include "talk/base/thread.h"
44 /////////////////////////////////////////////////////////////////////////////
46 /////////////////////////////////////////////////////////////////////////////
48 extern const ConstantLabel SECURITY_ERRORS[];
50 const ConstantLabel SCHANNEL_BUFFER_TYPES[] = {
51 KLABEL(SECBUFFER_EMPTY), // 0
52 KLABEL(SECBUFFER_DATA), // 1
53 KLABEL(SECBUFFER_TOKEN), // 2
54 KLABEL(SECBUFFER_PKG_PARAMS), // 3
55 KLABEL(SECBUFFER_MISSING), // 4
56 KLABEL(SECBUFFER_EXTRA), // 5
57 KLABEL(SECBUFFER_STREAM_TRAILER), // 6
58 KLABEL(SECBUFFER_STREAM_HEADER), // 7
59 KLABEL(SECBUFFER_MECHLIST), // 11
60 KLABEL(SECBUFFER_MECHLIST_SIGNATURE), // 12
61 KLABEL(SECBUFFER_TARGET), // 13
62 KLABEL(SECBUFFER_CHANNEL_BINDINGS), // 14
66 void DescribeBuffer(LoggingSeverity severity, const char* prefix,
67 const SecBuffer& sb) {
71 << ", " << FindLabel(sb.BufferType & ~SECBUFFER_ATTRMASK,
72 SCHANNEL_BUFFER_TYPES)
73 << ", " << sb.pvBuffer << ")";
76 void DescribeBuffers(LoggingSeverity severity, const char* prefix,
77 const SecBufferDesc* sbd) {
78 if (!LOG_CHECK_LEVEL_V(severity))
80 LOG_V(severity) << prefix << "(";
81 for (size_t i=0; i<sbd->cBuffers; ++i) {
82 DescribeBuffer(severity, " ", sbd->pBuffers[i]);
84 LOG_V(severity) << ")";
87 const ULONG SSL_FLAGS_DEFAULT = ISC_REQ_ALLOCATE_MEMORY
88 | ISC_REQ_CONFIDENTIALITY
89 | ISC_REQ_EXTENDED_ERROR
91 | ISC_REQ_REPLAY_DETECT
92 | ISC_REQ_SEQUENCE_DETECT
94 //| ISC_REQ_USE_SUPPLIED_CREDS;
96 typedef std::vector<char> SChannelBuffer;
98 struct SChannelAdapter::SSLImpl {
101 bool cred_init, ctx_init;
102 SChannelBuffer inbuf, outbuf, readable;
103 SecPkgContext_StreamSizes sizes;
105 SSLImpl() : cred_init(false), ctx_init(false) { }
108 SChannelAdapter::SChannelAdapter(AsyncSocket* socket)
109 : SSLAdapter(socket), state_(SSL_NONE),
110 restartable_(false), signal_close_(false), message_pending_(false),
114 SChannelAdapter::~SChannelAdapter() {
119 SChannelAdapter::StartSSL(const char* hostname, bool restartable) {
120 if (state_ != SSL_NONE)
121 return ERROR_ALREADY_INITIALIZED;
123 ssl_host_name_ = hostname;
124 restartable_ = restartable;
126 if (socket_->GetState() != Socket::CS_CONNECTED) {
131 state_ = SSL_CONNECTING;
132 if (int err = BeginSSL()) {
133 Error("BeginSSL", err, false);
141 SChannelAdapter::BeginSSL() {
142 LOG(LS_VERBOSE) << "BeginSSL: " << ssl_host_name_;
143 ASSERT(state_ == SSL_CONNECTING);
147 SCHANNEL_CRED sc_cred = { 0 };
148 sc_cred.dwVersion = SCHANNEL_CRED_VERSION;
149 //sc_cred.dwMinimumCipherStrength = 128; // Note: use system default
150 sc_cred.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_AUTO_CRED_VALIDATION;
152 ret = AcquireCredentialsHandle(NULL, UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL,
153 &sc_cred, NULL, NULL, &impl_->cred, NULL);
154 if (ret != SEC_E_OK) {
155 LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
156 << ErrorName(ret, SECURITY_ERRORS);
159 impl_->cred_init = true;
161 if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
162 SecPkgCred_CipherStrengths cipher_strengths = { 0 };
163 ret = QueryCredentialsAttributes(&impl_->cred,
164 SECPKG_ATTR_CIPHER_STRENGTHS,
166 if (SUCCEEDED(ret)) {
167 LOG(LS_VERBOSE) << "SChannel cipher strength: "
168 << cipher_strengths.dwMinimumCipherStrength << " - "
169 << cipher_strengths.dwMaximumCipherStrength;
172 SecPkgCred_SupportedAlgs supported_algs = { 0 };
173 ret = QueryCredentialsAttributes(&impl_->cred,
174 SECPKG_ATTR_SUPPORTED_ALGS,
176 if (SUCCEEDED(ret)) {
177 LOG(LS_VERBOSE) << "SChannel supported algorithms:";
178 for (DWORD i=0; i<supported_algs.cSupportedAlgs; ++i) {
179 ALG_ID alg_id = supported_algs.palgSupportedAlgs[i];
180 PCCRYPT_OID_INFO oinfo = CryptFindOIDInfo(CRYPT_OID_INFO_ALGID_KEY,
182 LPCWSTR alg_name = (NULL != oinfo) ? oinfo->pwszName : L"Unknown";
183 LOG(LS_VERBOSE) << " " << ToUtf8(alg_name) << " (" << alg_id << ")";
185 CSecBufferBase::FreeSSPI(supported_algs.palgSupportedAlgs);
189 ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
190 if (ignore_bad_cert())
191 flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
193 CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
194 ret = InitializeSecurityContextA(&impl_->cred, NULL,
195 const_cast<char*>(ssl_host_name_.c_str()),
196 flags, 0, 0, NULL, 0,
197 &impl_->ctx, sb_out.desc(),
200 impl_->ctx_init = true;
201 return ProcessContext(ret, NULL, sb_out.desc());
205 SChannelAdapter::ContinueSSL() {
206 LOG(LS_VERBOSE) << "ContinueSSL";
207 ASSERT(state_ == SSL_CONNECTING);
211 CSecBufferBundle<2> sb_in;
212 sb_in[0].BufferType = SECBUFFER_TOKEN;
213 sb_in[0].cbBuffer = static_cast<unsigned long>(impl_->inbuf.size());
214 sb_in[0].pvBuffer = &impl_->inbuf[0];
215 //DescribeBuffers(LS_VERBOSE, "Input Buffer ", sb_in.desc());
217 ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
218 if (ignore_bad_cert())
219 flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
221 CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
222 ret = InitializeSecurityContextA(&impl_->cred, &impl_->ctx,
223 const_cast<char*>(ssl_host_name_.c_str()),
224 flags, 0, 0, sb_in.desc(), 0,
227 return ProcessContext(ret, sb_in.desc(), sb_out.desc());
231 SChannelAdapter::ProcessContext(long int status, _SecBufferDesc* sbd_in,
232 _SecBufferDesc* sbd_out) {
233 if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED &&
234 status != SEC_E_INCOMPLETE_MESSAGE) {
236 << "InitializeSecurityContext error: "
237 << ErrorName(status, SECURITY_ERRORS);
240 // DescribeBuffers(LS_VERBOSE, "Input Buffer ", sbd_in);
242 // DescribeBuffers(LS_VERBOSE, "Output Buffer ", sbd_out);
244 if (status == SEC_E_INCOMPLETE_MESSAGE) {
245 // Wait for more input from server.
249 if (FAILED(status)) {
250 // We can't continue. Common errors:
251 // SEC_E_CERT_EXPIRED - Typically, this means the computer clock is wrong.
255 // Note: we check both input and output buffers for SECBUFFER_EXTRA.
256 // Experience shows it appearing in the input, but the documentation claims
257 // it should appear in the output.
260 for (size_t i=0; i<sbd_in->cBuffers; ++i) {
261 SecBuffer& buffer = sbd_in->pBuffers[i];
262 if (buffer.BufferType == SECBUFFER_EXTRA) {
263 extra += buffer.cbBuffer;
268 for (size_t i=0; i<sbd_out->cBuffers; ++i) {
269 SecBuffer& buffer = sbd_out->pBuffers[i];
270 if (buffer.BufferType == SECBUFFER_EXTRA) {
271 extra += buffer.cbBuffer;
272 } else if (buffer.BufferType == SECBUFFER_TOKEN) {
273 impl_->outbuf.insert(impl_->outbuf.end(),
274 reinterpret_cast<char*>(buffer.pvBuffer),
275 reinterpret_cast<char*>(buffer.pvBuffer) + buffer.cbBuffer);
281 ASSERT(extra <= impl_->inbuf.size());
282 size_t consumed = impl_->inbuf.size() - extra;
283 memmove(&impl_->inbuf[0], &impl_->inbuf[consumed], extra);
284 impl_->inbuf.resize(extra);
286 impl_->inbuf.clear();
289 if (SEC_I_CONTINUE_NEEDED == status) {
290 // Send data to server and wait for response.
291 // Note: ContinueSSL will result in a Flush, anyway.
292 return impl_->inbuf.empty() ? Flush() : ContinueSSL();
295 if (SEC_E_OK == status) {
296 LOG(LS_VERBOSE) << "QueryContextAttributes";
297 status = QueryContextAttributes(&impl_->ctx, SECPKG_ATTR_STREAM_SIZES,
299 if (FAILED(status)) {
300 LOG(LS_ERROR) << "QueryContextAttributes error: "
301 << ErrorName(status, SECURITY_ERRORS);
305 state_ = SSL_CONNECTED;
307 if (int err = DecryptData()) {
309 } else if (int err = Flush()) {
312 // If we decrypted any data, queue up a notification here
314 // Signal our connectedness
315 AsyncSocketAdapter::OnConnectEvent(this);
320 if (SEC_I_INCOMPLETE_CREDENTIALS == status) {
321 // We don't support client authentication in schannel.
325 // We don't expect any other codes
331 SChannelAdapter::DecryptData() {
332 SChannelBuffer& inbuf = impl_->inbuf;
333 SChannelBuffer& readable = impl_->readable;
335 while (!inbuf.empty()) {
336 CSecBufferBundle<4> in_buf;
337 in_buf[0].BufferType = SECBUFFER_DATA;
338 in_buf[0].cbBuffer = static_cast<unsigned long>(inbuf.size());
339 in_buf[0].pvBuffer = &inbuf[0];
341 //DescribeBuffers(LS_VERBOSE, "Decrypt In ", in_buf.desc());
342 SECURITY_STATUS status = DecryptMessage(&impl_->ctx, in_buf.desc(), 0, 0);
343 //DescribeBuffers(LS_VERBOSE, "Decrypt Out ", in_buf.desc());
345 // Note: We are explicitly treating SEC_E_OK, SEC_I_CONTEXT_EXPIRED, and
346 // any other successful results as continue.
347 if (SUCCEEDED(status)) {
348 size_t data_len = 0, extra_len = 0;
349 for (size_t i=0; i<in_buf.desc()->cBuffers; ++i) {
350 if (in_buf[i].BufferType == SECBUFFER_DATA) {
351 data_len += in_buf[i].cbBuffer;
352 readable.insert(readable.end(),
353 reinterpret_cast<char*>(in_buf[i].pvBuffer),
354 reinterpret_cast<char*>(in_buf[i].pvBuffer) + in_buf[i].cbBuffer);
355 } else if (in_buf[i].BufferType == SECBUFFER_EXTRA) {
356 extra_len += in_buf[i].cbBuffer;
359 // There is a bug on Win2K where SEC_I_CONTEXT_EXPIRED is misclassified.
360 if ((data_len == 0) && (inbuf[0] == 0x15)) {
361 status = SEC_I_CONTEXT_EXPIRED;
364 size_t consumed = inbuf.size() - extra_len;
365 memmove(&inbuf[0], &inbuf[consumed], extra_len);
366 inbuf.resize(extra_len);
370 // TODO: Handle SEC_I_CONTEXT_EXPIRED to do clean shutdown
371 if (status != SEC_E_OK) {
372 LOG(LS_INFO) << "DecryptMessage returned continuation code: "
373 << ErrorName(status, SECURITY_ERRORS);
378 if (status == SEC_E_INCOMPLETE_MESSAGE) {
389 SChannelAdapter::Cleanup() {
391 DeleteSecurityContext(&impl_->ctx);
392 if (impl_->cred_init)
393 FreeCredentialsHandle(&impl_->cred);
398 SChannelAdapter::PostEvent() {
399 // Check if there's anything notable to signal
400 if (impl_->readable.empty() && !signal_close_)
403 // Only one post in the queue at a time
404 if (message_pending_)
407 if (Thread* thread = Thread::Current()) {
408 message_pending_ = true;
411 LOG(LS_ERROR) << "No thread context available for SChannelAdapter";
417 SChannelAdapter::Error(const char* context, int err, bool signal) {
418 LOG(LS_WARNING) << "SChannelAdapter::Error("
420 << ErrorName(err, SECURITY_ERRORS) << ")";
424 AsyncSocketAdapter::OnCloseEvent(this, err);
428 SChannelAdapter::Read() {
430 SChannelBuffer& inbuf = impl_->inbuf;
432 int ret = AsyncSocketAdapter::Recv(buffer, sizeof(buffer));
434 inbuf.insert(inbuf.end(), buffer, buffer + ret);
435 } else if (GetError() == EWOULDBLOCK) {
436 return 0; // Blocking
444 SChannelAdapter::Flush() {
447 SChannelBuffer& outbuf = impl_->outbuf;
448 while (pos < outbuf.size()) {
449 int sent = AsyncSocketAdapter::Send(&outbuf[pos], outbuf.size() - pos);
452 } else if (GetError() == EWOULDBLOCK) {
459 if (int remainder = static_cast<int>(outbuf.size() - pos)) {
460 memmove(&outbuf[0], &outbuf[pos], remainder);
461 outbuf.resize(remainder);
469 // AsyncSocket Implementation
473 SChannelAdapter::Send(const void* pv, size_t cb) {
476 return AsyncSocketAdapter::Send(pv, cb);
480 SetError(EWOULDBLOCK);
492 SChannelBuffer& outbuf = impl_->outbuf;
493 while (written < cb) {
494 const size_t encrypt_len = std::min<size_t>(cb - written,
495 impl_->sizes.cbMaximumMessage);
497 CSecBufferBundle<4> out_buf;
498 out_buf[0].BufferType = SECBUFFER_STREAM_HEADER;
499 out_buf[0].cbBuffer = impl_->sizes.cbHeader;
500 out_buf[1].BufferType = SECBUFFER_DATA;
501 out_buf[1].cbBuffer = static_cast<unsigned long>(encrypt_len);
502 out_buf[2].BufferType = SECBUFFER_STREAM_TRAILER;
503 out_buf[2].cbBuffer = impl_->sizes.cbTrailer;
505 size_t packet_len = out_buf[0].cbBuffer
506 + out_buf[1].cbBuffer
507 + out_buf[2].cbBuffer;
509 SChannelBuffer message;
510 message.resize(packet_len);
511 out_buf[0].pvBuffer = &message[0];
512 out_buf[1].pvBuffer = &message[out_buf[0].cbBuffer];
513 out_buf[2].pvBuffer = &message[out_buf[0].cbBuffer + out_buf[1].cbBuffer];
515 memcpy(out_buf[1].pvBuffer,
516 static_cast<const char*>(pv) + written,
519 //DescribeBuffers(LS_VERBOSE, "Encrypt In ", out_buf.desc());
520 SECURITY_STATUS res = EncryptMessage(&impl_->ctx, 0, out_buf.desc(), 0);
521 //DescribeBuffers(LS_VERBOSE, "Encrypt Out ", out_buf.desc());
524 Error("EncryptMessage", res, false);
528 // We assume that the header and data segments do not change length,
529 // or else encrypting the concatenated packet in-place is wrong.
530 ASSERT(out_buf[0].cbBuffer == impl_->sizes.cbHeader);
531 ASSERT(out_buf[1].cbBuffer == static_cast<unsigned long>(encrypt_len));
533 // However, the length of the trailer may change due to padding.
534 ASSERT(out_buf[2].cbBuffer <= impl_->sizes.cbTrailer);
536 packet_len = out_buf[0].cbBuffer
537 + out_buf[1].cbBuffer
538 + out_buf[2].cbBuffer;
540 written += encrypt_len;
541 outbuf.insert(outbuf.end(), &message[0], &message[packet_len-1]+1);
544 if (int err = Flush()) {
550 return static_cast<int>(written);
554 SChannelAdapter::Recv(void* pv, size_t cb) {
557 return AsyncSocketAdapter::Recv(pv, cb);
561 SetError(EWOULDBLOCK);
572 SChannelBuffer& readable = impl_->readable;
573 if (readable.empty()) {
574 SetError(EWOULDBLOCK);
577 size_t read = _min(cb, readable.size());
578 memcpy(pv, &readable[0], read);
579 if (size_t remaining = readable.size() - read) {
580 memmove(&readable[0], &readable[read], remaining);
581 readable.resize(remaining);
587 return static_cast<int>(read);
591 SChannelAdapter::Close() {
592 if (!impl_->readable.empty()) {
593 LOG(WARNING) << "SChannelAdapter::Close with readable data";
594 // Note: this isn't strictly an error, but we're using it temporarily to
598 if (state_ == SSL_CONNECTED) {
599 DWORD token = SCHANNEL_SHUTDOWN;
600 CSecBufferBundle<1> sb_in;
601 sb_in[0].BufferType = SECBUFFER_TOKEN;
602 sb_in[0].cbBuffer = sizeof(token);
603 sb_in[0].pvBuffer = &token;
604 ApplyControlToken(&impl_->ctx, sb_in.desc());
605 // TODO: In theory, to do a nice shutdown, we need to begin shutdown
606 // negotiation with more calls to InitializeSecurityContext. Since the
607 // socket api doesn't support nice shutdown at this point, we don't bother.
611 state_ = restartable_ ? SSL_WAIT : SSL_NONE;
612 signal_close_ = false;
613 message_pending_ = false;
614 return AsyncSocketAdapter::Close();
618 SChannelAdapter::GetState() const {
621 ConnState state = socket_->GetState();
622 if ((state == CS_CONNECTED)
623 && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
624 state = CS_CONNECTING;
629 SChannelAdapter::OnConnectEvent(AsyncSocket* socket) {
630 LOG(LS_VERBOSE) << "SChannelAdapter::OnConnectEvent";
631 if (state_ != SSL_WAIT) {
632 ASSERT(state_ == SSL_NONE);
633 AsyncSocketAdapter::OnConnectEvent(socket);
637 state_ = SSL_CONNECTING;
638 if (int err = BeginSSL()) {
639 Error("BeginSSL", err);
644 SChannelAdapter::OnReadEvent(AsyncSocket* socket) {
645 if (state_ == SSL_NONE) {
646 AsyncSocketAdapter::OnReadEvent(socket);
650 if (int err = Read()) {
655 if (impl_->inbuf.empty())
658 if (state_ == SSL_CONNECTED) {
659 if (int err = DecryptData()) {
660 Error("DecryptData", err);
661 } else if (!impl_->readable.empty()) {
662 AsyncSocketAdapter::OnReadEvent(this);
664 } else if (state_ == SSL_CONNECTING) {
665 if (int err = ContinueSSL()) {
666 Error("ContinueSSL", err);
672 SChannelAdapter::OnWriteEvent(AsyncSocket* socket) {
673 if (state_ == SSL_NONE) {
674 AsyncSocketAdapter::OnWriteEvent(socket);
678 if (int err = Flush()) {
683 // See if we have more data to write
684 if (!impl_->outbuf.empty())
687 // Buffer is empty, submit notification
688 if (state_ == SSL_CONNECTED) {
689 AsyncSocketAdapter::OnWriteEvent(socket);
694 SChannelAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
695 if ((state_ == SSL_NONE) || impl_->readable.empty()) {
696 AsyncSocketAdapter::OnCloseEvent(socket, err);
700 // If readable is non-empty, then we have a pending Message
701 // that will allow us to signal close (eventually).
702 signal_close_ = true;
706 SChannelAdapter::OnMessage(Message* pmsg) {
707 if (!message_pending_)
708 return; // This occurs when socket is closed
710 message_pending_ = false;
711 if (!impl_->readable.empty()) {
712 AsyncSocketAdapter::OnReadEvent(this);
713 } else if (signal_close_) {
714 signal_close_ = false;
715 AsyncSocketAdapter::OnCloseEvent(this, 0); // TODO: cache this error?
719 } // namespace talk_base