curl_schannel.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2012, Marc Hoersken, <info@marc-hoersken.de>, et al.
  9. * Copyright (C) 2012, Mark Salisbury, <mark.salisbury@hp.com>
  10. * Copyright (C) 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
  11. *
  12. * This software is licensed as described in the file COPYING, which
  13. * you should have received as part of this distribution. The terms
  14. * are also available at http://curl.haxx.se/docs/copyright.html.
  15. *
  16. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  17. * copies of the Software, and permit persons to whom the Software is
  18. * furnished to do so, under the terms of the COPYING file.
  19. *
  20. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  21. * KIND, either express or implied.
  22. *
  23. ***************************************************************************/
  24. /*
  25. * Source file for all SChannel-specific code for the TLS/SSL layer. No code
  26. * but sslgen.c should ever call or use these functions.
  27. *
  28. */
  29. /*
  30. * Based upon the PolarSSL implementation in polarssl.c and polarssl.h:
  31. * Copyright (C) 2010, 2011, Hoi-Ho Chan, <hoiho.chan@gmail.com>
  32. *
  33. * Based upon the CyaSSL implementation in cyassl.c and cyassl.h:
  34. * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
  35. *
  36. * Thanks for code and inspiration!
  37. */
  38. /*
  39. * TODO list for TLS/SSL implementation:
  40. * - implement client certificate authentication
  41. * - implement custom server certificate validation
  42. * - implement cipher/algorithm option
  43. *
  44. * Related articles on MSDN:
  45. * - Getting a Certificate for Schannel
  46. * http://msdn.microsoft.com/en-us/library/windows/desktop/aa375447.aspx
  47. * - Specifying Schannel Ciphers and Cipher Strengths
  48. * http://msdn.microsoft.com/en-us/library/windows/desktop/aa380161.aspx
  49. */
  50. #include "setup.h"
  51. #ifdef USE_SCHANNEL
  52. #ifndef USE_WINDOWS_SSPI
  53. # error "Can't compile SCHANNEL support without SSPI."
  54. #endif
  55. #include "curl_sspi.h"
  56. #include "curl_schannel.h"
  57. #include "sslgen.h"
  58. #include "sendf.h"
  59. #include "connect.h" /* for the connect timeout */
  60. #include "strerror.h"
  61. #include "select.h" /* for the socket readyness */
  62. #include "inet_pton.h" /* for IP addr SNI check */
  63. #include "curl_multibyte.h"
  64. #include "warnless.h"
  65. #define _MPRINTF_REPLACE /* use our functions only */
  66. #include <curl/mprintf.h>
  67. #include "curl_memory.h"
  68. /* The last #include file should be: */
  69. #include "memdebug.h"
  70. /* Uncomment to force verbose output
  71. * #define infof(x, y, ...) printf(y, __VA_ARGS__)
  72. * #define failf(x, y, ...) printf(y, __VA_ARGS__)
  73. */
  74. static Curl_recv schannel_recv;
  75. static Curl_send schannel_send;
  76. #ifdef _WIN32_WCE
  77. static CURLcode verify_certificate(struct connectdata *conn, int sockindex);
  78. #endif
  79. static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType,
  80. void *BufDataPtr, unsigned long BufByteSize)
  81. {
  82. buffer->cbBuffer = BufByteSize;
  83. buffer->BufferType = BufType;
  84. buffer->pvBuffer = BufDataPtr;
  85. }
  86. static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr,
  87. unsigned long NumArrElem)
  88. {
  89. desc->ulVersion = SECBUFFER_VERSION;
  90. desc->pBuffers = BufArr;
  91. desc->cBuffers = NumArrElem;
  92. }
  93. static CURLcode
  94. schannel_connect_step1(struct connectdata *conn, int sockindex)
  95. {
  96. ssize_t written = -1;
  97. struct SessionHandle *data = conn->data;
  98. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  99. SecBuffer outbuf;
  100. SecBufferDesc outbuf_desc;
  101. SCHANNEL_CRED schannel_cred;
  102. SECURITY_STATUS sspi_status = SEC_E_OK;
  103. struct curl_schannel_cred *old_cred = NULL;
  104. struct in_addr addr;
  105. #ifdef ENABLE_IPV6
  106. struct in6_addr addr6;
  107. #endif
  108. TCHAR *host_name;
  109. CURLcode code;
  110. infof(data, "schannel: SSL/TLS connection with %s port %hu (step 1/3)\n",
  111. conn->host.name, conn->remote_port);
  112. /* check for an existing re-usable credential handle */
  113. if(!Curl_ssl_getsessionid(conn, (void**)&old_cred, NULL)) {
  114. connssl->cred = old_cred;
  115. infof(data, "schannel: re-using existing credential handle\n");
  116. }
  117. else {
  118. /* setup Schannel API options */
  119. memset(&schannel_cred, 0, sizeof(schannel_cred));
  120. schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
  121. if(data->set.ssl.verifypeer) {
  122. #ifdef _WIN32_WCE
  123. /* certificate validation on CE doesn't seem to work right; we'll
  124. do it following a more manual process. */
  125. schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION |
  126. SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  127. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  128. #else
  129. schannel_cred.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION |
  130. SCH_CRED_REVOCATION_CHECK_CHAIN;
  131. #endif
  132. infof(data, "schannel: checking server certificate revocation\n");
  133. }
  134. else {
  135. schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION |
  136. SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  137. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  138. infof(data, "schannel: disable server certificate revocation checks\n");
  139. }
  140. if(Curl_inet_pton(AF_INET, conn->host.name, &addr) ||
  141. #ifdef ENABLE_IPV6
  142. Curl_inet_pton(AF_INET6, conn->host.name, &addr6) ||
  143. #endif
  144. data->set.ssl.verifyhost < 2) {
  145. schannel_cred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK;
  146. infof(data, "schannel: using IP address, disable SNI servername "
  147. "check\n");
  148. }
  149. switch(data->set.ssl.version) {
  150. case CURL_SSLVERSION_TLSv1:
  151. schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_0_CLIENT |
  152. SP_PROT_TLS1_1_CLIENT |
  153. SP_PROT_TLS1_2_CLIENT;
  154. break;
  155. case CURL_SSLVERSION_SSLv3:
  156. schannel_cred.grbitEnabledProtocols = SP_PROT_SSL3_CLIENT;
  157. break;
  158. case CURL_SSLVERSION_SSLv2:
  159. schannel_cred.grbitEnabledProtocols = SP_PROT_SSL2_CLIENT;
  160. break;
  161. }
  162. /* allocate memory for the re-usable credential handle */
  163. connssl->cred = malloc(sizeof(struct curl_schannel_cred));
  164. if(!connssl->cred) {
  165. failf(data, "schannel: unable to allocate memory");
  166. return CURLE_OUT_OF_MEMORY;
  167. }
  168. memset(connssl->cred, 0, sizeof(struct curl_schannel_cred));
  169. /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx */
  170. sspi_status = s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME,
  171. SECPKG_CRED_OUTBOUND, NULL, &schannel_cred, NULL, NULL,
  172. &connssl->cred->cred_handle, &connssl->cred->time_stamp);
  173. if(sspi_status != SEC_E_OK) {
  174. if(sspi_status == SEC_E_WRONG_PRINCIPAL)
  175. failf(data, "schannel: SNI or certificate check failed: %s",
  176. Curl_sspi_strerror(conn, sspi_status));
  177. else
  178. failf(data, "schannel: AcquireCredentialsHandle failed: %s",
  179. Curl_sspi_strerror(conn, sspi_status));
  180. Curl_safefree(connssl->cred);
  181. return CURLE_SSL_CONNECT_ERROR;
  182. }
  183. }
  184. /* setup output buffer */
  185. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  186. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  187. /* setup request flags */
  188. connssl->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
  189. ISC_REQ_CONFIDENTIALITY | ISC_REQ_EXTENDED_ERROR |
  190. ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM;
  191. /* allocate memory for the security context handle */
  192. connssl->ctxt = malloc(sizeof(struct curl_schannel_ctxt));
  193. if(!connssl->ctxt) {
  194. failf(data, "schannel: unable to allocate memory");
  195. return CURLE_OUT_OF_MEMORY;
  196. }
  197. memset(connssl->ctxt, 0, sizeof(struct curl_schannel_ctxt));
  198. host_name = Curl_convert_UTF8_to_tchar(conn->host.name);
  199. if(!host_name)
  200. return CURLE_OUT_OF_MEMORY;
  201. /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */
  202. sspi_status = s_pSecFn->InitializeSecurityContext(
  203. &connssl->cred->cred_handle, NULL, host_name,
  204. connssl->req_flags, 0, 0, NULL, 0, &connssl->ctxt->ctxt_handle,
  205. &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
  206. Curl_unicodefree(host_name);
  207. if(sspi_status != SEC_I_CONTINUE_NEEDED) {
  208. if(sspi_status == SEC_E_WRONG_PRINCIPAL)
  209. failf(data, "schannel: SNI or certificate check failed: %s",
  210. Curl_sspi_strerror(conn, sspi_status));
  211. else
  212. failf(data, "schannel: initial InitializeSecurityContext failed: %s",
  213. Curl_sspi_strerror(conn, sspi_status));
  214. Curl_safefree(connssl->ctxt);
  215. return CURLE_SSL_CONNECT_ERROR;
  216. }
  217. infof(data, "schannel: sending initial handshake data: "
  218. "sending %lu bytes...\n", outbuf.cbBuffer);
  219. /* send initial handshake data which is now stored in output buffer */
  220. code = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer,
  221. outbuf.cbBuffer, &written);
  222. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  223. if((code != CURLE_OK) || (outbuf.cbBuffer != (size_t)written)) {
  224. failf(data, "schannel: failed to send initial handshake data: "
  225. "sent %zd of %lu bytes", written, outbuf.cbBuffer);
  226. return CURLE_SSL_CONNECT_ERROR;
  227. }
  228. infof(data, "schannel: sent initial handshake data: "
  229. "sent %zd bytes\n", written);
  230. /* continue to second handshake step */
  231. connssl->connecting_state = ssl_connect_2;
  232. return CURLE_OK;
  233. }
  234. static CURLcode
  235. schannel_connect_step2(struct connectdata *conn, int sockindex)
  236. {
  237. int i;
  238. ssize_t nread = -1, written = -1;
  239. struct SessionHandle *data = conn->data;
  240. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  241. SecBuffer outbuf[2];
  242. SecBufferDesc outbuf_desc;
  243. SecBuffer inbuf[2];
  244. SecBufferDesc inbuf_desc;
  245. SECURITY_STATUS sspi_status = SEC_E_OK;
  246. TCHAR *host_name;
  247. CURLcode code;
  248. bool doread;
  249. doread = (connssl->connecting_state != ssl_connect_2_writing) ? TRUE : FALSE;
  250. infof(data, "schannel: SSL/TLS connection with %s port %hu (step 2/3)\n",
  251. conn->host.name, conn->remote_port);
  252. /* buffer to store previously received and encrypted data */
  253. if(connssl->encdata_buffer == NULL) {
  254. connssl->encdata_offset = 0;
  255. connssl->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  256. connssl->encdata_buffer = malloc(connssl->encdata_length);
  257. if(connssl->encdata_buffer == NULL) {
  258. failf(data, "schannel: unable to allocate memory");
  259. return CURLE_OUT_OF_MEMORY;
  260. }
  261. }
  262. /* if we need a bigger buffer to read a full message, increase buffer now */
  263. if(connssl->encdata_length - connssl->encdata_offset <
  264. CURL_SCHANNEL_BUFFER_FREE_SIZE) {
  265. /* increase internal encrypted data buffer */
  266. connssl->encdata_length *= CURL_SCHANNEL_BUFFER_STEP_FACTOR;
  267. connssl->encdata_buffer = realloc(connssl->encdata_buffer,
  268. connssl->encdata_length);
  269. if(connssl->encdata_buffer == NULL) {
  270. failf(data, "schannel: unable to re-allocate memory");
  271. return CURLE_OUT_OF_MEMORY;
  272. }
  273. }
  274. for(;;) {
  275. if(doread) {
  276. /* read encrypted handshake data from socket */
  277. code = Curl_read_plain(conn->sock[sockindex],
  278. (char *) (connssl->encdata_buffer + connssl->encdata_offset),
  279. connssl->encdata_length - connssl->encdata_offset,
  280. &nread);
  281. if(code == CURLE_AGAIN) {
  282. if(connssl->connecting_state != ssl_connect_2_writing)
  283. connssl->connecting_state = ssl_connect_2_reading;
  284. infof(data, "schannel: failed to receive handshake, "
  285. "need more data\n");
  286. return CURLE_OK;
  287. }
  288. else if((code != CURLE_OK) || (nread == 0)) {
  289. failf(data, "schannel: failed to receive handshake, "
  290. "SSL/TLS connection failed");
  291. return CURLE_SSL_CONNECT_ERROR;
  292. }
  293. /* increase encrypted data buffer offset */
  294. connssl->encdata_offset += nread;
  295. }
  296. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  297. connssl->encdata_offset, connssl->encdata_length);
  298. /* setup input buffers */
  299. InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(connssl->encdata_offset),
  300. curlx_uztoul(connssl->encdata_offset));
  301. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  302. InitSecBufferDesc(&inbuf_desc, inbuf, 2);
  303. /* setup output buffers */
  304. InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0);
  305. InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0);
  306. InitSecBufferDesc(&outbuf_desc, outbuf, 2);
  307. if(inbuf[0].pvBuffer == NULL) {
  308. failf(data, "schannel: unable to allocate memory");
  309. return CURLE_OUT_OF_MEMORY;
  310. }
  311. /* copy received handshake data into input buffer */
  312. memcpy(inbuf[0].pvBuffer, connssl->encdata_buffer,
  313. connssl->encdata_offset);
  314. host_name = Curl_convert_UTF8_to_tchar(conn->host.name);
  315. if(!host_name)
  316. return CURLE_OUT_OF_MEMORY;
  317. /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx */
  318. sspi_status = s_pSecFn->InitializeSecurityContext(
  319. &connssl->cred->cred_handle, &connssl->ctxt->ctxt_handle,
  320. host_name, connssl->req_flags, 0, 0, &inbuf_desc, 0, NULL,
  321. &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
  322. Curl_unicodefree(host_name);
  323. /* free buffer for received handshake data */
  324. Curl_safefree(inbuf[0].pvBuffer);
  325. /* check if the handshake was incomplete */
  326. if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  327. connssl->connecting_state = ssl_connect_2_reading;
  328. infof(data, "schannel: received incomplete message, need more data\n");
  329. return CURLE_OK;
  330. }
  331. /* check if the handshake needs to be continued */
  332. if(sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) {
  333. for(i = 0; i < 2; i++) {
  334. /* search for handshake tokens that need to be send */
  335. if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) {
  336. infof(data, "schannel: sending next handshake data: "
  337. "sending %lu bytes...\n", outbuf[i].cbBuffer);
  338. /* send handshake token to server */
  339. code = Curl_write_plain(conn, conn->sock[sockindex],
  340. outbuf[i].pvBuffer, outbuf[i].cbBuffer,
  341. &written);
  342. if((code != CURLE_OK) || (outbuf[i].cbBuffer != (size_t)written)) {
  343. failf(data, "schannel: failed to send next handshake data: "
  344. "sent %zd of %lu bytes", written, outbuf[i].cbBuffer);
  345. return CURLE_SSL_CONNECT_ERROR;
  346. }
  347. }
  348. /* free obsolete buffer */
  349. if(outbuf[i].pvBuffer != NULL) {
  350. s_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer);
  351. }
  352. }
  353. }
  354. else {
  355. if(sspi_status == SEC_E_WRONG_PRINCIPAL)
  356. failf(data, "schannel: SNI or certificate check failed: %s",
  357. Curl_sspi_strerror(conn, sspi_status));
  358. else
  359. failf(data, "schannel: next InitializeSecurityContext failed: %s",
  360. Curl_sspi_strerror(conn, sspi_status));
  361. return CURLE_SSL_CONNECT_ERROR;
  362. }
  363. /* check if there was additional remaining encrypted data */
  364. if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) {
  365. infof(data, "schannel: encrypted data length: %lu\n", inbuf[1].cbBuffer);
  366. /*
  367. There are two cases where we could be getting extra data here:
  368. 1) If we're renegotiating a connection and the handshake is already
  369. complete (from the server perspective), it can encrypted app data
  370. (not handshake data) in an extra buffer at this point.
  371. 2) (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a
  372. connection and this extra data is part of the handshake.
  373. We should process the data immediately; waiting for the socket to
  374. be ready may fail since the server is done sending handshake data.
  375. */
  376. /* check if the remaining data is less than the total amount
  377. and therefore begins after the already processed data */
  378. if(connssl->encdata_offset > inbuf[1].cbBuffer) {
  379. memmove(connssl->encdata_buffer,
  380. (connssl->encdata_buffer + connssl->encdata_offset) -
  381. inbuf[1].cbBuffer, inbuf[1].cbBuffer);
  382. connssl->encdata_offset = inbuf[1].cbBuffer;
  383. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  384. doread = FALSE;
  385. continue;
  386. }
  387. }
  388. }
  389. else {
  390. connssl->encdata_offset = 0;
  391. }
  392. break;
  393. }
  394. /* check if the handshake needs to be continued */
  395. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  396. connssl->connecting_state = ssl_connect_2_reading;
  397. return CURLE_OK;
  398. }
  399. /* check if the handshake is complete */
  400. if(sspi_status == SEC_E_OK) {
  401. connssl->connecting_state = ssl_connect_3;
  402. infof(data, "schannel: SSL/TLS handshake complete\n");
  403. }
  404. #ifdef _WIN32_WCE
  405. /* Windows CE doesn't do any server certificate validation.
  406. We have to do it manually. */
  407. if(data->set.ssl.verifypeer)
  408. return verify_certificate(conn, sockindex);
  409. #endif
  410. return CURLE_OK;
  411. }
  412. static CURLcode
  413. schannel_connect_step3(struct connectdata *conn, int sockindex)
  414. {
  415. CURLcode retcode = CURLE_OK;
  416. struct SessionHandle *data = conn->data;
  417. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  418. struct curl_schannel_cred *old_cred = NULL;
  419. int incache;
  420. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  421. infof(data, "schannel: SSL/TLS connection with %s port %hu (step 3/3)\n",
  422. conn->host.name, conn->remote_port);
  423. /* check if the required context attributes are met */
  424. if(connssl->ret_flags != connssl->req_flags) {
  425. if(!(connssl->ret_flags & ISC_RET_SEQUENCE_DETECT))
  426. failf(data, "schannel: failed to setup sequence detection");
  427. if(!(connssl->ret_flags & ISC_RET_REPLAY_DETECT))
  428. failf(data, "schannel: failed to setup replay detection");
  429. if(!(connssl->ret_flags & ISC_RET_CONFIDENTIALITY))
  430. failf(data, "schannel: failed to setup confidentiality");
  431. if(!(connssl->ret_flags & ISC_RET_EXTENDED_ERROR))
  432. failf(data, "schannel: failed to setup extended errors");
  433. if(!(connssl->ret_flags & ISC_RET_ALLOCATED_MEMORY))
  434. failf(data, "schannel: failed to setup memory allocation");
  435. if(!(connssl->ret_flags & ISC_RET_STREAM))
  436. failf(data, "schannel: failed to setup stream orientation");
  437. return CURLE_SSL_CONNECT_ERROR;
  438. }
  439. /* increment the reference counter of the credential/session handle */
  440. if(connssl->cred && connssl->ctxt) {
  441. connssl->cred->refcount++;
  442. infof(data, "schannel: incremented credential handle refcount = %d\n",
  443. connssl->cred->refcount);
  444. }
  445. /* save the current session data for possible re-use */
  446. incache = !(Curl_ssl_getsessionid(conn, (void**)&old_cred, NULL));
  447. if(incache) {
  448. if(old_cred != connssl->cred) {
  449. infof(data, "schannel: old credential handle is stale, removing\n");
  450. Curl_ssl_delsessionid(conn, (void*)old_cred);
  451. incache = FALSE;
  452. }
  453. }
  454. if(!incache) {
  455. retcode = Curl_ssl_addsessionid(conn, (void*)connssl->cred,
  456. sizeof(struct curl_schannel_cred));
  457. if(retcode) {
  458. failf(data, "schannel: failed to store credential handle");
  459. return retcode;
  460. }
  461. else {
  462. infof(data, "schannel: stored credential handle in session cache\n");
  463. }
  464. }
  465. connssl->connecting_state = ssl_connect_done;
  466. return CURLE_OK;
  467. }
  468. static CURLcode
  469. schannel_connect_common(struct connectdata *conn, int sockindex,
  470. bool nonblocking, bool *done)
  471. {
  472. CURLcode retcode;
  473. struct SessionHandle *data = conn->data;
  474. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  475. curl_socket_t sockfd = conn->sock[sockindex];
  476. long timeout_ms;
  477. int what;
  478. /* check if the connection has already been established */
  479. if(ssl_connection_complete == connssl->state) {
  480. *done = TRUE;
  481. return CURLE_OK;
  482. }
  483. if(ssl_connect_1 == connssl->connecting_state) {
  484. /* check out how much more time we're allowed */
  485. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  486. if(timeout_ms < 0) {
  487. /* no need to continue if time already is up */
  488. failf(data, "SSL/TLS connection timeout");
  489. return CURLE_OPERATION_TIMEDOUT;
  490. }
  491. retcode = schannel_connect_step1(conn, sockindex);
  492. if(retcode)
  493. return retcode;
  494. }
  495. while(ssl_connect_2 == connssl->connecting_state ||
  496. ssl_connect_2_reading == connssl->connecting_state ||
  497. ssl_connect_2_writing == connssl->connecting_state) {
  498. /* check out how much more time we're allowed */
  499. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  500. if(timeout_ms < 0) {
  501. /* no need to continue if time already is up */
  502. failf(data, "SSL/TLS connection timeout");
  503. return CURLE_OPERATION_TIMEDOUT;
  504. }
  505. /* if ssl is expecting something, check if it's available. */
  506. if(connssl->connecting_state == ssl_connect_2_reading
  507. || connssl->connecting_state == ssl_connect_2_writing) {
  508. curl_socket_t writefd = ssl_connect_2_writing ==
  509. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  510. curl_socket_t readfd = ssl_connect_2_reading ==
  511. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  512. what = Curl_socket_ready(readfd, writefd, nonblocking ? 0 : timeout_ms);
  513. if(what < 0) {
  514. /* fatal error */
  515. failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO);
  516. return CURLE_SSL_CONNECT_ERROR;
  517. }
  518. else if(0 == what) {
  519. if(nonblocking) {
  520. *done = FALSE;
  521. return CURLE_OK;
  522. }
  523. else {
  524. /* timeout */
  525. failf(data, "SSL/TLS connection timeout");
  526. return CURLE_OPERATION_TIMEDOUT;
  527. }
  528. }
  529. /* socket is readable or writable */
  530. }
  531. /* Run transaction, and return to the caller if it failed or if
  532. * this connection is part of a multi handle and this loop would
  533. * execute again. This permits the owner of a multi handle to
  534. * abort a connection attempt before step2 has completed while
  535. * ensuring that a client using select() or epoll() will always
  536. * have a valid fdset to wait on.
  537. */
  538. retcode = schannel_connect_step2(conn, sockindex);
  539. if(retcode || (nonblocking &&
  540. (ssl_connect_2 == connssl->connecting_state ||
  541. ssl_connect_2_reading == connssl->connecting_state ||
  542. ssl_connect_2_writing == connssl->connecting_state)))
  543. return retcode;
  544. } /* repeat step2 until all transactions are done. */
  545. if(ssl_connect_3 == connssl->connecting_state) {
  546. retcode = schannel_connect_step3(conn, sockindex);
  547. if(retcode)
  548. return retcode;
  549. }
  550. if(ssl_connect_done == connssl->connecting_state) {
  551. connssl->state = ssl_connection_complete;
  552. conn->recv[sockindex] = schannel_recv;
  553. conn->send[sockindex] = schannel_send;
  554. *done = TRUE;
  555. }
  556. else
  557. *done = FALSE;
  558. /* reset our connection state machine */
  559. connssl->connecting_state = ssl_connect_1;
  560. return CURLE_OK;
  561. }
  562. static ssize_t
  563. schannel_send(struct connectdata *conn, int sockindex,
  564. const void *buf, size_t len, CURLcode *err)
  565. {
  566. ssize_t written = -1;
  567. size_t data_len = 0;
  568. unsigned char *data = NULL;
  569. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  570. SecBuffer outbuf[4];
  571. SecBufferDesc outbuf_desc;
  572. SECURITY_STATUS sspi_status = SEC_E_OK;
  573. CURLcode code;
  574. /* check if the maximum stream sizes were queried */
  575. if(connssl->stream_sizes.cbMaximumMessage == 0) {
  576. sspi_status = s_pSecFn->QueryContextAttributes(
  577. &connssl->ctxt->ctxt_handle,
  578. SECPKG_ATTR_STREAM_SIZES,
  579. &connssl->stream_sizes);
  580. if(sspi_status != SEC_E_OK) {
  581. *err = CURLE_SEND_ERROR;
  582. return -1;
  583. }
  584. }
  585. /* check if the buffer is longer than the maximum message length */
  586. if(len > connssl->stream_sizes.cbMaximumMessage) {
  587. *err = CURLE_SEND_ERROR;
  588. return -1;
  589. }
  590. /* calculate the complete message length and allocate a buffer for it */
  591. data_len = connssl->stream_sizes.cbHeader + len +
  592. connssl->stream_sizes.cbTrailer;
  593. data = (unsigned char*) malloc(data_len);
  594. if(data == NULL) {
  595. *err = CURLE_OUT_OF_MEMORY;
  596. return -1;
  597. }
  598. /* setup output buffers (header, data, trailer, empty) */
  599. InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
  600. data, connssl->stream_sizes.cbHeader);
  601. InitSecBuffer(&outbuf[1], SECBUFFER_DATA,
  602. data + connssl->stream_sizes.cbHeader, curlx_uztoul(len));
  603. InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
  604. data + connssl->stream_sizes.cbHeader + len,
  605. connssl->stream_sizes.cbTrailer);
  606. InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
  607. InitSecBufferDesc(&outbuf_desc, outbuf, 4);
  608. /* copy data into output buffer */
  609. memcpy(outbuf[1].pvBuffer, buf, len);
  610. /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */
  611. sspi_status = s_pSecFn->EncryptMessage(&connssl->ctxt->ctxt_handle, 0,
  612. &outbuf_desc, 0);
  613. /* check if the message was encrypted */
  614. if(sspi_status == SEC_E_OK) {
  615. written = 0;
  616. /* send the encrypted message including header, data and trailer */
  617. len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer;
  618. /*
  619. It's important to send the full message which includes the header,
  620. encrypted payload, and trailer. Until the client receives all the
  621. data a coherent message has not been delivered and the client
  622. can't read any of it.
  623. If we wanted to buffer the unwritten encrypted bytes, we would
  624. tell the client that all data it has requested to be sent has been
  625. sent. The unwritten encrypted bytes would be the first bytes to
  626. send on the next invocation.
  627. Here's the catch with this - if we tell the client that all the
  628. bytes have been sent, will the client call this method again to
  629. send the buffered data? Looking at who calls this function, it
  630. seems the answer is NO.
  631. */
  632. /* send entire message or fail */
  633. while(len > (size_t)written) {
  634. ssize_t this_write;
  635. long timeleft;
  636. int what;
  637. this_write = 0;
  638. timeleft = Curl_timeleft(conn->data, NULL, TRUE);
  639. if(timeleft < 0) {
  640. /* we already got the timeout */
  641. failf(conn->data, "schannel: timed out sending data "
  642. "(bytes sent: %zd)", written);
  643. *err = CURLE_OPERATION_TIMEDOUT;
  644. written = -1;
  645. break;
  646. }
  647. what = Curl_socket_ready(CURL_SOCKET_BAD, conn->sock[sockindex],
  648. timeleft);
  649. if(what < 0) {
  650. /* fatal error */
  651. failf(conn->data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  652. *err = CURLE_SEND_ERROR;
  653. written = -1;
  654. break;
  655. }
  656. else if(0 == what) {
  657. failf(conn->data, "schannel: timed out sending data "
  658. "(bytes sent: %zd)", written);
  659. *err = CURLE_OPERATION_TIMEDOUT;
  660. written = -1;
  661. break;
  662. }
  663. /* socket is writable */
  664. code = Curl_write_plain(conn, conn->sock[sockindex], data + written,
  665. len - written, &this_write);
  666. if(code == CURLE_AGAIN)
  667. continue;
  668. else if(code != CURLE_OK) {
  669. *err = code;
  670. written = -1;
  671. break;
  672. }
  673. written += this_write;
  674. }
  675. }
  676. else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) {
  677. *err = CURLE_OUT_OF_MEMORY;
  678. }
  679. else{
  680. *err = CURLE_SEND_ERROR;
  681. }
  682. Curl_safefree(data);
  683. if(len == (size_t)written)
  684. /* Encrypted message including header, data and trailer entirely sent.
  685. The return value is the number of unencrypted bytes that were sent. */
  686. written = outbuf[1].cbBuffer;
  687. return written;
  688. }
  689. static ssize_t
  690. schannel_recv(struct connectdata *conn, int sockindex,
  691. char *buf, size_t len, CURLcode *err)
  692. {
  693. size_t size = 0;
  694. ssize_t nread = 0, ret = -1;
  695. CURLcode retcode;
  696. struct SessionHandle *data = conn->data;
  697. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  698. bool done = FALSE;
  699. SecBuffer inbuf[4];
  700. SecBufferDesc inbuf_desc;
  701. SECURITY_STATUS sspi_status = SEC_E_OK;
  702. infof(data, "schannel: client wants to read %zu bytes\n", len);
  703. *err = CURLE_OK;
  704. /* buffer to store previously received and decrypted data */
  705. if(connssl->decdata_buffer == NULL) {
  706. connssl->decdata_offset = 0;
  707. connssl->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  708. connssl->decdata_buffer = malloc(connssl->decdata_length);
  709. if(connssl->decdata_buffer == NULL) {
  710. failf(data, "schannel: unable to allocate memory");
  711. *err = CURLE_OUT_OF_MEMORY;
  712. return -1;
  713. }
  714. }
  715. /* increase buffer in order to fit the requested amount of data */
  716. while(connssl->encdata_length - connssl->encdata_offset <
  717. CURL_SCHANNEL_BUFFER_FREE_SIZE || connssl->encdata_length < len) {
  718. /* increase internal encrypted data buffer */
  719. connssl->encdata_length *= CURL_SCHANNEL_BUFFER_STEP_FACTOR;
  720. connssl->encdata_buffer = realloc(connssl->encdata_buffer,
  721. connssl->encdata_length);
  722. if(connssl->encdata_buffer == NULL) {
  723. failf(data, "schannel: unable to re-allocate memory");
  724. *err = CURLE_OUT_OF_MEMORY;
  725. return -1;
  726. }
  727. }
  728. /* read encrypted data from socket */
  729. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  730. connssl->encdata_offset, connssl->encdata_length);
  731. size = connssl->encdata_length - connssl->encdata_offset;
  732. if(size > 0) {
  733. *err = Curl_read_plain(conn->sock[sockindex],
  734. (char *) (connssl->encdata_buffer + connssl->encdata_offset),
  735. size, &nread);
  736. /* check for received data */
  737. if(*err != CURLE_OK)
  738. ret = -1;
  739. else {
  740. if(nread > 0)
  741. /* increase encrypted data buffer offset */
  742. connssl->encdata_offset += nread;
  743. ret = nread;
  744. }
  745. infof(data, "schannel: encrypted data got %zd\n", ret);
  746. }
  747. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  748. connssl->encdata_offset, connssl->encdata_length);
  749. /* check if we still have some data in our buffers */
  750. while(connssl->encdata_offset > 0 && sspi_status == SEC_E_OK &&
  751. connssl->decdata_offset < len) {
  752. /* prepare data buffer for DecryptMessage call */
  753. InitSecBuffer(&inbuf[0], SECBUFFER_DATA, connssl->encdata_buffer,
  754. curlx_uztoul(connssl->encdata_offset));
  755. /* we need 3 more empty input buffers for possible output */
  756. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  757. InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0);
  758. InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0);
  759. InitSecBufferDesc(&inbuf_desc, inbuf, 4);
  760. /* http://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx */
  761. sspi_status = s_pSecFn->DecryptMessage(&connssl->ctxt->ctxt_handle,
  762. &inbuf_desc, 0, NULL);
  763. /* check if we need more data */
  764. if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  765. infof(data, "schannel: failed to decrypt data, need more data\n");
  766. *err = CURLE_AGAIN;
  767. return -1;
  768. }
  769. /* check if everything went fine (server may want to renegotiate
  770. context) */
  771. if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE ||
  772. sspi_status == SEC_I_CONTEXT_EXPIRED) {
  773. /* check for successfully decrypted data */
  774. if(inbuf[1].BufferType == SECBUFFER_DATA) {
  775. infof(data, "schannel: decrypted data length: %lu\n",
  776. inbuf[1].cbBuffer);
  777. /* increase buffer in order to fit the received amount of data */
  778. size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ?
  779. inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE;
  780. while(connssl->decdata_length - connssl->decdata_offset < size ||
  781. connssl->decdata_length < len) {
  782. /* increase internal decrypted data buffer */
  783. connssl->decdata_length *= CURL_SCHANNEL_BUFFER_STEP_FACTOR;
  784. connssl->decdata_buffer = realloc(connssl->decdata_buffer,
  785. connssl->decdata_length);
  786. if(connssl->decdata_buffer == NULL) {
  787. failf(data, "schannel: unable to re-allocate memory");
  788. *err = CURLE_OUT_OF_MEMORY;
  789. return -1;
  790. }
  791. }
  792. /* copy decrypted data to internal buffer */
  793. size = inbuf[1].cbBuffer;
  794. if(size > 0) {
  795. memcpy(connssl->decdata_buffer + connssl->decdata_offset,
  796. inbuf[1].pvBuffer, size);
  797. connssl->decdata_offset += size;
  798. }
  799. infof(data, "schannel: decrypted data added: %zu\n", size);
  800. infof(data, "schannel: decrypted data cached: offset %zu length %zu\n",
  801. connssl->decdata_offset, connssl->decdata_length);
  802. }
  803. /* check for remaining encrypted data */
  804. if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) {
  805. infof(data, "schannel: encrypted data length: %lu\n",
  806. inbuf[3].cbBuffer);
  807. /* check if the remaining data is less than the total amount
  808. * and therefore begins after the already processed data
  809. */
  810. if(connssl->encdata_offset > inbuf[3].cbBuffer) {
  811. /* move remaining encrypted data forward to the beginning of
  812. buffer */
  813. memmove(connssl->encdata_buffer,
  814. (connssl->encdata_buffer + connssl->encdata_offset) -
  815. inbuf[3].cbBuffer, inbuf[3].cbBuffer);
  816. connssl->encdata_offset = inbuf[3].cbBuffer;
  817. }
  818. infof(data, "schannel: encrypted data cached: offset %zu length %zu\n",
  819. connssl->encdata_offset, connssl->encdata_length);
  820. }
  821. else{
  822. /* reset encrypted buffer offset, because there is no data remaining */
  823. connssl->encdata_offset = 0;
  824. }
  825. }
  826. /* check if server wants to renegotiate the connection context */
  827. if(sspi_status == SEC_I_RENEGOTIATE) {
  828. infof(data, "schannel: remote party requests SSL/TLS renegotiation\n");
  829. /* begin renegotiation */
  830. infof(data, "schannel: renegotiating SSL/TLS connection\n");
  831. connssl->state = ssl_connection_negotiating;
  832. connssl->connecting_state = ssl_connect_2_writing;
  833. retcode = schannel_connect_common(conn, sockindex, FALSE, &done);
  834. if(retcode)
  835. *err = retcode;
  836. else {
  837. infof(data, "schannel: SSL/TLS connection renegotiated\n");
  838. /* now retry receiving data */
  839. return schannel_recv(conn, sockindex, buf, len, err);
  840. }
  841. }
  842. }
  843. infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n",
  844. connssl->decdata_offset, connssl->decdata_length);
  845. /* copy requested decrypted data to supplied buffer */
  846. size = len < connssl->decdata_offset ? len : connssl->decdata_offset;
  847. if(size > 0) {
  848. memcpy(buf, connssl->decdata_buffer, size);
  849. ret = size;
  850. /* move remaining decrypted data forward to the beginning of buffer */
  851. memmove(connssl->decdata_buffer, connssl->decdata_buffer + size,
  852. connssl->decdata_offset - size);
  853. connssl->decdata_offset -= size;
  854. infof(data, "schannel: decrypted data returned %zd\n", size);
  855. infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n",
  856. connssl->decdata_offset, connssl->decdata_length);
  857. }
  858. /* check if the server closed the connection */
  859. if(ret <= 0 && ( /* special check for Windows 2000 Professional */
  860. sspi_status == SEC_I_CONTEXT_EXPIRED || (sspi_status == SEC_E_OK &&
  861. connssl->encdata_offset > 0 && connssl->encdata_buffer[0] == 0x15))) {
  862. infof(data, "schannel: server closed the connection\n");
  863. *err = CURLE_OK;
  864. return 0;
  865. }
  866. /* check if something went wrong and we need to return an error */
  867. if(ret < 0 && sspi_status != SEC_E_OK) {
  868. infof(data, "schannel: failed to read data from server: %s\n",
  869. Curl_sspi_strerror(conn, sspi_status));
  870. *err = CURLE_RECV_ERROR;
  871. return -1;
  872. }
  873. return ret;
  874. }
  875. CURLcode
  876. Curl_schannel_connect_nonblocking(struct connectdata *conn, int sockindex,
  877. bool *done)
  878. {
  879. return schannel_connect_common(conn, sockindex, TRUE, done);
  880. }
  881. CURLcode
  882. Curl_schannel_connect(struct connectdata *conn, int sockindex)
  883. {
  884. CURLcode retcode;
  885. bool done = FALSE;
  886. retcode = schannel_connect_common(conn, sockindex, FALSE, &done);
  887. if(retcode)
  888. return retcode;
  889. DEBUGASSERT(done);
  890. return CURLE_OK;
  891. }
  892. bool Curl_schannel_data_pending(const struct connectdata *conn, int sockindex)
  893. {
  894. const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  895. if(connssl->use) /* SSL/TLS is in use */
  896. return (connssl->encdata_offset > 0 ||
  897. connssl->decdata_offset > 0 ) ? TRUE : FALSE;
  898. else
  899. return FALSE;
  900. }
  901. void Curl_schannel_close(struct connectdata *conn, int sockindex)
  902. {
  903. if(conn->ssl[sockindex].use)
  904. /* if the SSL/TLS channel hasn't been shut down yet, do that now. */
  905. Curl_ssl_shutdown(conn, sockindex);
  906. }
  907. int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
  908. {
  909. /* See http://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx
  910. * Shutting Down an Schannel Connection
  911. */
  912. struct SessionHandle *data = conn->data;
  913. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  914. infof(data, "schannel: shutting down SSL/TLS connection with %s port %hu\n",
  915. conn->host.name, conn->remote_port);
  916. if(connssl->cred && connssl->ctxt) {
  917. SecBufferDesc BuffDesc;
  918. SecBuffer Buffer;
  919. SECURITY_STATUS sspi_status;
  920. SecBuffer outbuf;
  921. SecBufferDesc outbuf_desc;
  922. CURLcode code;
  923. TCHAR *host_name;
  924. DWORD dwshut = SCHANNEL_SHUTDOWN;
  925. InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
  926. InitSecBufferDesc(&BuffDesc, &Buffer, 1);
  927. sspi_status = s_pSecFn->ApplyControlToken(&connssl->ctxt->ctxt_handle,
  928. &BuffDesc);
  929. if(sspi_status != SEC_E_OK)
  930. failf(data, "schannel: ApplyControlToken failure: %s",
  931. Curl_sspi_strerror(conn, sspi_status));
  932. host_name = Curl_convert_UTF8_to_tchar(conn->host.name);
  933. if(!host_name)
  934. return CURLE_OUT_OF_MEMORY;
  935. /* setup output buffer */
  936. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  937. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  938. sspi_status = s_pSecFn->InitializeSecurityContext(
  939. &connssl->cred->cred_handle,
  940. &connssl->ctxt->ctxt_handle,
  941. host_name,
  942. connssl->req_flags,
  943. 0,
  944. 0,
  945. NULL,
  946. 0,
  947. &connssl->ctxt->ctxt_handle,
  948. &outbuf_desc,
  949. &connssl->ret_flags,
  950. &connssl->ctxt->time_stamp);
  951. Curl_unicodefree(host_name);
  952. if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) {
  953. /* send close message which is in output buffer */
  954. ssize_t written;
  955. code = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer,
  956. outbuf.cbBuffer, &written);
  957. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  958. if((code != CURLE_OK) || (outbuf.cbBuffer != (size_t)written)) {
  959. infof(data, "schannel: failed to send close msg: %s"
  960. " (bytes written: %zd)\n", curl_easy_strerror(code), written);
  961. }
  962. }
  963. /* free SSPI Schannel API security context handle */
  964. if(connssl->ctxt) {
  965. s_pSecFn->DeleteSecurityContext(&connssl->ctxt->ctxt_handle);
  966. Curl_safefree(connssl->ctxt);
  967. }
  968. /* decrement the reference counter of the credential/session handle */
  969. if(connssl->cred && connssl->cred->refcount > 0) {
  970. connssl->cred->refcount--;
  971. infof(data, "schannel: decremented credential handle refcount = %d\n",
  972. connssl->cred->refcount);
  973. }
  974. }
  975. /* free internal buffer for received encrypted data */
  976. if(connssl->encdata_buffer != NULL) {
  977. Curl_safefree(connssl->encdata_buffer);
  978. connssl->encdata_length = 0;
  979. connssl->encdata_offset = 0;
  980. }
  981. /* free internal buffer for received decrypted data */
  982. if(connssl->decdata_buffer != NULL) {
  983. Curl_safefree(connssl->decdata_buffer);
  984. connssl->decdata_length = 0;
  985. connssl->decdata_offset = 0;
  986. }
  987. return CURLE_OK;
  988. }
  989. void Curl_schannel_session_free(void *ptr)
  990. {
  991. struct curl_schannel_cred *cred = ptr;
  992. if(cred && cred->refcount == 0) {
  993. s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
  994. Curl_safefree(cred);
  995. }
  996. }
  997. int Curl_schannel_init(void)
  998. {
  999. return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0);
  1000. }
  1001. void Curl_schannel_cleanup(void)
  1002. {
  1003. Curl_sspi_global_cleanup();
  1004. }
  1005. size_t Curl_schannel_version(char *buffer, size_t size)
  1006. {
  1007. size = snprintf(buffer, size, "WinSSL");
  1008. return size;
  1009. }
  1010. #ifdef _WIN32_WCE
  1011. static CURLcode verify_certificate(struct connectdata *conn, int sockindex)
  1012. {
  1013. SECURITY_STATUS status;
  1014. struct SessionHandle *data = conn->data;
  1015. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1016. CURLcode result = CURLE_OK;
  1017. CERT_CONTEXT *pCertContextServer = NULL;
  1018. const CERT_CHAIN_CONTEXT *pChainContext = NULL;
  1019. status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
  1020. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  1021. &pCertContextServer);
  1022. if((status != SEC_E_OK) || (pCertContextServer == NULL)) {
  1023. failf(data, "schannel: Failed to read remote certificate context: %s",
  1024. Curl_sspi_strerror(conn, status));
  1025. result = CURLE_PEER_FAILED_VERIFICATION;
  1026. }
  1027. if(result == CURLE_OK) {
  1028. CERT_CHAIN_PARA ChainPara;
  1029. memset(&ChainPara, 0, sizeof(ChainPara));
  1030. ChainPara.cbSize = sizeof(ChainPara);
  1031. if(!CertGetCertificateChain(NULL,
  1032. pCertContextServer,
  1033. NULL,
  1034. pCertContextServer->hCertStore,
  1035. &ChainPara,
  1036. 0,
  1037. NULL,
  1038. &pChainContext)) {
  1039. failf(data, "schannel: CertGetCertificateChain failed: %s",
  1040. Curl_sspi_strerror(conn, GetLastError()));
  1041. pChainContext = NULL;
  1042. result = CURLE_PEER_FAILED_VERIFICATION;
  1043. }
  1044. if(result == CURLE_OK) {
  1045. CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0];
  1046. DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED|
  1047. CERT_TRUST_REVOCATION_STATUS_UNKNOWN);
  1048. dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus;
  1049. if(dwTrustErrorMask) {
  1050. if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN)
  1051. failf(data, "schannel: CertGetCertificateChain trust error"
  1052. " CERT_TRUST_IS_PARTIAL_CHAIN");
  1053. if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT)
  1054. failf(data, "schannel: CertGetCertificateChain trust error"
  1055. " CERT_TRUST_IS_UNTRUSTED_ROOT");
  1056. if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID)
  1057. failf(data, "schannel: CertGetCertificateChain trust error"
  1058. " CERT_TRUST_IS_NOT_TIME_VALID");
  1059. failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x",
  1060. dwTrustErrorMask);
  1061. result = CURLE_PEER_FAILED_VERIFICATION;
  1062. }
  1063. }
  1064. }
  1065. if(result == CURLE_OK) {
  1066. if(data->set.ssl.verifyhost == 1) {
  1067. infof(data, "warning: ignoring unsupported value (1) ssl.verifyhost\n");
  1068. }
  1069. else if(data->set.ssl.verifyhost == 2) {
  1070. TCHAR cert_hostname_buff[128];
  1071. xcharp_u hostname;
  1072. xcharp_u cert_hostname;
  1073. DWORD len;
  1074. cert_hostname.const_tchar_ptr = cert_hostname_buff;
  1075. hostname.tchar_ptr = Curl_convert_UTF8_to_tchar(conn->host.name);
  1076. len = CertGetNameString(pCertContextServer,
  1077. CERT_NAME_DNS_TYPE,
  1078. 0,
  1079. NULL,
  1080. cert_hostname.tchar_ptr,
  1081. 128);
  1082. if(len > 0 && *cert_hostname.tchar_ptr == '*') {
  1083. /* this is a wildcard cert. try matching the last len - 1 chars */
  1084. int hostname_len = strlen(conn->host.name);
  1085. cert_hostname.tchar_ptr++;
  1086. if(_tcsicmp(cert_hostname.const_tchar_ptr,
  1087. hostname.const_tchar_ptr + hostname_len - len + 2) != 0)
  1088. result = CURLE_PEER_FAILED_VERIFICATION;
  1089. }
  1090. else if(len == 0 || _tcsicmp(hostname.const_tchar_ptr,
  1091. cert_hostname.const_tchar_ptr) != 0) {
  1092. result = CURLE_PEER_FAILED_VERIFICATION;
  1093. }
  1094. if(result == CURLE_PEER_FAILED_VERIFICATION) {
  1095. char *_cert_hostname;
  1096. _cert_hostname = Curl_convert_tchar_to_UTF8(cert_hostname.tchar_ptr);
  1097. failf(data, "schannel: CertGetNameString() certificate hostname "
  1098. "(%s) did not match connection (%s)",
  1099. _cert_hostname, conn->host.name);
  1100. Curl_unicodefree(_cert_hostname);
  1101. }
  1102. Curl_unicodefree(hostname.tchar_ptr);
  1103. }
  1104. }
  1105. if(pChainContext)
  1106. CertFreeCertificateChain(pChainContext);
  1107. if(pCertContextServer)
  1108. CertFreeCertificateContext(pCertContextServer);
  1109. return result;
  1110. }
  1111. #endif /* _WIN32_WCE */
  1112. #endif /* USE_SCHANNEL */