You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

719 lines
21 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  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.
  15. *
  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.
  26. */
  27. #include "talk/base/win32.h"
  28. #define SECURITY_WIN32
  29. #include <security.h>
  30. #include <schannel.h>
  31. #include <iomanip>
  32. #include <vector>
  33. #include "talk/base/common.h"
  34. #include "talk/base/logging.h"
  35. #include "talk/base/schanneladapter.h"
  36. #include "talk/base/sec_buffer.h"
  37. #include "talk/base/thread.h"
  38. namespace talk_base {
  39. /////////////////////////////////////////////////////////////////////////////
  40. // SChannelAdapter
  41. /////////////////////////////////////////////////////////////////////////////
  42. extern const ConstantLabel SECURITY_ERRORS[];
  43. const ConstantLabel SCHANNEL_BUFFER_TYPES[] = {
  44. KLABEL(SECBUFFER_EMPTY), // 0
  45. KLABEL(SECBUFFER_DATA), // 1
  46. KLABEL(SECBUFFER_TOKEN), // 2
  47. KLABEL(SECBUFFER_PKG_PARAMS), // 3
  48. KLABEL(SECBUFFER_MISSING), // 4
  49. KLABEL(SECBUFFER_EXTRA), // 5
  50. KLABEL(SECBUFFER_STREAM_TRAILER), // 6
  51. KLABEL(SECBUFFER_STREAM_HEADER), // 7
  52. KLABEL(SECBUFFER_MECHLIST), // 11
  53. KLABEL(SECBUFFER_MECHLIST_SIGNATURE), // 12
  54. KLABEL(SECBUFFER_TARGET), // 13
  55. KLABEL(SECBUFFER_CHANNEL_BINDINGS), // 14
  56. LASTLABEL
  57. };
  58. void DescribeBuffer(LoggingSeverity severity, const char* prefix,
  59. const SecBuffer& sb) {
  60. LOG_V(severity)
  61. << prefix
  62. << "(" << sb.cbBuffer
  63. << ", " << FindLabel(sb.BufferType & ~SECBUFFER_ATTRMASK,
  64. SCHANNEL_BUFFER_TYPES)
  65. << ", " << sb.pvBuffer << ")";
  66. }
  67. void DescribeBuffers(LoggingSeverity severity, const char* prefix,
  68. const SecBufferDesc* sbd) {
  69. if (!LOG_CHECK_LEVEL_V(severity))
  70. return;
  71. LOG_V(severity) << prefix << "(";
  72. for (size_t i=0; i<sbd->cBuffers; ++i) {
  73. DescribeBuffer(severity, " ", sbd->pBuffers[i]);
  74. }
  75. LOG_V(severity) << ")";
  76. }
  77. const ULONG SSL_FLAGS_DEFAULT = ISC_REQ_ALLOCATE_MEMORY
  78. | ISC_REQ_CONFIDENTIALITY
  79. | ISC_REQ_EXTENDED_ERROR
  80. | ISC_REQ_INTEGRITY
  81. | ISC_REQ_REPLAY_DETECT
  82. | ISC_REQ_SEQUENCE_DETECT
  83. | ISC_REQ_STREAM;
  84. //| ISC_REQ_USE_SUPPLIED_CREDS;
  85. typedef std::vector<char> SChannelBuffer;
  86. struct SChannelAdapter::SSLImpl {
  87. CredHandle cred;
  88. CtxtHandle ctx;
  89. bool cred_init, ctx_init;
  90. SChannelBuffer inbuf, outbuf, readable;
  91. SecPkgContext_StreamSizes sizes;
  92. SSLImpl() : cred_init(false), ctx_init(false) { }
  93. };
  94. SChannelAdapter::SChannelAdapter(AsyncSocket* socket)
  95. : SSLAdapter(socket), state_(SSL_NONE),
  96. restartable_(false), signal_close_(false), message_pending_(false),
  97. impl_(new SSLImpl) {
  98. }
  99. SChannelAdapter::~SChannelAdapter() {
  100. Cleanup();
  101. }
  102. int
  103. SChannelAdapter::StartSSL(const char* hostname, bool restartable) {
  104. if (state_ != SSL_NONE)
  105. return ERROR_ALREADY_INITIALIZED;
  106. ssl_host_name_ = hostname;
  107. restartable_ = restartable;
  108. if (socket_->GetState() != Socket::CS_CONNECTED) {
  109. state_ = SSL_WAIT;
  110. return 0;
  111. }
  112. state_ = SSL_CONNECTING;
  113. if (int err = BeginSSL()) {
  114. Error("BeginSSL", err, false);
  115. return err;
  116. }
  117. return 0;
  118. }
  119. int
  120. SChannelAdapter::BeginSSL() {
  121. LOG(LS_VERBOSE) << "BeginSSL: " << ssl_host_name_;
  122. ASSERT(state_ == SSL_CONNECTING);
  123. SECURITY_STATUS ret;
  124. SCHANNEL_CRED sc_cred = { 0 };
  125. sc_cred.dwVersion = SCHANNEL_CRED_VERSION;
  126. //sc_cred.dwMinimumCipherStrength = 128; // Note: use system default
  127. sc_cred.dwFlags = SCH_CRED_NO_DEFAULT_CREDS | SCH_CRED_AUTO_CRED_VALIDATION;
  128. ret = AcquireCredentialsHandle(NULL, UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL,
  129. &sc_cred, NULL, NULL, &impl_->cred, NULL);
  130. if (ret != SEC_E_OK) {
  131. LOG(LS_ERROR) << "AcquireCredentialsHandle error: "
  132. << ErrorName(ret, SECURITY_ERRORS);
  133. return ret;
  134. }
  135. impl_->cred_init = true;
  136. if (LOG_CHECK_LEVEL(LS_VERBOSE)) {
  137. SecPkgCred_CipherStrengths cipher_strengths = { 0 };
  138. ret = QueryCredentialsAttributes(&impl_->cred,
  139. SECPKG_ATTR_CIPHER_STRENGTHS,
  140. &cipher_strengths);
  141. if (SUCCEEDED(ret)) {
  142. LOG(LS_VERBOSE) << "SChannel cipher strength: "
  143. << cipher_strengths.dwMinimumCipherStrength << " - "
  144. << cipher_strengths.dwMaximumCipherStrength;
  145. }
  146. SecPkgCred_SupportedAlgs supported_algs = { 0 };
  147. ret = QueryCredentialsAttributes(&impl_->cred,
  148. SECPKG_ATTR_SUPPORTED_ALGS,
  149. &supported_algs);
  150. if (SUCCEEDED(ret)) {
  151. LOG(LS_VERBOSE) << "SChannel supported algorithms:";
  152. for (DWORD i=0; i<supported_algs.cSupportedAlgs; ++i) {
  153. ALG_ID alg_id = supported_algs.palgSupportedAlgs[i];
  154. PCCRYPT_OID_INFO oinfo = CryptFindOIDInfo(CRYPT_OID_INFO_ALGID_KEY,
  155. &alg_id, 0);
  156. LPCWSTR alg_name = (NULL != oinfo) ? oinfo->pwszName : L"Unknown";
  157. LOG(LS_VERBOSE) << " " << ToUtf8(alg_name) << " (" << alg_id << ")";
  158. }
  159. CSecBufferBase::FreeSSPI(supported_algs.palgSupportedAlgs);
  160. }
  161. }
  162. ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
  163. if (ignore_bad_cert())
  164. flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
  165. CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
  166. ret = InitializeSecurityContextA(&impl_->cred, NULL,
  167. const_cast<char*>(ssl_host_name_.c_str()),
  168. flags, 0, 0, NULL, 0,
  169. &impl_->ctx, sb_out.desc(),
  170. &ret_flags, NULL);
  171. if (SUCCEEDED(ret))
  172. impl_->ctx_init = true;
  173. return ProcessContext(ret, NULL, sb_out.desc());
  174. }
  175. int
  176. SChannelAdapter::ContinueSSL() {
  177. LOG(LS_VERBOSE) << "ContinueSSL";
  178. ASSERT(state_ == SSL_CONNECTING);
  179. SECURITY_STATUS ret;
  180. CSecBufferBundle<2> sb_in;
  181. sb_in[0].BufferType = SECBUFFER_TOKEN;
  182. sb_in[0].cbBuffer = static_cast<unsigned long>(impl_->inbuf.size());
  183. sb_in[0].pvBuffer = &impl_->inbuf[0];
  184. //DescribeBuffers(LS_VERBOSE, "Input Buffer ", sb_in.desc());
  185. ULONG flags = SSL_FLAGS_DEFAULT, ret_flags = 0;
  186. if (ignore_bad_cert())
  187. flags |= ISC_REQ_MANUAL_CRED_VALIDATION;
  188. CSecBufferBundle<2, CSecBufferBase::FreeSSPI> sb_out;
  189. ret = InitializeSecurityContextA(&impl_->cred, &impl_->ctx,
  190. const_cast<char*>(ssl_host_name_.c_str()),
  191. flags, 0, 0, sb_in.desc(), 0,
  192. NULL, sb_out.desc(),
  193. &ret_flags, NULL);
  194. return ProcessContext(ret, sb_in.desc(), sb_out.desc());
  195. }
  196. int
  197. SChannelAdapter::ProcessContext(long int status, _SecBufferDesc* sbd_in,
  198. _SecBufferDesc* sbd_out) {
  199. if (status != SEC_E_OK && status != SEC_I_CONTINUE_NEEDED &&
  200. status != SEC_E_INCOMPLETE_MESSAGE) {
  201. LOG(LS_ERROR)
  202. << "InitializeSecurityContext error: "
  203. << ErrorName(status, SECURITY_ERRORS);
  204. }
  205. //if (sbd_in)
  206. // DescribeBuffers(LS_VERBOSE, "Input Buffer ", sbd_in);
  207. //if (sbd_out)
  208. // DescribeBuffers(LS_VERBOSE, "Output Buffer ", sbd_out);
  209. if (status == SEC_E_INCOMPLETE_MESSAGE) {
  210. // Wait for more input from server.
  211. return Flush();
  212. }
  213. if (FAILED(status)) {
  214. // We can't continue. Common errors:
  215. // SEC_E_CERT_EXPIRED - Typically, this means the computer clock is wrong.
  216. return status;
  217. }
  218. // Note: we check both input and output buffers for SECBUFFER_EXTRA.
  219. // Experience shows it appearing in the input, but the documentation claims
  220. // it should appear in the output.
  221. size_t extra = 0;
  222. if (sbd_in) {
  223. for (size_t i=0; i<sbd_in->cBuffers; ++i) {
  224. SecBuffer& buffer = sbd_in->pBuffers[i];
  225. if (buffer.BufferType == SECBUFFER_EXTRA) {
  226. extra += buffer.cbBuffer;
  227. }
  228. }
  229. }
  230. if (sbd_out) {
  231. for (size_t i=0; i<sbd_out->cBuffers; ++i) {
  232. SecBuffer& buffer = sbd_out->pBuffers[i];
  233. if (buffer.BufferType == SECBUFFER_EXTRA) {
  234. extra += buffer.cbBuffer;
  235. } else if (buffer.BufferType == SECBUFFER_TOKEN) {
  236. impl_->outbuf.insert(impl_->outbuf.end(),
  237. reinterpret_cast<char*>(buffer.pvBuffer),
  238. reinterpret_cast<char*>(buffer.pvBuffer) + buffer.cbBuffer);
  239. }
  240. }
  241. }
  242. if (extra) {
  243. ASSERT(extra <= impl_->inbuf.size());
  244. size_t consumed = impl_->inbuf.size() - extra;
  245. memmove(&impl_->inbuf[0], &impl_->inbuf[consumed], extra);
  246. impl_->inbuf.resize(extra);
  247. } else {
  248. impl_->inbuf.clear();
  249. }
  250. if (SEC_I_CONTINUE_NEEDED == status) {
  251. // Send data to server and wait for response.
  252. // Note: ContinueSSL will result in a Flush, anyway.
  253. return impl_->inbuf.empty() ? Flush() : ContinueSSL();
  254. }
  255. if (SEC_E_OK == status) {
  256. LOG(LS_VERBOSE) << "QueryContextAttributes";
  257. status = QueryContextAttributes(&impl_->ctx, SECPKG_ATTR_STREAM_SIZES,
  258. &impl_->sizes);
  259. if (FAILED(status)) {
  260. LOG(LS_ERROR) << "QueryContextAttributes error: "
  261. << ErrorName(status, SECURITY_ERRORS);
  262. return status;
  263. }
  264. state_ = SSL_CONNECTED;
  265. if (int err = DecryptData()) {
  266. return err;
  267. } else if (int err = Flush()) {
  268. return err;
  269. } else {
  270. // If we decrypted any data, queue up a notification here
  271. PostEvent();
  272. // Signal our connectedness
  273. AsyncSocketAdapter::OnConnectEvent(this);
  274. }
  275. return 0;
  276. }
  277. if (SEC_I_INCOMPLETE_CREDENTIALS == status) {
  278. // We don't support client authentication in schannel.
  279. return status;
  280. }
  281. // We don't expect any other codes
  282. ASSERT(false);
  283. return status;
  284. }
  285. int
  286. SChannelAdapter::DecryptData() {
  287. SChannelBuffer& inbuf = impl_->inbuf;
  288. SChannelBuffer& readable = impl_->readable;
  289. while (!inbuf.empty()) {
  290. CSecBufferBundle<4> in_buf;
  291. in_buf[0].BufferType = SECBUFFER_DATA;
  292. in_buf[0].cbBuffer = static_cast<unsigned long>(inbuf.size());
  293. in_buf[0].pvBuffer = &inbuf[0];
  294. //DescribeBuffers(LS_VERBOSE, "Decrypt In ", in_buf.desc());
  295. SECURITY_STATUS status = DecryptMessage(&impl_->ctx, in_buf.desc(), 0, 0);
  296. //DescribeBuffers(LS_VERBOSE, "Decrypt Out ", in_buf.desc());
  297. // Note: We are explicitly treating SEC_E_OK, SEC_I_CONTEXT_EXPIRED, and
  298. // any other successful results as continue.
  299. if (SUCCEEDED(status)) {
  300. size_t data_len = 0, extra_len = 0;
  301. for (size_t i=0; i<in_buf.desc()->cBuffers; ++i) {
  302. if (in_buf[i].BufferType == SECBUFFER_DATA) {
  303. data_len += in_buf[i].cbBuffer;
  304. readable.insert(readable.end(),
  305. reinterpret_cast<char*>(in_buf[i].pvBuffer),
  306. reinterpret_cast<char*>(in_buf[i].pvBuffer) + in_buf[i].cbBuffer);
  307. } else if (in_buf[i].BufferType == SECBUFFER_EXTRA) {
  308. extra_len += in_buf[i].cbBuffer;
  309. }
  310. }
  311. // There is a bug on Win2K where SEC_I_CONTEXT_EXPIRED is misclassified.
  312. if ((data_len == 0) && (inbuf[0] == 0x15)) {
  313. status = SEC_I_CONTEXT_EXPIRED;
  314. }
  315. if (extra_len) {
  316. size_t consumed = inbuf.size() - extra_len;
  317. memmove(&inbuf[0], &inbuf[consumed], extra_len);
  318. inbuf.resize(extra_len);
  319. } else {
  320. inbuf.clear();
  321. }
  322. // TODO: Handle SEC_I_CONTEXT_EXPIRED to do clean shutdown
  323. if (status != SEC_E_OK) {
  324. LOG(LS_INFO) << "DecryptMessage returned continuation code: "
  325. << ErrorName(status, SECURITY_ERRORS);
  326. }
  327. continue;
  328. }
  329. if (status == SEC_E_INCOMPLETE_MESSAGE) {
  330. break;
  331. } else {
  332. return status;
  333. }
  334. }
  335. return 0;
  336. }
  337. void
  338. SChannelAdapter::Cleanup() {
  339. if (impl_->ctx_init)
  340. DeleteSecurityContext(&impl_->ctx);
  341. if (impl_->cred_init)
  342. FreeCredentialsHandle(&impl_->cred);
  343. delete impl_;
  344. }
  345. void
  346. SChannelAdapter::PostEvent() {
  347. // Check if there's anything notable to signal
  348. if (impl_->readable.empty() && !signal_close_)
  349. return;
  350. // Only one post in the queue at a time
  351. if (message_pending_)
  352. return;
  353. if (Thread* thread = Thread::Current()) {
  354. message_pending_ = true;
  355. thread->Post(this);
  356. } else {
  357. LOG(LS_ERROR) << "No thread context available for SChannelAdapter";
  358. ASSERT(false);
  359. }
  360. }
  361. void
  362. SChannelAdapter::Error(const char* context, int err, bool signal) {
  363. LOG(LS_WARNING) << "SChannelAdapter::Error("
  364. << context << ", "
  365. << ErrorName(err, SECURITY_ERRORS) << ")";
  366. state_ = SSL_ERROR;
  367. SetError(err);
  368. if (signal)
  369. AsyncSocketAdapter::OnCloseEvent(this, err);
  370. }
  371. int
  372. SChannelAdapter::Read() {
  373. char buffer[4096];
  374. SChannelBuffer& inbuf = impl_->inbuf;
  375. while (true) {
  376. int ret = AsyncSocketAdapter::Recv(buffer, sizeof(buffer));
  377. if (ret > 0) {
  378. inbuf.insert(inbuf.end(), buffer, buffer + ret);
  379. } else if (GetError() == EWOULDBLOCK) {
  380. return 0; // Blocking
  381. } else {
  382. return GetError();
  383. }
  384. }
  385. }
  386. int
  387. SChannelAdapter::Flush() {
  388. int result = 0;
  389. size_t pos = 0;
  390. SChannelBuffer& outbuf = impl_->outbuf;
  391. while (pos < outbuf.size()) {
  392. int sent = AsyncSocketAdapter::Send(&outbuf[pos], outbuf.size() - pos);
  393. if (sent > 0) {
  394. pos += sent;
  395. } else if (GetError() == EWOULDBLOCK) {
  396. break; // Blocking
  397. } else {
  398. result = GetError();
  399. break;
  400. }
  401. }
  402. if (int remainder = static_cast<int>(outbuf.size() - pos)) {
  403. memmove(&outbuf[0], &outbuf[pos], remainder);
  404. outbuf.resize(remainder);
  405. } else {
  406. outbuf.clear();
  407. }
  408. return result;
  409. }
  410. //
  411. // AsyncSocket Implementation
  412. //
  413. int
  414. SChannelAdapter::Send(const void* pv, size_t cb) {
  415. switch (state_) {
  416. case SSL_NONE:
  417. return AsyncSocketAdapter::Send(pv, cb);
  418. case SSL_WAIT:
  419. case SSL_CONNECTING:
  420. SetError(EWOULDBLOCK);
  421. return SOCKET_ERROR;
  422. case SSL_CONNECTED:
  423. break;
  424. case SSL_ERROR:
  425. default:
  426. return SOCKET_ERROR;
  427. }
  428. size_t written = 0;
  429. SChannelBuffer& outbuf = impl_->outbuf;
  430. while (written < cb) {
  431. const size_t encrypt_len = std::min<size_t>(cb - written,
  432. impl_->sizes.cbMaximumMessage);
  433. CSecBufferBundle<4> out_buf;
  434. out_buf[0].BufferType = SECBUFFER_STREAM_HEADER;
  435. out_buf[0].cbBuffer = impl_->sizes.cbHeader;
  436. out_buf[1].BufferType = SECBUFFER_DATA;
  437. out_buf[1].cbBuffer = static_cast<unsigned long>(encrypt_len);
  438. out_buf[2].BufferType = SECBUFFER_STREAM_TRAILER;
  439. out_buf[2].cbBuffer = impl_->sizes.cbTrailer;
  440. size_t packet_len = out_buf[0].cbBuffer
  441. + out_buf[1].cbBuffer
  442. + out_buf[2].cbBuffer;
  443. SChannelBuffer message;
  444. message.resize(packet_len);
  445. out_buf[0].pvBuffer = &message[0];
  446. out_buf[1].pvBuffer = &message[out_buf[0].cbBuffer];
  447. out_buf[2].pvBuffer = &message[out_buf[0].cbBuffer + out_buf[1].cbBuffer];
  448. memcpy(out_buf[1].pvBuffer,
  449. static_cast<const char*>(pv) + written,
  450. encrypt_len);
  451. //DescribeBuffers(LS_VERBOSE, "Encrypt In ", out_buf.desc());
  452. SECURITY_STATUS res = EncryptMessage(&impl_->ctx, 0, out_buf.desc(), 0);
  453. //DescribeBuffers(LS_VERBOSE, "Encrypt Out ", out_buf.desc());
  454. if (FAILED(res)) {
  455. Error("EncryptMessage", res, false);
  456. return SOCKET_ERROR;
  457. }
  458. // We assume that the header and data segments do not change length,
  459. // or else encrypting the concatenated packet in-place is wrong.
  460. ASSERT(out_buf[0].cbBuffer == impl_->sizes.cbHeader);
  461. ASSERT(out_buf[1].cbBuffer == static_cast<unsigned long>(encrypt_len));
  462. // However, the length of the trailer may change due to padding.
  463. ASSERT(out_buf[2].cbBuffer <= impl_->sizes.cbTrailer);
  464. packet_len = out_buf[0].cbBuffer
  465. + out_buf[1].cbBuffer
  466. + out_buf[2].cbBuffer;
  467. written += encrypt_len;
  468. outbuf.insert(outbuf.end(), &message[0], &message[packet_len-1]+1);
  469. }
  470. if (int err = Flush()) {
  471. state_ = SSL_ERROR;
  472. SetError(err);
  473. return SOCKET_ERROR;
  474. }
  475. return static_cast<int>(written);
  476. }
  477. int
  478. SChannelAdapter::Recv(void* pv, size_t cb) {
  479. switch (state_) {
  480. case SSL_NONE:
  481. return AsyncSocketAdapter::Recv(pv, cb);
  482. case SSL_WAIT:
  483. case SSL_CONNECTING:
  484. SetError(EWOULDBLOCK);
  485. return SOCKET_ERROR;
  486. case SSL_CONNECTED:
  487. break;
  488. case SSL_ERROR:
  489. default:
  490. return SOCKET_ERROR;
  491. }
  492. SChannelBuffer& readable = impl_->readable;
  493. if (readable.empty()) {
  494. SetError(EWOULDBLOCK);
  495. return SOCKET_ERROR;
  496. }
  497. size_t read = _min(cb, readable.size());
  498. memcpy(pv, &readable[0], read);
  499. if (size_t remaining = readable.size() - read) {
  500. memmove(&readable[0], &readable[read], remaining);
  501. readable.resize(remaining);
  502. } else {
  503. readable.clear();
  504. }
  505. PostEvent();
  506. return static_cast<int>(read);
  507. }
  508. int
  509. SChannelAdapter::Close() {
  510. if (!impl_->readable.empty()) {
  511. LOG(WARNING) << "SChannelAdapter::Close with readable data";
  512. // Note: this isn't strictly an error, but we're using it temporarily to
  513. // track bugs.
  514. //ASSERT(false);
  515. }
  516. if (state_ == SSL_CONNECTED) {
  517. DWORD token = SCHANNEL_SHUTDOWN;
  518. CSecBufferBundle<1> sb_in;
  519. sb_in[0].BufferType = SECBUFFER_TOKEN;
  520. sb_in[0].cbBuffer = sizeof(token);
  521. sb_in[0].pvBuffer = &token;
  522. ApplyControlToken(&impl_->ctx, sb_in.desc());
  523. // TODO: In theory, to do a nice shutdown, we need to begin shutdown
  524. // negotiation with more calls to InitializeSecurityContext. Since the
  525. // socket api doesn't support nice shutdown at this point, we don't bother.
  526. }
  527. Cleanup();
  528. impl_ = new SSLImpl;
  529. state_ = restartable_ ? SSL_WAIT : SSL_NONE;
  530. signal_close_ = false;
  531. message_pending_ = false;
  532. return AsyncSocketAdapter::Close();
  533. }
  534. Socket::ConnState
  535. SChannelAdapter::GetState() const {
  536. if (signal_close_)
  537. return CS_CONNECTED;
  538. ConnState state = socket_->GetState();
  539. if ((state == CS_CONNECTED)
  540. && ((state_ == SSL_WAIT) || (state_ == SSL_CONNECTING)))
  541. state = CS_CONNECTING;
  542. return state;
  543. }
  544. void
  545. SChannelAdapter::OnConnectEvent(AsyncSocket* socket) {
  546. LOG(LS_VERBOSE) << "SChannelAdapter::OnConnectEvent";
  547. if (state_ != SSL_WAIT) {
  548. ASSERT(state_ == SSL_NONE);
  549. AsyncSocketAdapter::OnConnectEvent(socket);
  550. return;
  551. }
  552. state_ = SSL_CONNECTING;
  553. if (int err = BeginSSL()) {
  554. Error("BeginSSL", err);
  555. }
  556. }
  557. void
  558. SChannelAdapter::OnReadEvent(AsyncSocket* socket) {
  559. if (state_ == SSL_NONE) {
  560. AsyncSocketAdapter::OnReadEvent(socket);
  561. return;
  562. }
  563. if (int err = Read()) {
  564. Error("Read", err);
  565. return;
  566. }
  567. if (impl_->inbuf.empty())
  568. return;
  569. if (state_ == SSL_CONNECTED) {
  570. if (int err = DecryptData()) {
  571. Error("DecryptData", err);
  572. } else if (!impl_->readable.empty()) {
  573. AsyncSocketAdapter::OnReadEvent(this);
  574. }
  575. } else if (state_ == SSL_CONNECTING) {
  576. if (int err = ContinueSSL()) {
  577. Error("ContinueSSL", err);
  578. }
  579. }
  580. }
  581. void
  582. SChannelAdapter::OnWriteEvent(AsyncSocket* socket) {
  583. if (state_ == SSL_NONE) {
  584. AsyncSocketAdapter::OnWriteEvent(socket);
  585. return;
  586. }
  587. if (int err = Flush()) {
  588. Error("Flush", err);
  589. return;
  590. }
  591. // See if we have more data to write
  592. if (!impl_->outbuf.empty())
  593. return;
  594. // Buffer is empty, submit notification
  595. if (state_ == SSL_CONNECTED) {
  596. AsyncSocketAdapter::OnWriteEvent(socket);
  597. }
  598. }
  599. void
  600. SChannelAdapter::OnCloseEvent(AsyncSocket* socket, int err) {
  601. if ((state_ == SSL_NONE) || impl_->readable.empty()) {
  602. AsyncSocketAdapter::OnCloseEvent(socket, err);
  603. return;
  604. }
  605. // If readable is non-empty, then we have a pending Message
  606. // that will allow us to signal close (eventually).
  607. signal_close_ = true;
  608. }
  609. void
  610. SChannelAdapter::OnMessage(Message* pmsg) {
  611. if (!message_pending_)
  612. return; // This occurs when socket is closed
  613. message_pending_ = false;
  614. if (!impl_->readable.empty()) {
  615. AsyncSocketAdapter::OnReadEvent(this);
  616. } else if (signal_close_) {
  617. signal_close_ = false;
  618. AsyncSocketAdapter::OnCloseEvent(this, 0); // TODO: cache this error?
  619. }
  620. }
  621. } // namespace talk_base