schannel.c 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 2012 - 2016, Marc Hoersken, <[email protected]>
  9. * Copyright (C) 2012, Mark Salisbury, <[email protected]>
  10. * Copyright (C) 2012 - 2016, Daniel Stenberg, <[email protected]>, 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 https://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 vtls.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, <[email protected]>
  32. *
  33. * Based upon the CyaSSL implementation in cyassl.c and cyassl.h:
  34. * Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al.
  35. *
  36. * Thanks for code and inspiration!
  37. */
  38. #include "curl_setup.h"
  39. #ifdef USE_SCHANNEL
  40. #ifndef USE_WINDOWS_SSPI
  41. # error "Can't compile SCHANNEL support without SSPI."
  42. #endif
  43. #include "curl_sspi.h"
  44. #include "schannel.h"
  45. #include "vtls.h"
  46. #include "sendf.h"
  47. #include "connect.h" /* for the connect timeout */
  48. #include "strerror.h"
  49. #include "select.h" /* for the socket readyness */
  50. #include "inet_pton.h" /* for IP addr SNI check */
  51. #include "curl_multibyte.h"
  52. #include "warnless.h"
  53. #include "x509asn1.h"
  54. #include "curl_printf.h"
  55. #include "system_win32.h"
  56. #include "hostcheck.h"
  57. /* The last #include file should be: */
  58. #include "curl_memory.h"
  59. #include "memdebug.h"
  60. /* ALPN requires version 8.1 of the Windows SDK, which was
  61. shipped with Visual Studio 2013, aka _MSC_VER 1800:
  62. https://technet.microsoft.com/en-us/library/hh831771%28v=ws.11%29.aspx
  63. */
  64. #if defined(_MSC_VER) && (_MSC_VER >= 1800) && !defined(_USING_V110_SDK71_)
  65. # define HAS_ALPN 1
  66. #endif
  67. /* Uncomment to force verbose output
  68. * #define infof(x, y, ...) printf(y, __VA_ARGS__)
  69. * #define failf(x, y, ...) printf(y, __VA_ARGS__)
  70. */
  71. static Curl_recv schannel_recv;
  72. static Curl_send schannel_send;
  73. #ifdef _WIN32_WCE
  74. static CURLcode verify_certificate(struct connectdata *conn, int sockindex);
  75. #endif
  76. static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType,
  77. void *BufDataPtr, unsigned long BufByteSize)
  78. {
  79. buffer->cbBuffer = BufByteSize;
  80. buffer->BufferType = BufType;
  81. buffer->pvBuffer = BufDataPtr;
  82. }
  83. static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr,
  84. unsigned long NumArrElem)
  85. {
  86. desc->ulVersion = SECBUFFER_VERSION;
  87. desc->pBuffers = BufArr;
  88. desc->cBuffers = NumArrElem;
  89. }
  90. static CURLcode
  91. schannel_connect_step1(struct connectdata *conn, int sockindex)
  92. {
  93. ssize_t written = -1;
  94. struct Curl_easy *data = conn->data;
  95. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  96. SecBuffer outbuf;
  97. SecBufferDesc outbuf_desc;
  98. SecBuffer inbuf;
  99. SecBufferDesc inbuf_desc;
  100. #ifdef HAS_ALPN
  101. unsigned char alpn_buffer[128];
  102. #endif
  103. SCHANNEL_CRED schannel_cred;
  104. SECURITY_STATUS sspi_status = SEC_E_OK;
  105. struct curl_schannel_cred *old_cred = NULL;
  106. struct in_addr addr;
  107. #ifdef ENABLE_IPV6
  108. struct in6_addr addr6;
  109. #endif
  110. TCHAR *host_name;
  111. CURLcode result;
  112. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  113. conn->host.name;
  114. infof(data, "schannel: SSL/TLS connection with %s port %hu (step 1/3)\n",
  115. hostname, conn->remote_port);
  116. #ifdef HAS_ALPN
  117. /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above.
  118. Also it doesn't seem to be supported for Wine, see curl bug #983. */
  119. connssl->use_alpn = conn->bits.tls_enable_alpn &&
  120. !GetProcAddress(GetModuleHandleA("ntdll"),
  121. "wine_get_version") &&
  122. Curl_verify_windows_version(6, 3, PLATFORM_WINNT,
  123. VERSION_GREATER_THAN_EQUAL);
  124. #else
  125. connssl->use_alpn = false;
  126. #endif
  127. connssl->cred = NULL;
  128. /* check for an existing re-usable credential handle */
  129. if(data->set.general_ssl.sessionid) {
  130. Curl_ssl_sessionid_lock(conn);
  131. if(!Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL, sockindex)) {
  132. connssl->cred = old_cred;
  133. infof(data, "schannel: re-using existing credential handle\n");
  134. /* increment the reference counter of the credential/session handle */
  135. connssl->cred->refcount++;
  136. infof(data, "schannel: incremented credential handle refcount = %d\n",
  137. connssl->cred->refcount);
  138. }
  139. Curl_ssl_sessionid_unlock(conn);
  140. }
  141. if(!connssl->cred) {
  142. /* setup Schannel API options */
  143. memset(&schannel_cred, 0, sizeof(schannel_cred));
  144. schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
  145. if(conn->ssl_config.verifypeer) {
  146. #ifdef _WIN32_WCE
  147. /* certificate validation on CE doesn't seem to work right; we'll
  148. do it following a more manual process. */
  149. schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION |
  150. SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  151. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  152. #else
  153. schannel_cred.dwFlags = SCH_CRED_AUTO_CRED_VALIDATION;
  154. /* TODO s/data->set.ssl.no_revoke/SSL_SET_OPTION(no_revoke)/g */
  155. if(data->set.ssl.no_revoke)
  156. schannel_cred.dwFlags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  157. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  158. else
  159. schannel_cred.dwFlags |= SCH_CRED_REVOCATION_CHECK_CHAIN;
  160. #endif
  161. if(data->set.ssl.no_revoke)
  162. infof(data, "schannel: disabled server certificate revocation "
  163. "checks\n");
  164. else
  165. infof(data, "schannel: checking server certificate revocation\n");
  166. }
  167. else {
  168. schannel_cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION |
  169. SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  170. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  171. infof(data, "schannel: disabled server certificate revocation checks\n");
  172. }
  173. if(!conn->ssl_config.verifyhost) {
  174. schannel_cred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK;
  175. infof(data, "schannel: verifyhost setting prevents Schannel from "
  176. "comparing the supplied target name with the subject "
  177. "names in server certificates. Also disables SNI.\n");
  178. }
  179. switch(conn->ssl_config.version) {
  180. case CURL_SSLVERSION_DEFAULT:
  181. case CURL_SSLVERSION_TLSv1:
  182. schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_0_CLIENT |
  183. SP_PROT_TLS1_1_CLIENT |
  184. SP_PROT_TLS1_2_CLIENT;
  185. break;
  186. case CURL_SSLVERSION_TLSv1_0:
  187. schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_0_CLIENT;
  188. break;
  189. case CURL_SSLVERSION_TLSv1_1:
  190. schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_1_CLIENT;
  191. break;
  192. case CURL_SSLVERSION_TLSv1_2:
  193. schannel_cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT;
  194. break;
  195. case CURL_SSLVERSION_TLSv1_3:
  196. failf(data, "Schannel: TLS 1.3 is not yet supported");
  197. return CURLE_SSL_CONNECT_ERROR;
  198. case CURL_SSLVERSION_SSLv3:
  199. schannel_cred.grbitEnabledProtocols = SP_PROT_SSL3_CLIENT;
  200. break;
  201. case CURL_SSLVERSION_SSLv2:
  202. schannel_cred.grbitEnabledProtocols = SP_PROT_SSL2_CLIENT;
  203. break;
  204. default:
  205. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  206. return CURLE_SSL_CONNECT_ERROR;
  207. }
  208. /* allocate memory for the re-usable credential handle */
  209. connssl->cred = (struct curl_schannel_cred *)
  210. malloc(sizeof(struct curl_schannel_cred));
  211. if(!connssl->cred) {
  212. failf(data, "schannel: unable to allocate memory");
  213. return CURLE_OUT_OF_MEMORY;
  214. }
  215. memset(connssl->cred, 0, sizeof(struct curl_schannel_cred));
  216. connssl->cred->refcount = 1;
  217. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa374716.aspx
  218. */
  219. sspi_status =
  220. s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR *)UNISP_NAME,
  221. SECPKG_CRED_OUTBOUND, NULL,
  222. &schannel_cred, NULL, NULL,
  223. &connssl->cred->cred_handle,
  224. &connssl->cred->time_stamp);
  225. if(sspi_status != SEC_E_OK) {
  226. if(sspi_status == SEC_E_WRONG_PRINCIPAL)
  227. failf(data, "schannel: SNI or certificate check failed: %s",
  228. Curl_sspi_strerror(conn, sspi_status));
  229. else
  230. failf(data, "schannel: AcquireCredentialsHandle failed: %s",
  231. Curl_sspi_strerror(conn, sspi_status));
  232. Curl_safefree(connssl->cred);
  233. return CURLE_SSL_CONNECT_ERROR;
  234. }
  235. }
  236. /* Warn if SNI is disabled due to use of an IP address */
  237. if(Curl_inet_pton(AF_INET, hostname, &addr)
  238. #ifdef ENABLE_IPV6
  239. || Curl_inet_pton(AF_INET6, hostname, &addr6)
  240. #endif
  241. ) {
  242. infof(data, "schannel: using IP address, SNI is not supported by OS.\n");
  243. }
  244. #ifdef HAS_ALPN
  245. if(connssl->use_alpn) {
  246. int cur = 0;
  247. int list_start_index = 0;
  248. unsigned int *extension_len = NULL;
  249. unsigned short* list_len = NULL;
  250. /* The first four bytes will be an unsigned int indicating number
  251. of bytes of data in the rest of the the buffer. */
  252. extension_len = (unsigned int *)(&alpn_buffer[cur]);
  253. cur += sizeof(unsigned int);
  254. /* The next four bytes are an indicator that this buffer will contain
  255. ALPN data, as opposed to NPN, for example. */
  256. *(unsigned int *)&alpn_buffer[cur] =
  257. SecApplicationProtocolNegotiationExt_ALPN;
  258. cur += sizeof(unsigned int);
  259. /* The next two bytes will be an unsigned short indicating the number
  260. of bytes used to list the preferred protocols. */
  261. list_len = (unsigned short*)(&alpn_buffer[cur]);
  262. cur += sizeof(unsigned short);
  263. list_start_index = cur;
  264. #ifdef USE_NGHTTP2
  265. if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
  266. memcpy(&alpn_buffer[cur], NGHTTP2_PROTO_ALPN, NGHTTP2_PROTO_ALPN_LEN);
  267. cur += NGHTTP2_PROTO_ALPN_LEN;
  268. infof(data, "schannel: ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
  269. }
  270. #endif
  271. alpn_buffer[cur++] = ALPN_HTTP_1_1_LENGTH;
  272. memcpy(&alpn_buffer[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
  273. cur += ALPN_HTTP_1_1_LENGTH;
  274. infof(data, "schannel: ALPN, offering %s\n", ALPN_HTTP_1_1);
  275. *list_len = curlx_uitous(cur - list_start_index);
  276. *extension_len = *list_len + sizeof(unsigned int) + sizeof(unsigned short);
  277. InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur);
  278. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  279. }
  280. else
  281. {
  282. InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  283. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  284. }
  285. #else /* HAS_ALPN */
  286. InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  287. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  288. #endif
  289. /* setup output buffer */
  290. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  291. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  292. /* setup request flags */
  293. connssl->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
  294. ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
  295. ISC_REQ_STREAM;
  296. /* allocate memory for the security context handle */
  297. connssl->ctxt = (struct curl_schannel_ctxt *)
  298. malloc(sizeof(struct curl_schannel_ctxt));
  299. if(!connssl->ctxt) {
  300. failf(data, "schannel: unable to allocate memory");
  301. return CURLE_OUT_OF_MEMORY;
  302. }
  303. memset(connssl->ctxt, 0, sizeof(struct curl_schannel_ctxt));
  304. host_name = Curl_convert_UTF8_to_tchar(hostname);
  305. if(!host_name)
  306. return CURLE_OUT_OF_MEMORY;
  307. /* Schannel InitializeSecurityContext:
  308. https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx
  309. At the moment we don't pass inbuf unless we're using ALPN since we only
  310. use it for that, and Wine (for which we currently disable ALPN) is giving
  311. us problems with inbuf regardless. https://github.com/curl/curl/issues/983
  312. */
  313. sspi_status = s_pSecFn->InitializeSecurityContext(
  314. &connssl->cred->cred_handle, NULL, host_name, connssl->req_flags, 0, 0,
  315. (connssl->use_alpn ? &inbuf_desc : NULL),
  316. 0, &connssl->ctxt->ctxt_handle,
  317. &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
  318. Curl_unicodefree(host_name);
  319. if(sspi_status != SEC_I_CONTINUE_NEEDED) {
  320. if(sspi_status == SEC_E_WRONG_PRINCIPAL)
  321. failf(data, "schannel: SNI or certificate check failed: %s",
  322. Curl_sspi_strerror(conn, sspi_status));
  323. else
  324. failf(data, "schannel: initial InitializeSecurityContext failed: %s",
  325. Curl_sspi_strerror(conn, sspi_status));
  326. Curl_safefree(connssl->ctxt);
  327. return CURLE_SSL_CONNECT_ERROR;
  328. }
  329. infof(data, "schannel: sending initial handshake data: "
  330. "sending %lu bytes...\n", outbuf.cbBuffer);
  331. /* send initial handshake data which is now stored in output buffer */
  332. result = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer,
  333. outbuf.cbBuffer, &written);
  334. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  335. if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
  336. failf(data, "schannel: failed to send initial handshake data: "
  337. "sent %zd of %lu bytes", written, outbuf.cbBuffer);
  338. return CURLE_SSL_CONNECT_ERROR;
  339. }
  340. infof(data, "schannel: sent initial handshake data: "
  341. "sent %zd bytes\n", written);
  342. connssl->recv_unrecoverable_err = CURLE_OK;
  343. connssl->recv_sspi_close_notify = false;
  344. connssl->recv_connection_closed = false;
  345. /* continue to second handshake step */
  346. connssl->connecting_state = ssl_connect_2;
  347. return CURLE_OK;
  348. }
  349. static CURLcode
  350. schannel_connect_step2(struct connectdata *conn, int sockindex)
  351. {
  352. int i;
  353. ssize_t nread = -1, written = -1;
  354. struct Curl_easy *data = conn->data;
  355. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  356. unsigned char *reallocated_buffer;
  357. size_t reallocated_length;
  358. SecBuffer outbuf[3];
  359. SecBufferDesc outbuf_desc;
  360. SecBuffer inbuf[2];
  361. SecBufferDesc inbuf_desc;
  362. SECURITY_STATUS sspi_status = SEC_E_OK;
  363. TCHAR *host_name;
  364. CURLcode result;
  365. bool doread;
  366. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  367. conn->host.name;
  368. doread = (connssl->connecting_state != ssl_connect_2_writing) ? TRUE : FALSE;
  369. infof(data, "schannel: SSL/TLS connection with %s port %hu (step 2/3)\n",
  370. hostname, conn->remote_port);
  371. if(!connssl->cred || !connssl->ctxt)
  372. return CURLE_SSL_CONNECT_ERROR;
  373. /* buffer to store previously received and decrypted data */
  374. if(connssl->decdata_buffer == NULL) {
  375. connssl->decdata_offset = 0;
  376. connssl->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  377. connssl->decdata_buffer = malloc(connssl->decdata_length);
  378. if(connssl->decdata_buffer == NULL) {
  379. failf(data, "schannel: unable to allocate memory");
  380. return CURLE_OUT_OF_MEMORY;
  381. }
  382. }
  383. /* buffer to store previously received and encrypted data */
  384. if(connssl->encdata_buffer == NULL) {
  385. connssl->encdata_offset = 0;
  386. connssl->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  387. connssl->encdata_buffer = malloc(connssl->encdata_length);
  388. if(connssl->encdata_buffer == NULL) {
  389. failf(data, "schannel: unable to allocate memory");
  390. return CURLE_OUT_OF_MEMORY;
  391. }
  392. }
  393. /* if we need a bigger buffer to read a full message, increase buffer now */
  394. if(connssl->encdata_length - connssl->encdata_offset <
  395. CURL_SCHANNEL_BUFFER_FREE_SIZE) {
  396. /* increase internal encrypted data buffer */
  397. reallocated_length = connssl->encdata_offset +
  398. CURL_SCHANNEL_BUFFER_FREE_SIZE;
  399. reallocated_buffer = realloc(connssl->encdata_buffer,
  400. reallocated_length);
  401. if(reallocated_buffer == NULL) {
  402. failf(data, "schannel: unable to re-allocate memory");
  403. return CURLE_OUT_OF_MEMORY;
  404. }
  405. else {
  406. connssl->encdata_buffer = reallocated_buffer;
  407. connssl->encdata_length = reallocated_length;
  408. }
  409. }
  410. for(;;) {
  411. if(doread) {
  412. /* read encrypted handshake data from socket */
  413. result = Curl_read_plain(conn->sock[sockindex],
  414. (char *) (connssl->encdata_buffer +
  415. connssl->encdata_offset),
  416. connssl->encdata_length -
  417. connssl->encdata_offset,
  418. &nread);
  419. if(result == CURLE_AGAIN) {
  420. if(connssl->connecting_state != ssl_connect_2_writing)
  421. connssl->connecting_state = ssl_connect_2_reading;
  422. infof(data, "schannel: failed to receive handshake, "
  423. "need more data\n");
  424. return CURLE_OK;
  425. }
  426. else if((result != CURLE_OK) || (nread == 0)) {
  427. failf(data, "schannel: failed to receive handshake, "
  428. "SSL/TLS connection failed");
  429. return CURLE_SSL_CONNECT_ERROR;
  430. }
  431. /* increase encrypted data buffer offset */
  432. connssl->encdata_offset += nread;
  433. }
  434. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  435. connssl->encdata_offset, connssl->encdata_length);
  436. /* setup input buffers */
  437. InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(connssl->encdata_offset),
  438. curlx_uztoul(connssl->encdata_offset));
  439. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  440. InitSecBufferDesc(&inbuf_desc, inbuf, 2);
  441. /* setup output buffers */
  442. InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0);
  443. InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0);
  444. InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0);
  445. InitSecBufferDesc(&outbuf_desc, outbuf, 3);
  446. if(inbuf[0].pvBuffer == NULL) {
  447. failf(data, "schannel: unable to allocate memory");
  448. return CURLE_OUT_OF_MEMORY;
  449. }
  450. /* copy received handshake data into input buffer */
  451. memcpy(inbuf[0].pvBuffer, connssl->encdata_buffer,
  452. connssl->encdata_offset);
  453. host_name = Curl_convert_UTF8_to_tchar(hostname);
  454. if(!host_name)
  455. return CURLE_OUT_OF_MEMORY;
  456. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx
  457. */
  458. sspi_status = s_pSecFn->InitializeSecurityContext(
  459. &connssl->cred->cred_handle, &connssl->ctxt->ctxt_handle,
  460. host_name, connssl->req_flags, 0, 0, &inbuf_desc, 0, NULL,
  461. &outbuf_desc, &connssl->ret_flags, &connssl->ctxt->time_stamp);
  462. Curl_unicodefree(host_name);
  463. /* free buffer for received handshake data */
  464. Curl_safefree(inbuf[0].pvBuffer);
  465. /* check if the handshake was incomplete */
  466. if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  467. connssl->connecting_state = ssl_connect_2_reading;
  468. infof(data, "schannel: received incomplete message, need more data\n");
  469. return CURLE_OK;
  470. }
  471. /* If the server has requested a client certificate, attempt to continue
  472. the handshake without one. This will allow connections to servers which
  473. request a client certificate but do not require it. */
  474. if(sspi_status == SEC_I_INCOMPLETE_CREDENTIALS &&
  475. !(connssl->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
  476. connssl->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
  477. connssl->connecting_state = ssl_connect_2_writing;
  478. infof(data, "schannel: a client certificate has been requested\n");
  479. return CURLE_OK;
  480. }
  481. /* check if the handshake needs to be continued */
  482. if(sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) {
  483. for(i = 0; i < 3; i++) {
  484. /* search for handshake tokens that need to be send */
  485. if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) {
  486. infof(data, "schannel: sending next handshake data: "
  487. "sending %lu bytes...\n", outbuf[i].cbBuffer);
  488. /* send handshake token to server */
  489. result = Curl_write_plain(conn, conn->sock[sockindex],
  490. outbuf[i].pvBuffer, outbuf[i].cbBuffer,
  491. &written);
  492. if((result != CURLE_OK) ||
  493. (outbuf[i].cbBuffer != (size_t) written)) {
  494. failf(data, "schannel: failed to send next handshake data: "
  495. "sent %zd of %lu bytes", written, outbuf[i].cbBuffer);
  496. return CURLE_SSL_CONNECT_ERROR;
  497. }
  498. }
  499. /* free obsolete buffer */
  500. if(outbuf[i].pvBuffer != NULL) {
  501. s_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer);
  502. }
  503. }
  504. }
  505. else {
  506. if(sspi_status == SEC_E_WRONG_PRINCIPAL)
  507. failf(data, "schannel: SNI or certificate check failed: %s",
  508. Curl_sspi_strerror(conn, sspi_status));
  509. else
  510. failf(data, "schannel: next InitializeSecurityContext failed: %s",
  511. Curl_sspi_strerror(conn, sspi_status));
  512. return CURLE_SSL_CONNECT_ERROR;
  513. }
  514. /* check if there was additional remaining encrypted data */
  515. if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) {
  516. infof(data, "schannel: encrypted data length: %lu\n", inbuf[1].cbBuffer);
  517. /*
  518. There are two cases where we could be getting extra data here:
  519. 1) If we're renegotiating a connection and the handshake is already
  520. complete (from the server perspective), it can encrypted app data
  521. (not handshake data) in an extra buffer at this point.
  522. 2) (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a
  523. connection and this extra data is part of the handshake.
  524. We should process the data immediately; waiting for the socket to
  525. be ready may fail since the server is done sending handshake data.
  526. */
  527. /* check if the remaining data is less than the total amount
  528. and therefore begins after the already processed data */
  529. if(connssl->encdata_offset > inbuf[1].cbBuffer) {
  530. memmove(connssl->encdata_buffer,
  531. (connssl->encdata_buffer + connssl->encdata_offset) -
  532. inbuf[1].cbBuffer, inbuf[1].cbBuffer);
  533. connssl->encdata_offset = inbuf[1].cbBuffer;
  534. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  535. doread = FALSE;
  536. continue;
  537. }
  538. }
  539. }
  540. else {
  541. connssl->encdata_offset = 0;
  542. }
  543. break;
  544. }
  545. /* check if the handshake needs to be continued */
  546. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  547. connssl->connecting_state = ssl_connect_2_reading;
  548. return CURLE_OK;
  549. }
  550. /* check if the handshake is complete */
  551. if(sspi_status == SEC_E_OK) {
  552. connssl->connecting_state = ssl_connect_3;
  553. infof(data, "schannel: SSL/TLS handshake complete\n");
  554. }
  555. #ifdef _WIN32_WCE
  556. /* Windows CE doesn't do any server certificate validation.
  557. We have to do it manually. */
  558. if(conn->ssl_config.verifypeer)
  559. return verify_certificate(conn, sockindex);
  560. #endif
  561. return CURLE_OK;
  562. }
  563. static CURLcode
  564. schannel_connect_step3(struct connectdata *conn, int sockindex)
  565. {
  566. CURLcode result = CURLE_OK;
  567. struct Curl_easy *data = conn->data;
  568. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  569. SECURITY_STATUS sspi_status = SEC_E_OK;
  570. CERT_CONTEXT *ccert_context = NULL;
  571. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  572. conn->host.name;
  573. #ifdef HAS_ALPN
  574. SecPkgContext_ApplicationProtocol alpn_result;
  575. #endif
  576. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  577. infof(data, "schannel: SSL/TLS connection with %s port %hu (step 3/3)\n",
  578. hostname, conn->remote_port);
  579. if(!connssl->cred)
  580. return CURLE_SSL_CONNECT_ERROR;
  581. /* check if the required context attributes are met */
  582. if(connssl->ret_flags != connssl->req_flags) {
  583. if(!(connssl->ret_flags & ISC_RET_SEQUENCE_DETECT))
  584. failf(data, "schannel: failed to setup sequence detection");
  585. if(!(connssl->ret_flags & ISC_RET_REPLAY_DETECT))
  586. failf(data, "schannel: failed to setup replay detection");
  587. if(!(connssl->ret_flags & ISC_RET_CONFIDENTIALITY))
  588. failf(data, "schannel: failed to setup confidentiality");
  589. if(!(connssl->ret_flags & ISC_RET_ALLOCATED_MEMORY))
  590. failf(data, "schannel: failed to setup memory allocation");
  591. if(!(connssl->ret_flags & ISC_RET_STREAM))
  592. failf(data, "schannel: failed to setup stream orientation");
  593. return CURLE_SSL_CONNECT_ERROR;
  594. }
  595. #ifdef HAS_ALPN
  596. if(connssl->use_alpn) {
  597. sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
  598. SECPKG_ATTR_APPLICATION_PROTOCOL, &alpn_result);
  599. if(sspi_status != SEC_E_OK) {
  600. failf(data, "schannel: failed to retrieve ALPN result");
  601. return CURLE_SSL_CONNECT_ERROR;
  602. }
  603. if(alpn_result.ProtoNegoStatus ==
  604. SecApplicationProtocolNegotiationStatus_Success) {
  605. infof(data, "schannel: ALPN, server accepted to use %.*s\n",
  606. alpn_result.ProtocolIdSize, alpn_result.ProtocolId);
  607. #ifdef USE_NGHTTP2
  608. if(alpn_result.ProtocolIdSize == NGHTTP2_PROTO_VERSION_ID_LEN &&
  609. !memcmp(NGHTTP2_PROTO_VERSION_ID, alpn_result.ProtocolId,
  610. NGHTTP2_PROTO_VERSION_ID_LEN)) {
  611. conn->negnpn = CURL_HTTP_VERSION_2;
  612. }
  613. else
  614. #endif
  615. if(alpn_result.ProtocolIdSize == ALPN_HTTP_1_1_LENGTH &&
  616. !memcmp(ALPN_HTTP_1_1, alpn_result.ProtocolId,
  617. ALPN_HTTP_1_1_LENGTH)) {
  618. conn->negnpn = CURL_HTTP_VERSION_1_1;
  619. }
  620. }
  621. else
  622. infof(data, "ALPN, server did not agree to a protocol\n");
  623. }
  624. #endif
  625. /* save the current session data for possible re-use */
  626. if(data->set.general_ssl.sessionid) {
  627. bool incache;
  628. struct curl_schannel_cred *old_cred = NULL;
  629. Curl_ssl_sessionid_lock(conn);
  630. incache = !(Curl_ssl_getsessionid(conn, (void **)&old_cred, NULL,
  631. sockindex));
  632. if(incache) {
  633. if(old_cred != connssl->cred) {
  634. infof(data, "schannel: old credential handle is stale, removing\n");
  635. /* we're not taking old_cred ownership here, no refcount++ is needed */
  636. Curl_ssl_delsessionid(conn, (void *)old_cred);
  637. incache = FALSE;
  638. }
  639. }
  640. if(!incache) {
  641. result = Curl_ssl_addsessionid(conn, (void *)connssl->cred,
  642. sizeof(struct curl_schannel_cred),
  643. sockindex);
  644. if(result) {
  645. Curl_ssl_sessionid_unlock(conn);
  646. failf(data, "schannel: failed to store credential handle");
  647. return result;
  648. }
  649. else {
  650. /* this cred session is now also referenced by sessionid cache */
  651. connssl->cred->refcount++;
  652. infof(data, "schannel: stored credential handle in session cache\n");
  653. }
  654. }
  655. Curl_ssl_sessionid_unlock(conn);
  656. }
  657. if(data->set.ssl.certinfo) {
  658. sspi_status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
  659. SECPKG_ATTR_REMOTE_CERT_CONTEXT, &ccert_context);
  660. if((sspi_status != SEC_E_OK) || (ccert_context == NULL)) {
  661. failf(data, "schannel: failed to retrieve remote cert context");
  662. return CURLE_SSL_CONNECT_ERROR;
  663. }
  664. result = Curl_ssl_init_certinfo(data, 1);
  665. if(!result) {
  666. if(((ccert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
  667. (ccert_context->cbCertEncoded > 0)) {
  668. const char *beg = (const char *) ccert_context->pbCertEncoded;
  669. const char *end = beg + ccert_context->cbCertEncoded;
  670. result = Curl_extract_certinfo(conn, 0, beg, end);
  671. }
  672. }
  673. CertFreeCertificateContext(ccert_context);
  674. if(result)
  675. return result;
  676. }
  677. connssl->connecting_state = ssl_connect_done;
  678. return CURLE_OK;
  679. }
  680. static CURLcode
  681. schannel_connect_common(struct connectdata *conn, int sockindex,
  682. bool nonblocking, bool *done)
  683. {
  684. CURLcode result;
  685. struct Curl_easy *data = conn->data;
  686. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  687. curl_socket_t sockfd = conn->sock[sockindex];
  688. time_t timeout_ms;
  689. int what;
  690. /* check if the connection has already been established */
  691. if(ssl_connection_complete == connssl->state) {
  692. *done = TRUE;
  693. return CURLE_OK;
  694. }
  695. if(ssl_connect_1 == connssl->connecting_state) {
  696. /* check out how much more time we're allowed */
  697. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  698. if(timeout_ms < 0) {
  699. /* no need to continue if time already is up */
  700. failf(data, "SSL/TLS connection timeout");
  701. return CURLE_OPERATION_TIMEDOUT;
  702. }
  703. result = schannel_connect_step1(conn, sockindex);
  704. if(result)
  705. return result;
  706. }
  707. while(ssl_connect_2 == connssl->connecting_state ||
  708. ssl_connect_2_reading == connssl->connecting_state ||
  709. ssl_connect_2_writing == connssl->connecting_state) {
  710. /* check out how much more time we're allowed */
  711. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  712. if(timeout_ms < 0) {
  713. /* no need to continue if time already is up */
  714. failf(data, "SSL/TLS connection timeout");
  715. return CURLE_OPERATION_TIMEDOUT;
  716. }
  717. /* if ssl is expecting something, check if it's available. */
  718. if(connssl->connecting_state == ssl_connect_2_reading
  719. || connssl->connecting_state == ssl_connect_2_writing) {
  720. curl_socket_t writefd = ssl_connect_2_writing ==
  721. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  722. curl_socket_t readfd = ssl_connect_2_reading ==
  723. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  724. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  725. nonblocking ? 0 : timeout_ms);
  726. if(what < 0) {
  727. /* fatal error */
  728. failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO);
  729. return CURLE_SSL_CONNECT_ERROR;
  730. }
  731. else if(0 == what) {
  732. if(nonblocking) {
  733. *done = FALSE;
  734. return CURLE_OK;
  735. }
  736. else {
  737. /* timeout */
  738. failf(data, "SSL/TLS connection timeout");
  739. return CURLE_OPERATION_TIMEDOUT;
  740. }
  741. }
  742. /* socket is readable or writable */
  743. }
  744. /* Run transaction, and return to the caller if it failed or if
  745. * this connection is part of a multi handle and this loop would
  746. * execute again. This permits the owner of a multi handle to
  747. * abort a connection attempt before step2 has completed while
  748. * ensuring that a client using select() or epoll() will always
  749. * have a valid fdset to wait on.
  750. */
  751. result = schannel_connect_step2(conn, sockindex);
  752. if(result || (nonblocking &&
  753. (ssl_connect_2 == connssl->connecting_state ||
  754. ssl_connect_2_reading == connssl->connecting_state ||
  755. ssl_connect_2_writing == connssl->connecting_state)))
  756. return result;
  757. } /* repeat step2 until all transactions are done. */
  758. if(ssl_connect_3 == connssl->connecting_state) {
  759. result = schannel_connect_step3(conn, sockindex);
  760. if(result)
  761. return result;
  762. }
  763. if(ssl_connect_done == connssl->connecting_state) {
  764. connssl->state = ssl_connection_complete;
  765. conn->recv[sockindex] = schannel_recv;
  766. conn->send[sockindex] = schannel_send;
  767. *done = TRUE;
  768. }
  769. else
  770. *done = FALSE;
  771. /* reset our connection state machine */
  772. connssl->connecting_state = ssl_connect_1;
  773. return CURLE_OK;
  774. }
  775. static ssize_t
  776. schannel_send(struct connectdata *conn, int sockindex,
  777. const void *buf, size_t len, CURLcode *err)
  778. {
  779. ssize_t written = -1;
  780. size_t data_len = 0;
  781. unsigned char *data = NULL;
  782. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  783. SecBuffer outbuf[4];
  784. SecBufferDesc outbuf_desc;
  785. SECURITY_STATUS sspi_status = SEC_E_OK;
  786. CURLcode result;
  787. /* check if the maximum stream sizes were queried */
  788. if(connssl->stream_sizes.cbMaximumMessage == 0) {
  789. sspi_status = s_pSecFn->QueryContextAttributes(
  790. &connssl->ctxt->ctxt_handle,
  791. SECPKG_ATTR_STREAM_SIZES,
  792. &connssl->stream_sizes);
  793. if(sspi_status != SEC_E_OK) {
  794. *err = CURLE_SEND_ERROR;
  795. return -1;
  796. }
  797. }
  798. /* check if the buffer is longer than the maximum message length */
  799. if(len > connssl->stream_sizes.cbMaximumMessage) {
  800. *err = CURLE_SEND_ERROR;
  801. return -1;
  802. }
  803. /* calculate the complete message length and allocate a buffer for it */
  804. data_len = connssl->stream_sizes.cbHeader + len +
  805. connssl->stream_sizes.cbTrailer;
  806. data = (unsigned char *) malloc(data_len);
  807. if(data == NULL) {
  808. *err = CURLE_OUT_OF_MEMORY;
  809. return -1;
  810. }
  811. /* setup output buffers (header, data, trailer, empty) */
  812. InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
  813. data, connssl->stream_sizes.cbHeader);
  814. InitSecBuffer(&outbuf[1], SECBUFFER_DATA,
  815. data + connssl->stream_sizes.cbHeader, curlx_uztoul(len));
  816. InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
  817. data + connssl->stream_sizes.cbHeader + len,
  818. connssl->stream_sizes.cbTrailer);
  819. InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
  820. InitSecBufferDesc(&outbuf_desc, outbuf, 4);
  821. /* copy data into output buffer */
  822. memcpy(outbuf[1].pvBuffer, buf, len);
  823. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */
  824. sspi_status = s_pSecFn->EncryptMessage(&connssl->ctxt->ctxt_handle, 0,
  825. &outbuf_desc, 0);
  826. /* check if the message was encrypted */
  827. if(sspi_status == SEC_E_OK) {
  828. written = 0;
  829. /* send the encrypted message including header, data and trailer */
  830. len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer;
  831. /*
  832. It's important to send the full message which includes the header,
  833. encrypted payload, and trailer. Until the client receives all the
  834. data a coherent message has not been delivered and the client
  835. can't read any of it.
  836. If we wanted to buffer the unwritten encrypted bytes, we would
  837. tell the client that all data it has requested to be sent has been
  838. sent. The unwritten encrypted bytes would be the first bytes to
  839. send on the next invocation.
  840. Here's the catch with this - if we tell the client that all the
  841. bytes have been sent, will the client call this method again to
  842. send the buffered data? Looking at who calls this function, it
  843. seems the answer is NO.
  844. */
  845. /* send entire message or fail */
  846. while(len > (size_t)written) {
  847. ssize_t this_write;
  848. time_t timeleft;
  849. int what;
  850. this_write = 0;
  851. timeleft = Curl_timeleft(conn->data, NULL, FALSE);
  852. if(timeleft < 0) {
  853. /* we already got the timeout */
  854. failf(conn->data, "schannel: timed out sending data "
  855. "(bytes sent: %zd)", written);
  856. *err = CURLE_OPERATION_TIMEDOUT;
  857. written = -1;
  858. break;
  859. }
  860. what = SOCKET_WRITABLE(conn->sock[sockindex], timeleft);
  861. if(what < 0) {
  862. /* fatal error */
  863. failf(conn->data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  864. *err = CURLE_SEND_ERROR;
  865. written = -1;
  866. break;
  867. }
  868. else if(0 == what) {
  869. failf(conn->data, "schannel: timed out sending data "
  870. "(bytes sent: %zd)", written);
  871. *err = CURLE_OPERATION_TIMEDOUT;
  872. written = -1;
  873. break;
  874. }
  875. /* socket is writable */
  876. result = Curl_write_plain(conn, conn->sock[sockindex], data + written,
  877. len - written, &this_write);
  878. if(result == CURLE_AGAIN)
  879. continue;
  880. else if(result != CURLE_OK) {
  881. *err = result;
  882. written = -1;
  883. break;
  884. }
  885. written += this_write;
  886. }
  887. }
  888. else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) {
  889. *err = CURLE_OUT_OF_MEMORY;
  890. }
  891. else{
  892. *err = CURLE_SEND_ERROR;
  893. }
  894. Curl_safefree(data);
  895. if(len == (size_t)written)
  896. /* Encrypted message including header, data and trailer entirely sent.
  897. The return value is the number of unencrypted bytes that were sent. */
  898. written = outbuf[1].cbBuffer;
  899. return written;
  900. }
  901. static ssize_t
  902. schannel_recv(struct connectdata *conn, int sockindex,
  903. char *buf, size_t len, CURLcode *err)
  904. {
  905. size_t size = 0;
  906. ssize_t nread = -1;
  907. struct Curl_easy *data = conn->data;
  908. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  909. unsigned char *reallocated_buffer;
  910. size_t reallocated_length;
  911. bool done = FALSE;
  912. SecBuffer inbuf[4];
  913. SecBufferDesc inbuf_desc;
  914. SECURITY_STATUS sspi_status = SEC_E_OK;
  915. /* we want the length of the encrypted buffer to be at least large enough
  916. that it can hold all the bytes requested and some TLS record overhead. */
  917. size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE;
  918. /****************************************************************************
  919. * Don't return or set connssl->recv_unrecoverable_err unless in the cleanup.
  920. * The pattern for return error is set *err, optional infof, goto cleanup.
  921. *
  922. * Our priority is to always return as much decrypted data to the caller as
  923. * possible, even if an error occurs. The state of the decrypted buffer must
  924. * always be valid. Transfer of decrypted data to the caller's buffer is
  925. * handled in the cleanup.
  926. */
  927. infof(data, "schannel: client wants to read %zu bytes\n", len);
  928. *err = CURLE_OK;
  929. if(len && len <= connssl->decdata_offset) {
  930. infof(data, "schannel: enough decrypted data is already available\n");
  931. goto cleanup;
  932. }
  933. else if(connssl->recv_unrecoverable_err) {
  934. *err = connssl->recv_unrecoverable_err;
  935. infof(data, "schannel: an unrecoverable error occurred in a prior call\n");
  936. goto cleanup;
  937. }
  938. else if(connssl->recv_sspi_close_notify) {
  939. /* once a server has indicated shutdown there is no more encrypted data */
  940. infof(data, "schannel: server indicated shutdown in a prior call\n");
  941. goto cleanup;
  942. }
  943. else if(!len) {
  944. /* It's debatable what to return when !len. Regardless we can't return
  945. immediately because there may be data to decrypt (in the case we want to
  946. decrypt all encrypted cached data) so handle !len later in cleanup.
  947. */
  948. ; /* do nothing */
  949. }
  950. else if(!connssl->recv_connection_closed) {
  951. /* increase enc buffer in order to fit the requested amount of data */
  952. size = connssl->encdata_length - connssl->encdata_offset;
  953. if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE ||
  954. connssl->encdata_length < min_encdata_length) {
  955. reallocated_length = connssl->encdata_offset +
  956. CURL_SCHANNEL_BUFFER_FREE_SIZE;
  957. if(reallocated_length < min_encdata_length) {
  958. reallocated_length = min_encdata_length;
  959. }
  960. reallocated_buffer = realloc(connssl->encdata_buffer,
  961. reallocated_length);
  962. if(reallocated_buffer == NULL) {
  963. *err = CURLE_OUT_OF_MEMORY;
  964. failf(data, "schannel: unable to re-allocate memory");
  965. goto cleanup;
  966. }
  967. connssl->encdata_buffer = reallocated_buffer;
  968. connssl->encdata_length = reallocated_length;
  969. size = connssl->encdata_length - connssl->encdata_offset;
  970. infof(data, "schannel: encdata_buffer resized %zu\n",
  971. connssl->encdata_length);
  972. }
  973. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  974. connssl->encdata_offset, connssl->encdata_length);
  975. /* read encrypted data from socket */
  976. *err = Curl_read_plain(conn->sock[sockindex],
  977. (char *)(connssl->encdata_buffer +
  978. connssl->encdata_offset),
  979. size, &nread);
  980. if(*err) {
  981. nread = -1;
  982. if(*err == CURLE_AGAIN)
  983. infof(data, "schannel: Curl_read_plain returned CURLE_AGAIN\n");
  984. else if(*err == CURLE_RECV_ERROR)
  985. infof(data, "schannel: Curl_read_plain returned CURLE_RECV_ERROR\n");
  986. else
  987. infof(data, "schannel: Curl_read_plain returned error %d\n", *err);
  988. }
  989. else if(nread == 0) {
  990. connssl->recv_connection_closed = true;
  991. infof(data, "schannel: server closed the connection\n");
  992. }
  993. else if(nread > 0) {
  994. connssl->encdata_offset += (size_t)nread;
  995. infof(data, "schannel: encrypted data got %zd\n", nread);
  996. }
  997. }
  998. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  999. connssl->encdata_offset, connssl->encdata_length);
  1000. /* decrypt loop */
  1001. while(connssl->encdata_offset > 0 && sspi_status == SEC_E_OK &&
  1002. (!len || connssl->decdata_offset < len ||
  1003. connssl->recv_connection_closed)) {
  1004. /* prepare data buffer for DecryptMessage call */
  1005. InitSecBuffer(&inbuf[0], SECBUFFER_DATA, connssl->encdata_buffer,
  1006. curlx_uztoul(connssl->encdata_offset));
  1007. /* we need 3 more empty input buffers for possible output */
  1008. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  1009. InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0);
  1010. InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0);
  1011. InitSecBufferDesc(&inbuf_desc, inbuf, 4);
  1012. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx
  1013. */
  1014. sspi_status = s_pSecFn->DecryptMessage(&connssl->ctxt->ctxt_handle,
  1015. &inbuf_desc, 0, NULL);
  1016. /* check if everything went fine (server may want to renegotiate
  1017. or shutdown the connection context) */
  1018. if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE ||
  1019. sspi_status == SEC_I_CONTEXT_EXPIRED) {
  1020. /* check for successfully decrypted data, even before actual
  1021. renegotiation or shutdown of the connection context */
  1022. if(inbuf[1].BufferType == SECBUFFER_DATA) {
  1023. infof(data, "schannel: decrypted data length: %lu\n",
  1024. inbuf[1].cbBuffer);
  1025. /* increase buffer in order to fit the received amount of data */
  1026. size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ?
  1027. inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1028. if(connssl->decdata_length - connssl->decdata_offset < size ||
  1029. connssl->decdata_length < len) {
  1030. /* increase internal decrypted data buffer */
  1031. reallocated_length = connssl->decdata_offset + size;
  1032. /* make sure that the requested amount of data fits */
  1033. if(reallocated_length < len) {
  1034. reallocated_length = len;
  1035. }
  1036. reallocated_buffer = realloc(connssl->decdata_buffer,
  1037. reallocated_length);
  1038. if(reallocated_buffer == NULL) {
  1039. *err = CURLE_OUT_OF_MEMORY;
  1040. failf(data, "schannel: unable to re-allocate memory");
  1041. goto cleanup;
  1042. }
  1043. connssl->decdata_buffer = reallocated_buffer;
  1044. connssl->decdata_length = reallocated_length;
  1045. }
  1046. /* copy decrypted data to internal buffer */
  1047. size = inbuf[1].cbBuffer;
  1048. if(size) {
  1049. memcpy(connssl->decdata_buffer + connssl->decdata_offset,
  1050. inbuf[1].pvBuffer, size);
  1051. connssl->decdata_offset += size;
  1052. }
  1053. infof(data, "schannel: decrypted data added: %zu\n", size);
  1054. infof(data, "schannel: decrypted data cached: offset %zu length %zu\n",
  1055. connssl->decdata_offset, connssl->decdata_length);
  1056. }
  1057. /* check for remaining encrypted data */
  1058. if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) {
  1059. infof(data, "schannel: encrypted data length: %lu\n",
  1060. inbuf[3].cbBuffer);
  1061. /* check if the remaining data is less than the total amount
  1062. * and therefore begins after the already processed data
  1063. */
  1064. if(connssl->encdata_offset > inbuf[3].cbBuffer) {
  1065. /* move remaining encrypted data forward to the beginning of
  1066. buffer */
  1067. memmove(connssl->encdata_buffer,
  1068. (connssl->encdata_buffer + connssl->encdata_offset) -
  1069. inbuf[3].cbBuffer, inbuf[3].cbBuffer);
  1070. connssl->encdata_offset = inbuf[3].cbBuffer;
  1071. }
  1072. infof(data, "schannel: encrypted data cached: offset %zu length %zu\n",
  1073. connssl->encdata_offset, connssl->encdata_length);
  1074. }
  1075. else {
  1076. /* reset encrypted buffer offset, because there is no data remaining */
  1077. connssl->encdata_offset = 0;
  1078. }
  1079. /* check if server wants to renegotiate the connection context */
  1080. if(sspi_status == SEC_I_RENEGOTIATE) {
  1081. infof(data, "schannel: remote party requests renegotiation\n");
  1082. if(*err && *err != CURLE_AGAIN) {
  1083. infof(data, "schannel: can't renogotiate, an error is pending\n");
  1084. goto cleanup;
  1085. }
  1086. if(connssl->encdata_offset) {
  1087. *err = CURLE_RECV_ERROR;
  1088. infof(data, "schannel: can't renogotiate, "
  1089. "encrypted data available\n");
  1090. goto cleanup;
  1091. }
  1092. /* begin renegotiation */
  1093. infof(data, "schannel: renegotiating SSL/TLS connection\n");
  1094. connssl->state = ssl_connection_negotiating;
  1095. connssl->connecting_state = ssl_connect_2_writing;
  1096. *err = schannel_connect_common(conn, sockindex, FALSE, &done);
  1097. if(*err) {
  1098. infof(data, "schannel: renegotiation failed\n");
  1099. goto cleanup;
  1100. }
  1101. /* now retry receiving data */
  1102. sspi_status = SEC_E_OK;
  1103. infof(data, "schannel: SSL/TLS connection renegotiated\n");
  1104. continue;
  1105. }
  1106. /* check if the server closed the connection */
  1107. else if(sspi_status == SEC_I_CONTEXT_EXPIRED) {
  1108. /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not
  1109. returned so we have to work around that in cleanup. */
  1110. connssl->recv_sspi_close_notify = true;
  1111. if(!connssl->recv_connection_closed) {
  1112. connssl->recv_connection_closed = true;
  1113. infof(data, "schannel: server closed the connection\n");
  1114. }
  1115. goto cleanup;
  1116. }
  1117. }
  1118. else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  1119. if(!*err)
  1120. *err = CURLE_AGAIN;
  1121. infof(data, "schannel: failed to decrypt data, need more data\n");
  1122. goto cleanup;
  1123. }
  1124. else {
  1125. *err = CURLE_RECV_ERROR;
  1126. infof(data, "schannel: failed to read data from server: %s\n",
  1127. Curl_sspi_strerror(conn, sspi_status));
  1128. goto cleanup;
  1129. }
  1130. }
  1131. infof(data, "schannel: encrypted data buffer: offset %zu length %zu\n",
  1132. connssl->encdata_offset, connssl->encdata_length);
  1133. infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n",
  1134. connssl->decdata_offset, connssl->decdata_length);
  1135. cleanup:
  1136. /* Warning- there is no guarantee the encdata state is valid at this point */
  1137. infof(data, "schannel: schannel_recv cleanup\n");
  1138. /* Error if the connection has closed without a close_notify.
  1139. Behavior here is a matter of debate. We don't want to be vulnerable to a
  1140. truncation attack however there's some browser precedent for ignoring the
  1141. close_notify for compatibility reasons.
  1142. Additionally, Windows 2000 (v5.0) is a special case since it seems it doesn't
  1143. return close_notify. In that case if the connection was closed we assume it
  1144. was graceful (close_notify) since there doesn't seem to be a way to tell.
  1145. */
  1146. if(len && !connssl->decdata_offset && connssl->recv_connection_closed &&
  1147. !connssl->recv_sspi_close_notify) {
  1148. bool isWin2k = Curl_verify_windows_version(5, 0, PLATFORM_WINNT,
  1149. VERSION_EQUAL);
  1150. if(isWin2k && sspi_status == SEC_E_OK)
  1151. connssl->recv_sspi_close_notify = true;
  1152. else {
  1153. *err = CURLE_RECV_ERROR;
  1154. infof(data, "schannel: server closed abruptly (missing close_notify)\n");
  1155. }
  1156. }
  1157. /* Any error other than CURLE_AGAIN is an unrecoverable error. */
  1158. if(*err && *err != CURLE_AGAIN)
  1159. connssl->recv_unrecoverable_err = *err;
  1160. size = len < connssl->decdata_offset ? len : connssl->decdata_offset;
  1161. if(size) {
  1162. memcpy(buf, connssl->decdata_buffer, size);
  1163. memmove(connssl->decdata_buffer, connssl->decdata_buffer + size,
  1164. connssl->decdata_offset - size);
  1165. connssl->decdata_offset -= size;
  1166. infof(data, "schannel: decrypted data returned %zu\n", size);
  1167. infof(data, "schannel: decrypted data buffer: offset %zu length %zu\n",
  1168. connssl->decdata_offset, connssl->decdata_length);
  1169. *err = CURLE_OK;
  1170. return (ssize_t)size;
  1171. }
  1172. if(!*err && !connssl->recv_connection_closed)
  1173. *err = CURLE_AGAIN;
  1174. /* It's debatable what to return when !len. We could return whatever error we
  1175. got from decryption but instead we override here so the return is consistent.
  1176. */
  1177. if(!len)
  1178. *err = CURLE_OK;
  1179. return *err ? -1 : 0;
  1180. }
  1181. CURLcode
  1182. Curl_schannel_connect_nonblocking(struct connectdata *conn, int sockindex,
  1183. bool *done)
  1184. {
  1185. return schannel_connect_common(conn, sockindex, TRUE, done);
  1186. }
  1187. CURLcode
  1188. Curl_schannel_connect(struct connectdata *conn, int sockindex)
  1189. {
  1190. CURLcode result;
  1191. bool done = FALSE;
  1192. result = schannel_connect_common(conn, sockindex, FALSE, &done);
  1193. if(result)
  1194. return result;
  1195. DEBUGASSERT(done);
  1196. return CURLE_OK;
  1197. }
  1198. bool Curl_schannel_data_pending(const struct connectdata *conn, int sockindex)
  1199. {
  1200. const struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1201. if(connssl->use) /* SSL/TLS is in use */
  1202. return (connssl->encdata_offset > 0 ||
  1203. connssl->decdata_offset > 0) ? TRUE : FALSE;
  1204. else
  1205. return FALSE;
  1206. }
  1207. void Curl_schannel_close(struct connectdata *conn, int sockindex)
  1208. {
  1209. if(conn->ssl[sockindex].use)
  1210. /* if the SSL/TLS channel hasn't been shut down yet, do that now. */
  1211. Curl_ssl_shutdown(conn, sockindex);
  1212. }
  1213. int Curl_schannel_shutdown(struct connectdata *conn, int sockindex)
  1214. {
  1215. /* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx
  1216. * Shutting Down an Schannel Connection
  1217. */
  1218. struct Curl_easy *data = conn->data;
  1219. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1220. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  1221. conn->host.name;
  1222. infof(data, "schannel: shutting down SSL/TLS connection with %s port %hu\n",
  1223. hostname, conn->remote_port);
  1224. if(connssl->cred && connssl->ctxt) {
  1225. SecBufferDesc BuffDesc;
  1226. SecBuffer Buffer;
  1227. SECURITY_STATUS sspi_status;
  1228. SecBuffer outbuf;
  1229. SecBufferDesc outbuf_desc;
  1230. CURLcode result;
  1231. TCHAR *host_name;
  1232. DWORD dwshut = SCHANNEL_SHUTDOWN;
  1233. InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
  1234. InitSecBufferDesc(&BuffDesc, &Buffer, 1);
  1235. sspi_status = s_pSecFn->ApplyControlToken(&connssl->ctxt->ctxt_handle,
  1236. &BuffDesc);
  1237. if(sspi_status != SEC_E_OK)
  1238. failf(data, "schannel: ApplyControlToken failure: %s",
  1239. Curl_sspi_strerror(conn, sspi_status));
  1240. host_name = Curl_convert_UTF8_to_tchar(hostname);
  1241. if(!host_name)
  1242. return CURLE_OUT_OF_MEMORY;
  1243. /* setup output buffer */
  1244. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  1245. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  1246. sspi_status = s_pSecFn->InitializeSecurityContext(
  1247. &connssl->cred->cred_handle,
  1248. &connssl->ctxt->ctxt_handle,
  1249. host_name,
  1250. connssl->req_flags,
  1251. 0,
  1252. 0,
  1253. NULL,
  1254. 0,
  1255. &connssl->ctxt->ctxt_handle,
  1256. &outbuf_desc,
  1257. &connssl->ret_flags,
  1258. &connssl->ctxt->time_stamp);
  1259. Curl_unicodefree(host_name);
  1260. if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) {
  1261. /* send close message which is in output buffer */
  1262. ssize_t written;
  1263. result = Curl_write_plain(conn, conn->sock[sockindex], outbuf.pvBuffer,
  1264. outbuf.cbBuffer, &written);
  1265. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  1266. if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
  1267. infof(data, "schannel: failed to send close msg: %s"
  1268. " (bytes written: %zd)\n", curl_easy_strerror(result), written);
  1269. }
  1270. }
  1271. }
  1272. /* free SSPI Schannel API security context handle */
  1273. if(connssl->ctxt) {
  1274. infof(data, "schannel: clear security context handle\n");
  1275. s_pSecFn->DeleteSecurityContext(&connssl->ctxt->ctxt_handle);
  1276. Curl_safefree(connssl->ctxt);
  1277. }
  1278. /* free SSPI Schannel API credential handle */
  1279. if(connssl->cred) {
  1280. Curl_ssl_sessionid_lock(conn);
  1281. Curl_schannel_session_free(connssl->cred);
  1282. Curl_ssl_sessionid_unlock(conn);
  1283. connssl->cred = NULL;
  1284. }
  1285. /* free internal buffer for received encrypted data */
  1286. if(connssl->encdata_buffer != NULL) {
  1287. Curl_safefree(connssl->encdata_buffer);
  1288. connssl->encdata_length = 0;
  1289. connssl->encdata_offset = 0;
  1290. }
  1291. /* free internal buffer for received decrypted data */
  1292. if(connssl->decdata_buffer != NULL) {
  1293. Curl_safefree(connssl->decdata_buffer);
  1294. connssl->decdata_length = 0;
  1295. connssl->decdata_offset = 0;
  1296. }
  1297. return CURLE_OK;
  1298. }
  1299. void Curl_schannel_session_free(void *ptr)
  1300. {
  1301. /* this is expected to be called under sessionid lock */
  1302. struct curl_schannel_cred *cred = ptr;
  1303. cred->refcount--;
  1304. if(cred->refcount == 0) {
  1305. s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
  1306. Curl_safefree(cred);
  1307. }
  1308. }
  1309. int Curl_schannel_init(void)
  1310. {
  1311. return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0);
  1312. }
  1313. void Curl_schannel_cleanup(void)
  1314. {
  1315. Curl_sspi_global_cleanup();
  1316. }
  1317. size_t Curl_schannel_version(char *buffer, size_t size)
  1318. {
  1319. size = snprintf(buffer, size, "WinSSL");
  1320. return size;
  1321. }
  1322. int Curl_schannel_random(unsigned char *entropy, size_t length)
  1323. {
  1324. HCRYPTPROV hCryptProv = 0;
  1325. if(!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL,
  1326. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  1327. return 1;
  1328. if(!CryptGenRandom(hCryptProv, (DWORD)length, entropy)) {
  1329. CryptReleaseContext(hCryptProv, 0UL);
  1330. return 1;
  1331. }
  1332. CryptReleaseContext(hCryptProv, 0UL);
  1333. return 0;
  1334. }
  1335. #ifdef _WIN32_WCE
  1336. static CURLcode verify_certificate(struct connectdata *conn, int sockindex)
  1337. {
  1338. SECURITY_STATUS status;
  1339. struct Curl_easy *data = conn->data;
  1340. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1341. CURLcode result = CURLE_OK;
  1342. CERT_CONTEXT *pCertContextServer = NULL;
  1343. const CERT_CHAIN_CONTEXT *pChainContext = NULL;
  1344. const char * const conn_hostname = SSL_IS_PROXY() ?
  1345. conn->http_proxy.host.name :
  1346. conn->host.name;
  1347. status = s_pSecFn->QueryContextAttributes(&connssl->ctxt->ctxt_handle,
  1348. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  1349. &pCertContextServer);
  1350. if((status != SEC_E_OK) || (pCertContextServer == NULL)) {
  1351. failf(data, "schannel: Failed to read remote certificate context: %s",
  1352. Curl_sspi_strerror(conn, status));
  1353. result = CURLE_PEER_FAILED_VERIFICATION;
  1354. }
  1355. if(result == CURLE_OK) {
  1356. CERT_CHAIN_PARA ChainPara;
  1357. memset(&ChainPara, 0, sizeof(ChainPara));
  1358. ChainPara.cbSize = sizeof(ChainPara);
  1359. if(!CertGetCertificateChain(NULL,
  1360. pCertContextServer,
  1361. NULL,
  1362. pCertContextServer->hCertStore,
  1363. &ChainPara,
  1364. (data->set.ssl.no_revoke ? 0 :
  1365. CERT_CHAIN_REVOCATION_CHECK_CHAIN),
  1366. NULL,
  1367. &pChainContext)) {
  1368. failf(data, "schannel: CertGetCertificateChain failed: %s",
  1369. Curl_sspi_strerror(conn, GetLastError()));
  1370. pChainContext = NULL;
  1371. result = CURLE_PEER_FAILED_VERIFICATION;
  1372. }
  1373. if(result == CURLE_OK) {
  1374. CERT_SIMPLE_CHAIN *pSimpleChain = pChainContext->rgpChain[0];
  1375. DWORD dwTrustErrorMask = ~(DWORD)(CERT_TRUST_IS_NOT_TIME_NESTED);
  1376. dwTrustErrorMask &= pSimpleChain->TrustStatus.dwErrorStatus;
  1377. if(dwTrustErrorMask) {
  1378. if(dwTrustErrorMask & CERT_TRUST_IS_REVOKED)
  1379. failf(data, "schannel: CertGetCertificateChain trust error"
  1380. " CERT_TRUST_IS_REVOKED");
  1381. else if(dwTrustErrorMask & CERT_TRUST_IS_PARTIAL_CHAIN)
  1382. failf(data, "schannel: CertGetCertificateChain trust error"
  1383. " CERT_TRUST_IS_PARTIAL_CHAIN");
  1384. else if(dwTrustErrorMask & CERT_TRUST_IS_UNTRUSTED_ROOT)
  1385. failf(data, "schannel: CertGetCertificateChain trust error"
  1386. " CERT_TRUST_IS_UNTRUSTED_ROOT");
  1387. else if(dwTrustErrorMask & CERT_TRUST_IS_NOT_TIME_VALID)
  1388. failf(data, "schannel: CertGetCertificateChain trust error"
  1389. " CERT_TRUST_IS_NOT_TIME_VALID");
  1390. else
  1391. failf(data, "schannel: CertGetCertificateChain error mask: 0x%08x",
  1392. dwTrustErrorMask);
  1393. result = CURLE_PEER_FAILED_VERIFICATION;
  1394. }
  1395. }
  1396. }
  1397. if(result == CURLE_OK) {
  1398. if(conn->ssl_config.verifyhost) {
  1399. TCHAR cert_hostname_buff[256];
  1400. DWORD len;
  1401. /* TODO: Fix this for certificates with multiple alternative names.
  1402. Right now we're only asking for the first preferred alternative name.
  1403. Instead we'd need to do all via CERT_NAME_SEARCH_ALL_NAMES_FLAG
  1404. (if WinCE supports that?) and run this section in a loop for each.
  1405. https://msdn.microsoft.com/en-us/library/windows/desktop/aa376086.aspx
  1406. curl: (51) schannel: CertGetNameString() certificate hostname
  1407. (.google.com) did not match connection (google.com)
  1408. */
  1409. len = CertGetNameString(pCertContextServer,
  1410. CERT_NAME_DNS_TYPE,
  1411. CERT_NAME_DISABLE_IE4_UTF8_FLAG,
  1412. NULL,
  1413. cert_hostname_buff,
  1414. 256);
  1415. if(len > 0) {
  1416. const char *cert_hostname;
  1417. /* Comparing the cert name and the connection hostname encoded as UTF-8
  1418. * is acceptable since both values are assumed to use ASCII
  1419. * (or some equivalent) encoding
  1420. */
  1421. cert_hostname = Curl_convert_tchar_to_UTF8(cert_hostname_buff);
  1422. if(!cert_hostname) {
  1423. result = CURLE_OUT_OF_MEMORY;
  1424. }
  1425. else{
  1426. int match_result;
  1427. match_result = Curl_cert_hostcheck(cert_hostname, conn->host.name);
  1428. if(match_result == CURL_HOST_MATCH) {
  1429. infof(data,
  1430. "schannel: connection hostname (%s) validated "
  1431. "against certificate name (%s)\n",
  1432. conn->host.name,
  1433. cert_hostname);
  1434. result = CURLE_OK;
  1435. }
  1436. else{
  1437. failf(data,
  1438. "schannel: connection hostname (%s) "
  1439. "does not match certificate name (%s)",
  1440. conn->host.name,
  1441. cert_hostname);
  1442. result = CURLE_PEER_FAILED_VERIFICATION;
  1443. }
  1444. Curl_unicodefree(cert_hostname);
  1445. }
  1446. }
  1447. else {
  1448. failf(data,
  1449. "schannel: CertGetNameString did not provide any "
  1450. "certificate name information");
  1451. result = CURLE_PEER_FAILED_VERIFICATION;
  1452. }
  1453. }
  1454. }
  1455. if(pChainContext)
  1456. CertFreeCertificateChain(pChainContext);
  1457. if(pCertContextServer)
  1458. CertFreeCertificateContext(pCertContextServer);
  1459. return result;
  1460. }
  1461. #endif /* _WIN32_WCE */
  1462. #endif /* USE_SCHANNEL */