2
0

schannel.c 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) Marc Hoersken, <info@marc-hoersken.de>
  10. * Copyright (C) Mark Salisbury, <mark.salisbury@hp.com>
  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.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. * SPDX-License-Identifier: curl
  24. *
  25. ***************************************************************************/
  26. /*
  27. * Source file for all Schannel-specific code for the TLS/SSL layer. No code
  28. * but vtls.c should ever call or use these functions.
  29. */
  30. #include "curl_setup.h"
  31. #ifdef USE_SCHANNEL
  32. #ifndef USE_WINDOWS_SSPI
  33. # error "Can't compile SCHANNEL support without SSPI."
  34. #endif
  35. #include "schannel.h"
  36. #include "schannel_int.h"
  37. #include "vtls.h"
  38. #include "vtls_int.h"
  39. #include "strcase.h"
  40. #include "sendf.h"
  41. #include "connect.h" /* for the connect timeout */
  42. #include "strerror.h"
  43. #include "select.h" /* for the socket readiness */
  44. #include "inet_pton.h" /* for IP addr SNI check */
  45. #include "curl_multibyte.h"
  46. #include "warnless.h"
  47. #include "x509asn1.h"
  48. #include "curl_printf.h"
  49. #include "multiif.h"
  50. #include "version_win32.h"
  51. #include "rand.h"
  52. /* The last #include file should be: */
  53. #include "curl_memory.h"
  54. #include "memdebug.h"
  55. /* ALPN requires version 8.1 of the Windows SDK, which was
  56. shipped with Visual Studio 2013, aka _MSC_VER 1800:
  57. https://technet.microsoft.com/en-us/library/hh831771%28v=ws.11%29.aspx
  58. */
  59. #if defined(_MSC_VER) && (_MSC_VER >= 1800) && !defined(_USING_V110_SDK71_)
  60. # define HAS_ALPN 1
  61. #endif
  62. #ifndef UNISP_NAME_A
  63. #define UNISP_NAME_A "Microsoft Unified Security Protocol Provider"
  64. #endif
  65. #ifndef UNISP_NAME_W
  66. #define UNISP_NAME_W L"Microsoft Unified Security Protocol Provider"
  67. #endif
  68. #ifndef UNISP_NAME
  69. #ifdef UNICODE
  70. #define UNISP_NAME UNISP_NAME_W
  71. #else
  72. #define UNISP_NAME UNISP_NAME_A
  73. #endif
  74. #endif
  75. #ifndef BCRYPT_CHACHA20_POLY1305_ALGORITHM
  76. #define BCRYPT_CHACHA20_POLY1305_ALGORITHM L"CHACHA20_POLY1305"
  77. #endif
  78. #ifndef BCRYPT_CHAIN_MODE_CCM
  79. #define BCRYPT_CHAIN_MODE_CCM L"ChainingModeCCM"
  80. #endif
  81. #ifndef BCRYPT_CHAIN_MODE_GCM
  82. #define BCRYPT_CHAIN_MODE_GCM L"ChainingModeGCM"
  83. #endif
  84. #ifndef BCRYPT_AES_ALGORITHM
  85. #define BCRYPT_AES_ALGORITHM L"AES"
  86. #endif
  87. #ifndef BCRYPT_SHA256_ALGORITHM
  88. #define BCRYPT_SHA256_ALGORITHM L"SHA256"
  89. #endif
  90. #ifndef BCRYPT_SHA384_ALGORITHM
  91. #define BCRYPT_SHA384_ALGORITHM L"SHA384"
  92. #endif
  93. /* Workaround broken compilers like MinGW.
  94. Return the number of elements in a statically sized array.
  95. */
  96. #ifndef ARRAYSIZE
  97. #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))
  98. #endif
  99. #ifdef HAS_CLIENT_CERT_PATH
  100. #ifdef UNICODE
  101. #define CURL_CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_W
  102. #else
  103. #define CURL_CERT_STORE_PROV_SYSTEM CERT_STORE_PROV_SYSTEM_A
  104. #endif
  105. #endif
  106. #ifndef SP_PROT_SSL2_CLIENT
  107. #define SP_PROT_SSL2_CLIENT 0x00000008
  108. #endif
  109. #ifndef SP_PROT_SSL3_CLIENT
  110. #define SP_PROT_SSL3_CLIENT 0x00000008
  111. #endif
  112. #ifndef SP_PROT_TLS1_CLIENT
  113. #define SP_PROT_TLS1_CLIENT 0x00000080
  114. #endif
  115. #ifndef SP_PROT_TLS1_0_CLIENT
  116. #define SP_PROT_TLS1_0_CLIENT SP_PROT_TLS1_CLIENT
  117. #endif
  118. #ifndef SP_PROT_TLS1_1_CLIENT
  119. #define SP_PROT_TLS1_1_CLIENT 0x00000200
  120. #endif
  121. #ifndef SP_PROT_TLS1_2_CLIENT
  122. #define SP_PROT_TLS1_2_CLIENT 0x00000800
  123. #endif
  124. #ifndef SP_PROT_TLS1_3_CLIENT
  125. #define SP_PROT_TLS1_3_CLIENT 0x00002000
  126. #endif
  127. #ifndef SCH_USE_STRONG_CRYPTO
  128. #define SCH_USE_STRONG_CRYPTO 0x00400000
  129. #endif
  130. #ifndef SECBUFFER_ALERT
  131. #define SECBUFFER_ALERT 17
  132. #endif
  133. /* Both schannel buffer sizes must be > 0 */
  134. #define CURL_SCHANNEL_BUFFER_INIT_SIZE 4096
  135. #define CURL_SCHANNEL_BUFFER_FREE_SIZE 1024
  136. #define CERT_THUMBPRINT_STR_LEN 40
  137. #define CERT_THUMBPRINT_DATA_LEN 20
  138. /* Uncomment to force verbose output
  139. * #define infof(x, y, ...) printf(y, __VA_ARGS__)
  140. * #define failf(x, y, ...) printf(y, __VA_ARGS__)
  141. */
  142. #ifndef CALG_SHA_256
  143. # define CALG_SHA_256 0x0000800c
  144. #endif
  145. /* Work around typo in classic MinGW's w32api up to version 5.0,
  146. see https://osdn.net/projects/mingw/ticket/38391 */
  147. #if !defined(ALG_CLASS_DHASH) && defined(ALG_CLASS_HASH)
  148. #define ALG_CLASS_DHASH ALG_CLASS_HASH
  149. #endif
  150. #ifndef PKCS12_NO_PERSIST_KEY
  151. #define PKCS12_NO_PERSIST_KEY 0x00008000
  152. #endif
  153. static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf,
  154. struct Curl_easy *data,
  155. const char *pinnedpubkey);
  156. static void InitSecBuffer(SecBuffer *buffer, unsigned long BufType,
  157. void *BufDataPtr, unsigned long BufByteSize)
  158. {
  159. buffer->cbBuffer = BufByteSize;
  160. buffer->BufferType = BufType;
  161. buffer->pvBuffer = BufDataPtr;
  162. }
  163. static void InitSecBufferDesc(SecBufferDesc *desc, SecBuffer *BufArr,
  164. unsigned long NumArrElem)
  165. {
  166. desc->ulVersion = SECBUFFER_VERSION;
  167. desc->pBuffers = BufArr;
  168. desc->cBuffers = NumArrElem;
  169. }
  170. static CURLcode
  171. schannel_set_ssl_version_min_max(DWORD *enabled_protocols,
  172. struct Curl_cfilter *cf,
  173. struct Curl_easy *data)
  174. {
  175. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  176. long ssl_version = conn_config->version;
  177. long ssl_version_max = conn_config->version_max;
  178. long i = ssl_version;
  179. switch(ssl_version_max) {
  180. case CURL_SSLVERSION_MAX_NONE:
  181. case CURL_SSLVERSION_MAX_DEFAULT:
  182. /* Windows Server 2022 and newer (including Windows 11) support TLS 1.3
  183. built-in. Previous builds of Windows 10 had broken TLS 1.3
  184. implementations that could be enabled via registry.
  185. */
  186. if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT,
  187. VERSION_GREATER_THAN_EQUAL)) {
  188. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_3;
  189. }
  190. else /* Windows 10 and older */
  191. ssl_version_max = CURL_SSLVERSION_MAX_TLSv1_2;
  192. break;
  193. }
  194. for(; i <= (ssl_version_max >> 16); ++i) {
  195. switch(i) {
  196. case CURL_SSLVERSION_TLSv1_0:
  197. (*enabled_protocols) |= SP_PROT_TLS1_0_CLIENT;
  198. break;
  199. case CURL_SSLVERSION_TLSv1_1:
  200. (*enabled_protocols) |= SP_PROT_TLS1_1_CLIENT;
  201. break;
  202. case CURL_SSLVERSION_TLSv1_2:
  203. (*enabled_protocols) |= SP_PROT_TLS1_2_CLIENT;
  204. break;
  205. case CURL_SSLVERSION_TLSv1_3:
  206. /* Windows Server 2022 and newer */
  207. if(curlx_verify_windows_version(10, 0, 20348, PLATFORM_WINNT,
  208. VERSION_GREATER_THAN_EQUAL)) {
  209. (*enabled_protocols) |= SP_PROT_TLS1_3_CLIENT;
  210. break;
  211. }
  212. else { /* Windows 10 and older */
  213. failf(data, "schannel: TLS 1.3 not supported on Windows prior to 11");
  214. return CURLE_SSL_CONNECT_ERROR;
  215. }
  216. }
  217. }
  218. return CURLE_OK;
  219. }
  220. /* longest is 26, buffer is slightly bigger */
  221. #define LONGEST_ALG_ID 32
  222. #define CIPHEROPTION(x) {#x, x}
  223. struct algo {
  224. const char *name;
  225. int id;
  226. };
  227. static const struct algo algs[]= {
  228. CIPHEROPTION(CALG_MD2),
  229. CIPHEROPTION(CALG_MD4),
  230. CIPHEROPTION(CALG_MD5),
  231. CIPHEROPTION(CALG_SHA),
  232. CIPHEROPTION(CALG_SHA1),
  233. CIPHEROPTION(CALG_MAC),
  234. CIPHEROPTION(CALG_RSA_SIGN),
  235. CIPHEROPTION(CALG_DSS_SIGN),
  236. /* ifdefs for the options that are defined conditionally in wincrypt.h */
  237. #ifdef CALG_NO_SIGN
  238. CIPHEROPTION(CALG_NO_SIGN),
  239. #endif
  240. CIPHEROPTION(CALG_RSA_KEYX),
  241. CIPHEROPTION(CALG_DES),
  242. #ifdef CALG_3DES_112
  243. CIPHEROPTION(CALG_3DES_112),
  244. #endif
  245. CIPHEROPTION(CALG_3DES),
  246. CIPHEROPTION(CALG_DESX),
  247. CIPHEROPTION(CALG_RC2),
  248. CIPHEROPTION(CALG_RC4),
  249. CIPHEROPTION(CALG_SEAL),
  250. #ifdef CALG_DH_SF
  251. CIPHEROPTION(CALG_DH_SF),
  252. #endif
  253. CIPHEROPTION(CALG_DH_EPHEM),
  254. #ifdef CALG_AGREEDKEY_ANY
  255. CIPHEROPTION(CALG_AGREEDKEY_ANY),
  256. #endif
  257. #ifdef CALG_HUGHES_MD5
  258. CIPHEROPTION(CALG_HUGHES_MD5),
  259. #endif
  260. CIPHEROPTION(CALG_SKIPJACK),
  261. #ifdef CALG_TEK
  262. CIPHEROPTION(CALG_TEK),
  263. #endif
  264. CIPHEROPTION(CALG_CYLINK_MEK),
  265. CIPHEROPTION(CALG_SSL3_SHAMD5),
  266. #ifdef CALG_SSL3_MASTER
  267. CIPHEROPTION(CALG_SSL3_MASTER),
  268. #endif
  269. #ifdef CALG_SCHANNEL_MASTER_HASH
  270. CIPHEROPTION(CALG_SCHANNEL_MASTER_HASH),
  271. #endif
  272. #ifdef CALG_SCHANNEL_MAC_KEY
  273. CIPHEROPTION(CALG_SCHANNEL_MAC_KEY),
  274. #endif
  275. #ifdef CALG_SCHANNEL_ENC_KEY
  276. CIPHEROPTION(CALG_SCHANNEL_ENC_KEY),
  277. #endif
  278. #ifdef CALG_PCT1_MASTER
  279. CIPHEROPTION(CALG_PCT1_MASTER),
  280. #endif
  281. #ifdef CALG_SSL2_MASTER
  282. CIPHEROPTION(CALG_SSL2_MASTER),
  283. #endif
  284. #ifdef CALG_TLS1_MASTER
  285. CIPHEROPTION(CALG_TLS1_MASTER),
  286. #endif
  287. #ifdef CALG_RC5
  288. CIPHEROPTION(CALG_RC5),
  289. #endif
  290. #ifdef CALG_HMAC
  291. CIPHEROPTION(CALG_HMAC),
  292. #endif
  293. #ifdef CALG_TLS1PRF
  294. CIPHEROPTION(CALG_TLS1PRF),
  295. #endif
  296. #ifdef CALG_HASH_REPLACE_OWF
  297. CIPHEROPTION(CALG_HASH_REPLACE_OWF),
  298. #endif
  299. #ifdef CALG_AES_128
  300. CIPHEROPTION(CALG_AES_128),
  301. #endif
  302. #ifdef CALG_AES_192
  303. CIPHEROPTION(CALG_AES_192),
  304. #endif
  305. #ifdef CALG_AES_256
  306. CIPHEROPTION(CALG_AES_256),
  307. #endif
  308. #ifdef CALG_AES
  309. CIPHEROPTION(CALG_AES),
  310. #endif
  311. #ifdef CALG_SHA_256
  312. CIPHEROPTION(CALG_SHA_256),
  313. #endif
  314. #ifdef CALG_SHA_384
  315. CIPHEROPTION(CALG_SHA_384),
  316. #endif
  317. #ifdef CALG_SHA_512
  318. CIPHEROPTION(CALG_SHA_512),
  319. #endif
  320. #ifdef CALG_ECDH
  321. CIPHEROPTION(CALG_ECDH),
  322. #endif
  323. #ifdef CALG_ECMQV
  324. CIPHEROPTION(CALG_ECMQV),
  325. #endif
  326. #ifdef CALG_ECDSA
  327. CIPHEROPTION(CALG_ECDSA),
  328. #endif
  329. #ifdef CALG_ECDH_EPHEM
  330. CIPHEROPTION(CALG_ECDH_EPHEM),
  331. #endif
  332. {NULL, 0},
  333. };
  334. static int
  335. get_alg_id_by_name(char *name)
  336. {
  337. char *nameEnd = strchr(name, ':');
  338. size_t n = nameEnd ? (size_t)(nameEnd - name) : strlen(name);
  339. int i;
  340. for(i = 0; algs[i].name; i++) {
  341. if((n == strlen(algs[i].name) && !strncmp(algs[i].name, name, n)))
  342. return algs[i].id;
  343. }
  344. return 0; /* not found */
  345. }
  346. #define NUM_CIPHERS 47 /* There are 47 options listed above */
  347. static CURLcode
  348. set_ssl_ciphers(SCHANNEL_CRED *schannel_cred, char *ciphers,
  349. ALG_ID *algIds)
  350. {
  351. char *startCur = ciphers;
  352. int algCount = 0;
  353. while(startCur && (0 != *startCur) && (algCount < NUM_CIPHERS)) {
  354. long alg = strtol(startCur, 0, 0);
  355. if(!alg)
  356. alg = get_alg_id_by_name(startCur);
  357. if(alg)
  358. algIds[algCount++] = alg;
  359. else if(!strncmp(startCur, "USE_STRONG_CRYPTO",
  360. sizeof("USE_STRONG_CRYPTO") - 1) ||
  361. !strncmp(startCur, "SCH_USE_STRONG_CRYPTO",
  362. sizeof("SCH_USE_STRONG_CRYPTO") - 1))
  363. schannel_cred->dwFlags |= SCH_USE_STRONG_CRYPTO;
  364. else
  365. return CURLE_SSL_CIPHER;
  366. startCur = strchr(startCur, ':');
  367. if(startCur)
  368. startCur++;
  369. }
  370. schannel_cred->palgSupportedAlgs = algIds;
  371. schannel_cred->cSupportedAlgs = algCount;
  372. return CURLE_OK;
  373. }
  374. #ifdef HAS_CLIENT_CERT_PATH
  375. /* Function allocates memory for store_path only if CURLE_OK is returned */
  376. static CURLcode
  377. get_cert_location(TCHAR *path, DWORD *store_name, TCHAR **store_path,
  378. TCHAR **thumbprint)
  379. {
  380. TCHAR *sep;
  381. TCHAR *store_path_start;
  382. size_t store_name_len;
  383. sep = _tcschr(path, TEXT('\\'));
  384. if(!sep)
  385. return CURLE_SSL_CERTPROBLEM;
  386. store_name_len = sep - path;
  387. if(_tcsncmp(path, TEXT("CurrentUser"), store_name_len) == 0)
  388. *store_name = CERT_SYSTEM_STORE_CURRENT_USER;
  389. else if(_tcsncmp(path, TEXT("LocalMachine"), store_name_len) == 0)
  390. *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE;
  391. else if(_tcsncmp(path, TEXT("CurrentService"), store_name_len) == 0)
  392. *store_name = CERT_SYSTEM_STORE_CURRENT_SERVICE;
  393. else if(_tcsncmp(path, TEXT("Services"), store_name_len) == 0)
  394. *store_name = CERT_SYSTEM_STORE_SERVICES;
  395. else if(_tcsncmp(path, TEXT("Users"), store_name_len) == 0)
  396. *store_name = CERT_SYSTEM_STORE_USERS;
  397. else if(_tcsncmp(path, TEXT("CurrentUserGroupPolicy"),
  398. store_name_len) == 0)
  399. *store_name = CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY;
  400. else if(_tcsncmp(path, TEXT("LocalMachineGroupPolicy"),
  401. store_name_len) == 0)
  402. *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY;
  403. else if(_tcsncmp(path, TEXT("LocalMachineEnterprise"),
  404. store_name_len) == 0)
  405. *store_name = CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE;
  406. else
  407. return CURLE_SSL_CERTPROBLEM;
  408. store_path_start = sep + 1;
  409. sep = _tcschr(store_path_start, TEXT('\\'));
  410. if(!sep)
  411. return CURLE_SSL_CERTPROBLEM;
  412. *thumbprint = sep + 1;
  413. if(_tcslen(*thumbprint) != CERT_THUMBPRINT_STR_LEN)
  414. return CURLE_SSL_CERTPROBLEM;
  415. *sep = TEXT('\0');
  416. *store_path = _tcsdup(store_path_start);
  417. *sep = TEXT('\\');
  418. if(!*store_path)
  419. return CURLE_OUT_OF_MEMORY;
  420. return CURLE_OK;
  421. }
  422. #endif
  423. static CURLcode
  424. schannel_acquire_credential_handle(struct Curl_cfilter *cf,
  425. struct Curl_easy *data)
  426. {
  427. struct ssl_connect_data *connssl = cf->ctx;
  428. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  429. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  430. #ifdef HAS_CLIENT_CERT_PATH
  431. PCCERT_CONTEXT client_certs[1] = { NULL };
  432. HCERTSTORE client_cert_store = NULL;
  433. #endif
  434. SECURITY_STATUS sspi_status = SEC_E_OK;
  435. CURLcode result;
  436. /* setup Schannel API options */
  437. DWORD flags = 0;
  438. DWORD enabled_protocols = 0;
  439. struct schannel_ssl_backend_data *backend =
  440. (struct schannel_ssl_backend_data *)(connssl->backend);
  441. DEBUGASSERT(backend);
  442. if(conn_config->verifypeer) {
  443. #ifdef HAS_MANUAL_VERIFY_API
  444. if(backend->use_manual_cred_validation)
  445. flags = SCH_CRED_MANUAL_CRED_VALIDATION;
  446. else
  447. #endif
  448. flags = SCH_CRED_AUTO_CRED_VALIDATION;
  449. if(ssl_config->no_revoke) {
  450. flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  451. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  452. DEBUGF(infof(data, "schannel: disabled server certificate revocation "
  453. "checks"));
  454. }
  455. else if(ssl_config->revoke_best_effort) {
  456. flags |= SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  457. SCH_CRED_IGNORE_REVOCATION_OFFLINE | SCH_CRED_REVOCATION_CHECK_CHAIN;
  458. DEBUGF(infof(data, "schannel: ignore revocation offline errors"));
  459. }
  460. else {
  461. flags |= SCH_CRED_REVOCATION_CHECK_CHAIN;
  462. DEBUGF(infof(data,
  463. "schannel: checking server certificate revocation"));
  464. }
  465. }
  466. else {
  467. flags = SCH_CRED_MANUAL_CRED_VALIDATION |
  468. SCH_CRED_IGNORE_NO_REVOCATION_CHECK |
  469. SCH_CRED_IGNORE_REVOCATION_OFFLINE;
  470. DEBUGF(infof(data,
  471. "schannel: disabled server cert revocation checks"));
  472. }
  473. if(!conn_config->verifyhost) {
  474. flags |= SCH_CRED_NO_SERVERNAME_CHECK;
  475. DEBUGF(infof(data, "schannel: verifyhost setting prevents Schannel from "
  476. "comparing the supplied target name with the subject "
  477. "names in server certificates."));
  478. }
  479. if(!ssl_config->auto_client_cert) {
  480. flags &= ~SCH_CRED_USE_DEFAULT_CREDS;
  481. flags |= SCH_CRED_NO_DEFAULT_CREDS;
  482. infof(data, "schannel: disabled automatic use of client certificate");
  483. }
  484. else
  485. infof(data, "schannel: enabled automatic use of client certificate");
  486. switch(conn_config->version) {
  487. case CURL_SSLVERSION_DEFAULT:
  488. case CURL_SSLVERSION_TLSv1:
  489. case CURL_SSLVERSION_TLSv1_0:
  490. case CURL_SSLVERSION_TLSv1_1:
  491. case CURL_SSLVERSION_TLSv1_2:
  492. case CURL_SSLVERSION_TLSv1_3:
  493. {
  494. result = schannel_set_ssl_version_min_max(&enabled_protocols, cf, data);
  495. if(result != CURLE_OK)
  496. return result;
  497. break;
  498. }
  499. case CURL_SSLVERSION_SSLv3:
  500. case CURL_SSLVERSION_SSLv2:
  501. failf(data, "SSL versions not supported");
  502. return CURLE_NOT_BUILT_IN;
  503. default:
  504. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  505. return CURLE_SSL_CONNECT_ERROR;
  506. }
  507. #ifdef HAS_CLIENT_CERT_PATH
  508. /* client certificate */
  509. if(data->set.ssl.primary.clientcert || data->set.ssl.primary.cert_blob) {
  510. DWORD cert_store_name = 0;
  511. TCHAR *cert_store_path = NULL;
  512. TCHAR *cert_thumbprint_str = NULL;
  513. CRYPT_HASH_BLOB cert_thumbprint;
  514. BYTE cert_thumbprint_data[CERT_THUMBPRINT_DATA_LEN];
  515. HCERTSTORE cert_store = NULL;
  516. FILE *fInCert = NULL;
  517. void *certdata = NULL;
  518. size_t certsize = 0;
  519. bool blob = data->set.ssl.primary.cert_blob != NULL;
  520. TCHAR *cert_path = NULL;
  521. if(blob) {
  522. certdata = data->set.ssl.primary.cert_blob->data;
  523. certsize = data->set.ssl.primary.cert_blob->len;
  524. }
  525. else {
  526. cert_path = curlx_convert_UTF8_to_tchar(
  527. data->set.ssl.primary.clientcert);
  528. if(!cert_path)
  529. return CURLE_OUT_OF_MEMORY;
  530. result = get_cert_location(cert_path, &cert_store_name,
  531. &cert_store_path, &cert_thumbprint_str);
  532. if(result && (data->set.ssl.primary.clientcert[0]!='\0'))
  533. fInCert = fopen(data->set.ssl.primary.clientcert, "rb");
  534. if(result && !fInCert) {
  535. failf(data, "schannel: Failed to get certificate location"
  536. " or file for %s",
  537. data->set.ssl.primary.clientcert);
  538. curlx_unicodefree(cert_path);
  539. return result;
  540. }
  541. }
  542. if((fInCert || blob) && (data->set.ssl.cert_type) &&
  543. (!strcasecompare(data->set.ssl.cert_type, "P12"))) {
  544. failf(data, "schannel: certificate format compatibility error "
  545. " for %s",
  546. blob ? "(memory blob)" : data->set.ssl.primary.clientcert);
  547. curlx_unicodefree(cert_path);
  548. return CURLE_SSL_CERTPROBLEM;
  549. }
  550. if(fInCert || blob) {
  551. /* Reading a .P12 or .pfx file, like the example at bottom of
  552. https://social.msdn.microsoft.com/Forums/windowsdesktop/
  553. en-US/3e7bc95f-b21a-4bcd-bd2c-7f996718cae5
  554. */
  555. CRYPT_DATA_BLOB datablob;
  556. WCHAR* pszPassword;
  557. size_t pwd_len = 0;
  558. int str_w_len = 0;
  559. const char *cert_showfilename_error = blob ?
  560. "(memory blob)" : data->set.ssl.primary.clientcert;
  561. curlx_unicodefree(cert_path);
  562. if(fInCert) {
  563. long cert_tell = 0;
  564. bool continue_reading = fseek(fInCert, 0, SEEK_END) == 0;
  565. if(continue_reading)
  566. cert_tell = ftell(fInCert);
  567. if(cert_tell < 0)
  568. continue_reading = FALSE;
  569. else
  570. certsize = (size_t)cert_tell;
  571. if(continue_reading)
  572. continue_reading = fseek(fInCert, 0, SEEK_SET) == 0;
  573. if(continue_reading)
  574. certdata = malloc(certsize + 1);
  575. if((!certdata) ||
  576. ((int) fread(certdata, certsize, 1, fInCert) != 1))
  577. continue_reading = FALSE;
  578. fclose(fInCert);
  579. if(!continue_reading) {
  580. failf(data, "schannel: Failed to read cert file %s",
  581. data->set.ssl.primary.clientcert);
  582. free(certdata);
  583. return CURLE_SSL_CERTPROBLEM;
  584. }
  585. }
  586. /* Convert key-pair data to the in-memory certificate store */
  587. datablob.pbData = (BYTE*)certdata;
  588. datablob.cbData = (DWORD)certsize;
  589. if(data->set.ssl.key_passwd)
  590. pwd_len = strlen(data->set.ssl.key_passwd);
  591. pszPassword = (WCHAR*)malloc(sizeof(WCHAR)*(pwd_len + 1));
  592. if(pszPassword) {
  593. if(pwd_len > 0)
  594. str_w_len = MultiByteToWideChar(CP_UTF8,
  595. MB_ERR_INVALID_CHARS,
  596. data->set.ssl.key_passwd,
  597. (int)pwd_len,
  598. pszPassword, (int)(pwd_len + 1));
  599. if((str_w_len >= 0) && (str_w_len <= (int)pwd_len))
  600. pszPassword[str_w_len] = 0;
  601. else
  602. pszPassword[0] = 0;
  603. if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT,
  604. VERSION_GREATER_THAN_EQUAL))
  605. cert_store = PFXImportCertStore(&datablob, pszPassword,
  606. PKCS12_NO_PERSIST_KEY);
  607. else
  608. cert_store = PFXImportCertStore(&datablob, pszPassword, 0);
  609. free(pszPassword);
  610. }
  611. if(!blob)
  612. free(certdata);
  613. if(!cert_store) {
  614. DWORD errorcode = GetLastError();
  615. if(errorcode == ERROR_INVALID_PASSWORD)
  616. failf(data, "schannel: Failed to import cert file %s, "
  617. "password is bad",
  618. cert_showfilename_error);
  619. else
  620. failf(data, "schannel: Failed to import cert file %s, "
  621. "last error is 0x%x",
  622. cert_showfilename_error, errorcode);
  623. return CURLE_SSL_CERTPROBLEM;
  624. }
  625. client_certs[0] = CertFindCertificateInStore(
  626. cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
  627. CERT_FIND_ANY, NULL, NULL);
  628. if(!client_certs[0]) {
  629. failf(data, "schannel: Failed to get certificate from file %s"
  630. ", last error is 0x%x",
  631. cert_showfilename_error, GetLastError());
  632. CertCloseStore(cert_store, 0);
  633. return CURLE_SSL_CERTPROBLEM;
  634. }
  635. }
  636. else {
  637. cert_store =
  638. CertOpenStore(CURL_CERT_STORE_PROV_SYSTEM, 0,
  639. (HCRYPTPROV)NULL,
  640. CERT_STORE_OPEN_EXISTING_FLAG | cert_store_name,
  641. cert_store_path);
  642. if(!cert_store) {
  643. failf(data, "schannel: Failed to open cert store %x %s, "
  644. "last error is 0x%x",
  645. cert_store_name, cert_store_path, GetLastError());
  646. free(cert_store_path);
  647. curlx_unicodefree(cert_path);
  648. return CURLE_SSL_CERTPROBLEM;
  649. }
  650. free(cert_store_path);
  651. cert_thumbprint.pbData = cert_thumbprint_data;
  652. cert_thumbprint.cbData = CERT_THUMBPRINT_DATA_LEN;
  653. if(!CryptStringToBinary(cert_thumbprint_str,
  654. CERT_THUMBPRINT_STR_LEN,
  655. CRYPT_STRING_HEX,
  656. cert_thumbprint_data,
  657. &cert_thumbprint.cbData,
  658. NULL, NULL)) {
  659. curlx_unicodefree(cert_path);
  660. CertCloseStore(cert_store, 0);
  661. return CURLE_SSL_CERTPROBLEM;
  662. }
  663. client_certs[0] = CertFindCertificateInStore(
  664. cert_store, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0,
  665. CERT_FIND_HASH, &cert_thumbprint, NULL);
  666. curlx_unicodefree(cert_path);
  667. if(!client_certs[0]) {
  668. /* CRYPT_E_NOT_FOUND / E_INVALIDARG */
  669. CertCloseStore(cert_store, 0);
  670. return CURLE_SSL_CERTPROBLEM;
  671. }
  672. }
  673. client_cert_store = cert_store;
  674. }
  675. #else
  676. if(data->set.ssl.primary.clientcert || data->set.ssl.primary.cert_blob) {
  677. failf(data, "schannel: client cert support not built in");
  678. return CURLE_NOT_BUILT_IN;
  679. }
  680. #endif
  681. /* allocate memory for the re-usable credential handle */
  682. backend->cred = (struct Curl_schannel_cred *)
  683. calloc(1, sizeof(struct Curl_schannel_cred));
  684. if(!backend->cred) {
  685. failf(data, "schannel: unable to allocate memory");
  686. #ifdef HAS_CLIENT_CERT_PATH
  687. if(client_certs[0])
  688. CertFreeCertificateContext(client_certs[0]);
  689. if(client_cert_store)
  690. CertCloseStore(client_cert_store, 0);
  691. #endif
  692. return CURLE_OUT_OF_MEMORY;
  693. }
  694. backend->cred->refcount = 1;
  695. #ifdef HAS_CLIENT_CERT_PATH
  696. /* Since we did not persist the key, we need to extend the store's
  697. * lifetime until the end of the connection
  698. */
  699. backend->cred->client_cert_store = client_cert_store;
  700. #endif
  701. /* Windows 10, 1809 (a.k.a. Windows 10 build 17763) */
  702. if(curlx_verify_windows_version(10, 0, 17763, PLATFORM_WINNT,
  703. VERSION_GREATER_THAN_EQUAL)) {
  704. char *ciphers13 = 0;
  705. bool disable_aes_gcm_sha384 = FALSE;
  706. bool disable_aes_gcm_sha256 = FALSE;
  707. bool disable_chacha_poly = FALSE;
  708. bool disable_aes_ccm_8_sha256 = FALSE;
  709. bool disable_aes_ccm_sha256 = FALSE;
  710. SCH_CREDENTIALS credentials = { 0 };
  711. TLS_PARAMETERS tls_parameters = { 0 };
  712. CRYPTO_SETTINGS crypto_settings[4] = { 0 };
  713. UNICODE_STRING blocked_ccm_modes[1] = { 0 };
  714. UNICODE_STRING blocked_gcm_modes[1] = { 0 };
  715. int crypto_settings_idx = 0;
  716. /* If TLS 1.3 ciphers are explicitly listed, then
  717. * disable all the ciphers and re-enable which
  718. * ciphers the user has provided.
  719. */
  720. ciphers13 = conn_config->cipher_list13;
  721. if(ciphers13) {
  722. const int remaining_ciphers = 5;
  723. /* detect which remaining ciphers to enable
  724. and then disable everything else.
  725. */
  726. char *startCur = ciphers13;
  727. int algCount = 0;
  728. char tmp[LONGEST_ALG_ID] = { 0 };
  729. char *nameEnd;
  730. size_t n;
  731. disable_aes_gcm_sha384 = TRUE;
  732. disable_aes_gcm_sha256 = TRUE;
  733. disable_chacha_poly = TRUE;
  734. disable_aes_ccm_8_sha256 = TRUE;
  735. disable_aes_ccm_sha256 = TRUE;
  736. while(startCur && (0 != *startCur) && (algCount < remaining_ciphers)) {
  737. nameEnd = strchr(startCur, ':');
  738. n = nameEnd ? (size_t)(nameEnd - startCur) : strlen(startCur);
  739. /* reject too-long cipher names */
  740. if(n > (LONGEST_ALG_ID - 1)) {
  741. failf(data, "Cipher name too long, not checked.");
  742. return CURLE_SSL_CIPHER;
  743. }
  744. strncpy(tmp, startCur, n);
  745. tmp[n] = 0;
  746. if(disable_aes_gcm_sha384
  747. && !strcmp("TLS_AES_256_GCM_SHA384", tmp)) {
  748. disable_aes_gcm_sha384 = FALSE;
  749. }
  750. else if(disable_aes_gcm_sha256
  751. && !strcmp("TLS_AES_128_GCM_SHA256", tmp)) {
  752. disable_aes_gcm_sha256 = FALSE;
  753. }
  754. else if(disable_chacha_poly
  755. && !strcmp("TLS_CHACHA20_POLY1305_SHA256", tmp)) {
  756. disable_chacha_poly = FALSE;
  757. }
  758. else if(disable_aes_ccm_8_sha256
  759. && !strcmp("TLS_AES_128_CCM_8_SHA256", tmp)) {
  760. disable_aes_ccm_8_sha256 = FALSE;
  761. }
  762. else if(disable_aes_ccm_sha256
  763. && !strcmp("TLS_AES_128_CCM_SHA256", tmp)) {
  764. disable_aes_ccm_sha256 = FALSE;
  765. }
  766. else {
  767. failf(data, "Passed in an unknown TLS 1.3 cipher.");
  768. return CURLE_SSL_CIPHER;
  769. }
  770. startCur = nameEnd;
  771. if(startCur)
  772. startCur++;
  773. algCount++;
  774. }
  775. }
  776. if(disable_aes_gcm_sha384 && disable_aes_gcm_sha256
  777. && disable_chacha_poly && disable_aes_ccm_8_sha256
  778. && disable_aes_ccm_sha256) {
  779. failf(data, "All available TLS 1.3 ciphers were disabled.");
  780. return CURLE_SSL_CIPHER;
  781. }
  782. /* Disable TLS_AES_128_CCM_8_SHA256 and/or TLS_AES_128_CCM_SHA256 */
  783. if(disable_aes_ccm_8_sha256 || disable_aes_ccm_sha256) {
  784. /*
  785. Disallow AES_CCM algorithm.
  786. */
  787. blocked_ccm_modes[0].Length = sizeof(BCRYPT_CHAIN_MODE_CCM);
  788. blocked_ccm_modes[0].MaximumLength = sizeof(BCRYPT_CHAIN_MODE_CCM);
  789. blocked_ccm_modes[0].Buffer = (PWSTR)BCRYPT_CHAIN_MODE_CCM;
  790. crypto_settings[crypto_settings_idx].eAlgorithmUsage =
  791. TlsParametersCngAlgUsageCipher;
  792. crypto_settings[crypto_settings_idx].rgstrChainingModes =
  793. blocked_ccm_modes;
  794. crypto_settings[crypto_settings_idx].cChainingModes =
  795. ARRAYSIZE(blocked_ccm_modes);
  796. crypto_settings[crypto_settings_idx].strCngAlgId.Length =
  797. sizeof(BCRYPT_AES_ALGORITHM);
  798. crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength =
  799. sizeof(BCRYPT_AES_ALGORITHM);
  800. crypto_settings[crypto_settings_idx].strCngAlgId.Buffer =
  801. (PWSTR)BCRYPT_AES_ALGORITHM;
  802. /* only disabling one of the CCM modes */
  803. if(disable_aes_ccm_8_sha256 != disable_aes_ccm_sha256) {
  804. if(disable_aes_ccm_8_sha256)
  805. crypto_settings[crypto_settings_idx].dwMinBitLength = 128;
  806. else /* disable_aes_ccm_sha256 */
  807. crypto_settings[crypto_settings_idx].dwMaxBitLength = 64;
  808. }
  809. crypto_settings_idx++;
  810. }
  811. /* Disable TLS_AES_256_GCM_SHA384 and/or TLS_AES_128_GCM_SHA256 */
  812. if(disable_aes_gcm_sha384 || disable_aes_gcm_sha256) {
  813. /*
  814. Disallow AES_GCM algorithm
  815. */
  816. blocked_gcm_modes[0].Length = sizeof(BCRYPT_CHAIN_MODE_GCM);
  817. blocked_gcm_modes[0].MaximumLength = sizeof(BCRYPT_CHAIN_MODE_GCM);
  818. blocked_gcm_modes[0].Buffer = (PWSTR)BCRYPT_CHAIN_MODE_GCM;
  819. /* if only one is disabled, then explicitly disable the
  820. digest cipher suite (sha384 or sha256) */
  821. if(disable_aes_gcm_sha384 != disable_aes_gcm_sha256) {
  822. crypto_settings[crypto_settings_idx].eAlgorithmUsage =
  823. TlsParametersCngAlgUsageDigest;
  824. crypto_settings[crypto_settings_idx].strCngAlgId.Length =
  825. sizeof(disable_aes_gcm_sha384 ?
  826. BCRYPT_SHA384_ALGORITHM : BCRYPT_SHA256_ALGORITHM);
  827. crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength =
  828. sizeof(disable_aes_gcm_sha384 ?
  829. BCRYPT_SHA384_ALGORITHM : BCRYPT_SHA256_ALGORITHM);
  830. crypto_settings[crypto_settings_idx].strCngAlgId.Buffer =
  831. (PWSTR)(disable_aes_gcm_sha384 ?
  832. BCRYPT_SHA384_ALGORITHM : BCRYPT_SHA256_ALGORITHM);
  833. }
  834. else { /* Disable both AES_GCM ciphers */
  835. crypto_settings[crypto_settings_idx].eAlgorithmUsage =
  836. TlsParametersCngAlgUsageCipher;
  837. crypto_settings[crypto_settings_idx].strCngAlgId.Length =
  838. sizeof(BCRYPT_AES_ALGORITHM);
  839. crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength =
  840. sizeof(BCRYPT_AES_ALGORITHM);
  841. crypto_settings[crypto_settings_idx].strCngAlgId.Buffer =
  842. (PWSTR)BCRYPT_AES_ALGORITHM;
  843. }
  844. crypto_settings[crypto_settings_idx].rgstrChainingModes =
  845. blocked_gcm_modes;
  846. crypto_settings[crypto_settings_idx].cChainingModes = 1;
  847. crypto_settings_idx++;
  848. }
  849. /*
  850. Disable ChaCha20-Poly1305.
  851. */
  852. if(disable_chacha_poly) {
  853. crypto_settings[crypto_settings_idx].eAlgorithmUsage =
  854. TlsParametersCngAlgUsageCipher;
  855. crypto_settings[crypto_settings_idx].strCngAlgId.Length =
  856. sizeof(BCRYPT_CHACHA20_POLY1305_ALGORITHM);
  857. crypto_settings[crypto_settings_idx].strCngAlgId.MaximumLength =
  858. sizeof(BCRYPT_CHACHA20_POLY1305_ALGORITHM);
  859. crypto_settings[crypto_settings_idx].strCngAlgId.Buffer =
  860. (PWSTR)BCRYPT_CHACHA20_POLY1305_ALGORITHM;
  861. crypto_settings_idx++;
  862. }
  863. tls_parameters.pDisabledCrypto = crypto_settings;
  864. /* The number of blocked suites */
  865. tls_parameters.cDisabledCrypto = crypto_settings_idx;
  866. credentials.pTlsParameters = &tls_parameters;
  867. credentials.cTlsParameters = 1;
  868. credentials.dwVersion = SCH_CREDENTIALS_VERSION;
  869. credentials.dwFlags = flags | SCH_USE_STRONG_CRYPTO;
  870. credentials.pTlsParameters->grbitDisabledProtocols =
  871. (DWORD)~enabled_protocols;
  872. #ifdef HAS_CLIENT_CERT_PATH
  873. if(client_certs[0]) {
  874. credentials.cCreds = 1;
  875. credentials.paCred = client_certs;
  876. }
  877. #endif
  878. sspi_status =
  879. s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR*)UNISP_NAME,
  880. SECPKG_CRED_OUTBOUND, NULL,
  881. &credentials, NULL, NULL,
  882. &backend->cred->cred_handle,
  883. &backend->cred->time_stamp);
  884. }
  885. else {
  886. /* Pre-Windows 10 1809 */
  887. ALG_ID algIds[NUM_CIPHERS];
  888. char *ciphers = conn_config->cipher_list;
  889. SCHANNEL_CRED schannel_cred = { 0 };
  890. schannel_cred.dwVersion = SCHANNEL_CRED_VERSION;
  891. schannel_cred.dwFlags = flags;
  892. schannel_cred.grbitEnabledProtocols = enabled_protocols;
  893. if(ciphers) {
  894. result = set_ssl_ciphers(&schannel_cred, ciphers, algIds);
  895. if(CURLE_OK != result) {
  896. failf(data, "Unable to set ciphers to from connection ssl config");
  897. return result;
  898. }
  899. }
  900. else {
  901. schannel_cred.dwFlags = flags | SCH_USE_STRONG_CRYPTO;
  902. }
  903. #ifdef HAS_CLIENT_CERT_PATH
  904. if(client_certs[0]) {
  905. schannel_cred.cCreds = 1;
  906. schannel_cred.paCred = client_certs;
  907. }
  908. #endif
  909. sspi_status =
  910. s_pSecFn->AcquireCredentialsHandle(NULL, (TCHAR*)UNISP_NAME,
  911. SECPKG_CRED_OUTBOUND, NULL,
  912. &schannel_cred, NULL, NULL,
  913. &backend->cred->cred_handle,
  914. &backend->cred->time_stamp);
  915. }
  916. #ifdef HAS_CLIENT_CERT_PATH
  917. if(client_certs[0])
  918. CertFreeCertificateContext(client_certs[0]);
  919. #endif
  920. if(sspi_status != SEC_E_OK) {
  921. char buffer[STRERROR_LEN];
  922. failf(data, "schannel: AcquireCredentialsHandle failed: %s",
  923. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  924. Curl_safefree(backend->cred);
  925. switch(sspi_status) {
  926. case SEC_E_INSUFFICIENT_MEMORY:
  927. return CURLE_OUT_OF_MEMORY;
  928. case SEC_E_NO_CREDENTIALS:
  929. case SEC_E_SECPKG_NOT_FOUND:
  930. case SEC_E_NOT_OWNER:
  931. case SEC_E_UNKNOWN_CREDENTIALS:
  932. case SEC_E_INTERNAL_ERROR:
  933. default:
  934. return CURLE_SSL_CONNECT_ERROR;
  935. }
  936. }
  937. return CURLE_OK;
  938. }
  939. static CURLcode
  940. schannel_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)
  941. {
  942. ssize_t written = -1;
  943. struct ssl_connect_data *connssl = cf->ctx;
  944. struct schannel_ssl_backend_data *backend =
  945. (struct schannel_ssl_backend_data *)connssl->backend;
  946. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  947. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  948. SecBuffer outbuf;
  949. SecBufferDesc outbuf_desc;
  950. SecBuffer inbuf;
  951. SecBufferDesc inbuf_desc;
  952. #ifdef HAS_ALPN
  953. unsigned char alpn_buffer[128];
  954. #endif
  955. SECURITY_STATUS sspi_status = SEC_E_OK;
  956. struct Curl_schannel_cred *old_cred = NULL;
  957. struct in_addr addr;
  958. #ifdef ENABLE_IPV6
  959. struct in6_addr addr6;
  960. #endif
  961. CURLcode result;
  962. const char *hostname = connssl->hostname;
  963. DEBUGASSERT(backend);
  964. DEBUGF(infof(data,
  965. "schannel: SSL/TLS connection with %s port %d (step 1/3)",
  966. hostname, connssl->port));
  967. if(curlx_verify_windows_version(5, 1, 0, PLATFORM_WINNT,
  968. VERSION_LESS_THAN_EQUAL)) {
  969. /* Schannel in Windows XP (OS version 5.1) uses legacy handshakes and
  970. algorithms that may not be supported by all servers. */
  971. infof(data, "schannel: Windows version is old and may not be able to "
  972. "connect to some servers due to lack of SNI, algorithms, etc.");
  973. }
  974. #ifdef HAS_ALPN
  975. /* ALPN is only supported on Windows 8.1 / Server 2012 R2 and above.
  976. Also it doesn't seem to be supported for Wine, see curl bug #983. */
  977. backend->use_alpn = connssl->alpn &&
  978. !GetProcAddress(GetModuleHandle(TEXT("ntdll")),
  979. "wine_get_version") &&
  980. curlx_verify_windows_version(6, 3, 0, PLATFORM_WINNT,
  981. VERSION_GREATER_THAN_EQUAL);
  982. #else
  983. backend->use_alpn = false;
  984. #endif
  985. #ifdef _WIN32_WCE
  986. #ifdef HAS_MANUAL_VERIFY_API
  987. /* certificate validation on CE doesn't seem to work right; we'll
  988. * do it following a more manual process. */
  989. backend->use_manual_cred_validation = true;
  990. #else
  991. #error "compiler too old to support requisite manual cert verify for Win CE"
  992. #endif
  993. #else
  994. #ifdef HAS_MANUAL_VERIFY_API
  995. if(conn_config->CAfile || conn_config->ca_info_blob) {
  996. if(curlx_verify_windows_version(6, 1, 0, PLATFORM_WINNT,
  997. VERSION_GREATER_THAN_EQUAL)) {
  998. backend->use_manual_cred_validation = true;
  999. }
  1000. else {
  1001. failf(data, "schannel: this version of Windows is too old to support "
  1002. "certificate verification via CA bundle file.");
  1003. return CURLE_SSL_CACERT_BADFILE;
  1004. }
  1005. }
  1006. else
  1007. backend->use_manual_cred_validation = false;
  1008. #else
  1009. if(conn_config->CAfile || conn_config->ca_info_blob) {
  1010. failf(data, "schannel: CA cert support not built in");
  1011. return CURLE_NOT_BUILT_IN;
  1012. }
  1013. #endif
  1014. #endif
  1015. backend->cred = NULL;
  1016. /* check for an existing re-usable credential handle */
  1017. if(ssl_config->primary.sessionid) {
  1018. Curl_ssl_sessionid_lock(data);
  1019. if(!Curl_ssl_getsessionid(cf, data, (void **)&old_cred, NULL)) {
  1020. backend->cred = old_cred;
  1021. DEBUGF(infof(data, "schannel: re-using existing credential handle"));
  1022. /* increment the reference counter of the credential/session handle */
  1023. backend->cred->refcount++;
  1024. DEBUGF(infof(data,
  1025. "schannel: incremented credential handle refcount = %d",
  1026. backend->cred->refcount));
  1027. }
  1028. Curl_ssl_sessionid_unlock(data);
  1029. }
  1030. if(!backend->cred) {
  1031. char *snihost;
  1032. result = schannel_acquire_credential_handle(cf, data);
  1033. if(result)
  1034. return result;
  1035. /* schannel_acquire_credential_handle() sets backend->cred accordingly or
  1036. it returns error otherwise. */
  1037. /* A hostname associated with the credential is needed by
  1038. InitializeSecurityContext for SNI and other reasons. */
  1039. snihost = Curl_ssl_snihost(data, hostname, NULL);
  1040. if(!snihost) {
  1041. failf(data, "Failed to set SNI");
  1042. return CURLE_SSL_CONNECT_ERROR;
  1043. }
  1044. backend->cred->sni_hostname = curlx_convert_UTF8_to_tchar(snihost);
  1045. if(!backend->cred->sni_hostname)
  1046. return CURLE_OUT_OF_MEMORY;
  1047. }
  1048. /* Warn if SNI is disabled due to use of an IP address */
  1049. if(Curl_inet_pton(AF_INET, hostname, &addr)
  1050. #ifdef ENABLE_IPV6
  1051. || Curl_inet_pton(AF_INET6, hostname, &addr6)
  1052. #endif
  1053. ) {
  1054. infof(data, "schannel: using IP address, SNI is not supported by OS.");
  1055. }
  1056. #ifdef HAS_ALPN
  1057. if(backend->use_alpn) {
  1058. int cur = 0;
  1059. int list_start_index = 0;
  1060. unsigned int *extension_len = NULL;
  1061. unsigned short* list_len = NULL;
  1062. struct alpn_proto_buf proto;
  1063. /* The first four bytes will be an unsigned int indicating number
  1064. of bytes of data in the rest of the buffer. */
  1065. extension_len = (unsigned int *)(void *)(&alpn_buffer[cur]);
  1066. cur += (int)sizeof(unsigned int);
  1067. /* The next four bytes are an indicator that this buffer will contain
  1068. ALPN data, as opposed to NPN, for example. */
  1069. *(unsigned int *)(void *)&alpn_buffer[cur] =
  1070. SecApplicationProtocolNegotiationExt_ALPN;
  1071. cur += (int)sizeof(unsigned int);
  1072. /* The next two bytes will be an unsigned short indicating the number
  1073. of bytes used to list the preferred protocols. */
  1074. list_len = (unsigned short*)(void *)(&alpn_buffer[cur]);
  1075. cur += (int)sizeof(unsigned short);
  1076. list_start_index = cur;
  1077. result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);
  1078. if(result) {
  1079. failf(data, "Error setting ALPN");
  1080. return CURLE_SSL_CONNECT_ERROR;
  1081. }
  1082. memcpy(&alpn_buffer[cur], proto.data, proto.len);
  1083. cur += proto.len;
  1084. *list_len = curlx_uitous(cur - list_start_index);
  1085. *extension_len = *list_len +
  1086. (unsigned short)sizeof(unsigned int) +
  1087. (unsigned short)sizeof(unsigned short);
  1088. InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur);
  1089. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  1090. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  1091. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  1092. }
  1093. else {
  1094. InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  1095. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  1096. }
  1097. #else /* HAS_ALPN */
  1098. InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  1099. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  1100. #endif
  1101. /* setup output buffer */
  1102. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  1103. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  1104. /* security request flags */
  1105. backend->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
  1106. ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
  1107. ISC_REQ_STREAM;
  1108. if(!ssl_config->auto_client_cert) {
  1109. backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
  1110. }
  1111. /* allocate memory for the security context handle */
  1112. backend->ctxt = (struct Curl_schannel_ctxt *)
  1113. calloc(1, sizeof(struct Curl_schannel_ctxt));
  1114. if(!backend->ctxt) {
  1115. failf(data, "schannel: unable to allocate memory");
  1116. return CURLE_OUT_OF_MEMORY;
  1117. }
  1118. /* Schannel InitializeSecurityContext:
  1119. https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx
  1120. At the moment we don't pass inbuf unless we're using ALPN since we only
  1121. use it for that, and Wine (for which we currently disable ALPN) is giving
  1122. us problems with inbuf regardless. https://github.com/curl/curl/issues/983
  1123. */
  1124. sspi_status = s_pSecFn->InitializeSecurityContext(
  1125. &backend->cred->cred_handle, NULL, backend->cred->sni_hostname,
  1126. backend->req_flags, 0, 0,
  1127. (backend->use_alpn ? &inbuf_desc : NULL),
  1128. 0, &backend->ctxt->ctxt_handle,
  1129. &outbuf_desc, &backend->ret_flags, &backend->ctxt->time_stamp);
  1130. if(sspi_status != SEC_I_CONTINUE_NEEDED) {
  1131. char buffer[STRERROR_LEN];
  1132. Curl_safefree(backend->ctxt);
  1133. switch(sspi_status) {
  1134. case SEC_E_INSUFFICIENT_MEMORY:
  1135. failf(data, "schannel: initial InitializeSecurityContext failed: %s",
  1136. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1137. return CURLE_OUT_OF_MEMORY;
  1138. case SEC_E_WRONG_PRINCIPAL:
  1139. failf(data, "schannel: SNI or certificate check failed: %s",
  1140. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1141. return CURLE_PEER_FAILED_VERIFICATION;
  1142. /*
  1143. case SEC_E_INVALID_HANDLE:
  1144. case SEC_E_INVALID_TOKEN:
  1145. case SEC_E_LOGON_DENIED:
  1146. case SEC_E_TARGET_UNKNOWN:
  1147. case SEC_E_NO_AUTHENTICATING_AUTHORITY:
  1148. case SEC_E_INTERNAL_ERROR:
  1149. case SEC_E_NO_CREDENTIALS:
  1150. case SEC_E_UNSUPPORTED_FUNCTION:
  1151. case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
  1152. */
  1153. default:
  1154. failf(data, "schannel: initial InitializeSecurityContext failed: %s",
  1155. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1156. return CURLE_SSL_CONNECT_ERROR;
  1157. }
  1158. }
  1159. DEBUGF(infof(data, "schannel: sending initial handshake data: "
  1160. "sending %lu bytes.", outbuf.cbBuffer));
  1161. /* send initial handshake data which is now stored in output buffer */
  1162. written = Curl_conn_cf_send(cf->next, data,
  1163. outbuf.pvBuffer, outbuf.cbBuffer,
  1164. &result);
  1165. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  1166. if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
  1167. failf(data, "schannel: failed to send initial handshake data: "
  1168. "sent %zd of %lu bytes", written, outbuf.cbBuffer);
  1169. return CURLE_SSL_CONNECT_ERROR;
  1170. }
  1171. DEBUGF(infof(data, "schannel: sent initial handshake data: "
  1172. "sent %zd bytes", written));
  1173. backend->recv_unrecoverable_err = CURLE_OK;
  1174. backend->recv_sspi_close_notify = false;
  1175. backend->recv_connection_closed = false;
  1176. backend->recv_renegotiating = false;
  1177. backend->encdata_is_incomplete = false;
  1178. /* continue to second handshake step */
  1179. connssl->connecting_state = ssl_connect_2;
  1180. return CURLE_OK;
  1181. }
  1182. static CURLcode
  1183. schannel_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
  1184. {
  1185. struct ssl_connect_data *connssl = cf->ctx;
  1186. struct schannel_ssl_backend_data *backend =
  1187. (struct schannel_ssl_backend_data *)connssl->backend;
  1188. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1189. int i;
  1190. ssize_t nread = -1, written = -1;
  1191. unsigned char *reallocated_buffer;
  1192. SecBuffer outbuf[3];
  1193. SecBufferDesc outbuf_desc;
  1194. SecBuffer inbuf[2];
  1195. SecBufferDesc inbuf_desc;
  1196. SECURITY_STATUS sspi_status = SEC_E_OK;
  1197. CURLcode result;
  1198. bool doread;
  1199. const char *pubkey_ptr;
  1200. DEBUGASSERT(backend);
  1201. doread = (connssl->connecting_state != ssl_connect_2_writing) ? TRUE : FALSE;
  1202. DEBUGF(infof(data,
  1203. "schannel: SSL/TLS connection with %s port %d (step 2/3)",
  1204. connssl->hostname, connssl->port));
  1205. if(!backend->cred || !backend->ctxt)
  1206. return CURLE_SSL_CONNECT_ERROR;
  1207. /* buffer to store previously received and decrypted data */
  1208. if(!backend->decdata_buffer) {
  1209. backend->decdata_offset = 0;
  1210. backend->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  1211. backend->decdata_buffer = malloc(backend->decdata_length);
  1212. if(!backend->decdata_buffer) {
  1213. failf(data, "schannel: unable to allocate memory");
  1214. return CURLE_OUT_OF_MEMORY;
  1215. }
  1216. }
  1217. /* buffer to store previously received and encrypted data */
  1218. if(!backend->encdata_buffer) {
  1219. backend->encdata_is_incomplete = false;
  1220. backend->encdata_offset = 0;
  1221. backend->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  1222. backend->encdata_buffer = malloc(backend->encdata_length);
  1223. if(!backend->encdata_buffer) {
  1224. failf(data, "schannel: unable to allocate memory");
  1225. return CURLE_OUT_OF_MEMORY;
  1226. }
  1227. }
  1228. /* if we need a bigger buffer to read a full message, increase buffer now */
  1229. if(backend->encdata_length - backend->encdata_offset <
  1230. CURL_SCHANNEL_BUFFER_FREE_SIZE) {
  1231. /* increase internal encrypted data buffer */
  1232. size_t reallocated_length = backend->encdata_offset +
  1233. CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1234. reallocated_buffer = realloc(backend->encdata_buffer,
  1235. reallocated_length);
  1236. if(!reallocated_buffer) {
  1237. failf(data, "schannel: unable to re-allocate memory");
  1238. return CURLE_OUT_OF_MEMORY;
  1239. }
  1240. else {
  1241. backend->encdata_buffer = reallocated_buffer;
  1242. backend->encdata_length = reallocated_length;
  1243. }
  1244. }
  1245. for(;;) {
  1246. if(doread) {
  1247. /* read encrypted handshake data from socket */
  1248. nread = Curl_conn_cf_recv(cf->next, data,
  1249. (char *) (backend->encdata_buffer +
  1250. backend->encdata_offset),
  1251. backend->encdata_length -
  1252. backend->encdata_offset,
  1253. &result);
  1254. if(result == CURLE_AGAIN) {
  1255. if(connssl->connecting_state != ssl_connect_2_writing)
  1256. connssl->connecting_state = ssl_connect_2_reading;
  1257. DEBUGF(infof(data, "schannel: failed to receive handshake, "
  1258. "need more data"));
  1259. return CURLE_OK;
  1260. }
  1261. else if((result != CURLE_OK) || (nread == 0)) {
  1262. failf(data, "schannel: failed to receive handshake, "
  1263. "SSL/TLS connection failed");
  1264. return CURLE_SSL_CONNECT_ERROR;
  1265. }
  1266. /* increase encrypted data buffer offset */
  1267. backend->encdata_offset += nread;
  1268. backend->encdata_is_incomplete = false;
  1269. DEBUGF(infof(data, "schannel: encrypted data got %zd", nread));
  1270. }
  1271. DEBUGF(infof(data,
  1272. "schannel: encrypted data buffer: offset %zu length %zu",
  1273. backend->encdata_offset, backend->encdata_length));
  1274. /* setup input buffers */
  1275. InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(backend->encdata_offset),
  1276. curlx_uztoul(backend->encdata_offset));
  1277. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  1278. InitSecBufferDesc(&inbuf_desc, inbuf, 2);
  1279. /* setup output buffers */
  1280. InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0);
  1281. InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0);
  1282. InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0);
  1283. InitSecBufferDesc(&outbuf_desc, outbuf, 3);
  1284. if(!inbuf[0].pvBuffer) {
  1285. failf(data, "schannel: unable to allocate memory");
  1286. return CURLE_OUT_OF_MEMORY;
  1287. }
  1288. /* copy received handshake data into input buffer */
  1289. memcpy(inbuf[0].pvBuffer, backend->encdata_buffer,
  1290. backend->encdata_offset);
  1291. sspi_status = s_pSecFn->InitializeSecurityContext(
  1292. &backend->cred->cred_handle, &backend->ctxt->ctxt_handle,
  1293. backend->cred->sni_hostname, backend->req_flags,
  1294. 0, 0, &inbuf_desc, 0, NULL,
  1295. &outbuf_desc, &backend->ret_flags, &backend->ctxt->time_stamp);
  1296. /* free buffer for received handshake data */
  1297. Curl_safefree(inbuf[0].pvBuffer);
  1298. /* check if the handshake was incomplete */
  1299. if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  1300. backend->encdata_is_incomplete = true;
  1301. connssl->connecting_state = ssl_connect_2_reading;
  1302. DEBUGF(infof(data,
  1303. "schannel: received incomplete message, need more data"));
  1304. return CURLE_OK;
  1305. }
  1306. /* If the server has requested a client certificate, attempt to continue
  1307. the handshake without one. This will allow connections to servers which
  1308. request a client certificate but do not require it. */
  1309. if(sspi_status == SEC_I_INCOMPLETE_CREDENTIALS &&
  1310. !(backend->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
  1311. backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
  1312. connssl->connecting_state = ssl_connect_2_writing;
  1313. DEBUGF(infof(data,
  1314. "schannel: a client certificate has been requested"));
  1315. return CURLE_OK;
  1316. }
  1317. /* check if the handshake needs to be continued */
  1318. if(sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) {
  1319. for(i = 0; i < 3; i++) {
  1320. /* search for handshake tokens that need to be send */
  1321. if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) {
  1322. DEBUGF(infof(data, "schannel: sending next handshake data: "
  1323. "sending %lu bytes.", outbuf[i].cbBuffer));
  1324. /* send handshake token to server */
  1325. written = Curl_conn_cf_send(cf->next, data,
  1326. outbuf[i].pvBuffer, outbuf[i].cbBuffer,
  1327. &result);
  1328. if((result != CURLE_OK) ||
  1329. (outbuf[i].cbBuffer != (size_t) written)) {
  1330. failf(data, "schannel: failed to send next handshake data: "
  1331. "sent %zd of %lu bytes", written, outbuf[i].cbBuffer);
  1332. return CURLE_SSL_CONNECT_ERROR;
  1333. }
  1334. }
  1335. /* free obsolete buffer */
  1336. if(outbuf[i].pvBuffer) {
  1337. s_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer);
  1338. }
  1339. }
  1340. }
  1341. else {
  1342. char buffer[STRERROR_LEN];
  1343. switch(sspi_status) {
  1344. case SEC_E_INSUFFICIENT_MEMORY:
  1345. failf(data, "schannel: next InitializeSecurityContext failed: %s",
  1346. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1347. return CURLE_OUT_OF_MEMORY;
  1348. case SEC_E_WRONG_PRINCIPAL:
  1349. failf(data, "schannel: SNI or certificate check failed: %s",
  1350. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1351. return CURLE_PEER_FAILED_VERIFICATION;
  1352. case SEC_E_UNTRUSTED_ROOT:
  1353. failf(data, "schannel: %s",
  1354. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1355. return CURLE_PEER_FAILED_VERIFICATION;
  1356. /*
  1357. case SEC_E_INVALID_HANDLE:
  1358. case SEC_E_INVALID_TOKEN:
  1359. case SEC_E_LOGON_DENIED:
  1360. case SEC_E_TARGET_UNKNOWN:
  1361. case SEC_E_NO_AUTHENTICATING_AUTHORITY:
  1362. case SEC_E_INTERNAL_ERROR:
  1363. case SEC_E_NO_CREDENTIALS:
  1364. case SEC_E_UNSUPPORTED_FUNCTION:
  1365. case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
  1366. */
  1367. default:
  1368. failf(data, "schannel: next InitializeSecurityContext failed: %s",
  1369. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1370. return CURLE_SSL_CONNECT_ERROR;
  1371. }
  1372. }
  1373. /* check if there was additional remaining encrypted data */
  1374. if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) {
  1375. DEBUGF(infof(data, "schannel: encrypted data length: %lu",
  1376. inbuf[1].cbBuffer));
  1377. /*
  1378. There are two cases where we could be getting extra data here:
  1379. 1) If we're renegotiating a connection and the handshake is already
  1380. complete (from the server perspective), it can encrypted app data
  1381. (not handshake data) in an extra buffer at this point.
  1382. 2) (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a
  1383. connection and this extra data is part of the handshake.
  1384. We should process the data immediately; waiting for the socket to
  1385. be ready may fail since the server is done sending handshake data.
  1386. */
  1387. /* check if the remaining data is less than the total amount
  1388. and therefore begins after the already processed data */
  1389. if(backend->encdata_offset > inbuf[1].cbBuffer) {
  1390. memmove(backend->encdata_buffer,
  1391. (backend->encdata_buffer + backend->encdata_offset) -
  1392. inbuf[1].cbBuffer, inbuf[1].cbBuffer);
  1393. backend->encdata_offset = inbuf[1].cbBuffer;
  1394. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  1395. doread = FALSE;
  1396. continue;
  1397. }
  1398. }
  1399. }
  1400. else {
  1401. backend->encdata_offset = 0;
  1402. }
  1403. break;
  1404. }
  1405. /* check if the handshake needs to be continued */
  1406. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  1407. connssl->connecting_state = ssl_connect_2_reading;
  1408. return CURLE_OK;
  1409. }
  1410. /* check if the handshake is complete */
  1411. if(sspi_status == SEC_E_OK) {
  1412. connssl->connecting_state = ssl_connect_3;
  1413. DEBUGF(infof(data, "schannel: SSL/TLS handshake complete"));
  1414. }
  1415. pubkey_ptr = Curl_ssl_cf_is_proxy(cf)?
  1416. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  1417. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1418. if(pubkey_ptr) {
  1419. result = schannel_pkp_pin_peer_pubkey(cf, data, pubkey_ptr);
  1420. if(result) {
  1421. failf(data, "SSL: public key does not match pinned public key");
  1422. return result;
  1423. }
  1424. }
  1425. #ifdef HAS_MANUAL_VERIFY_API
  1426. if(conn_config->verifypeer && backend->use_manual_cred_validation) {
  1427. return Curl_verify_certificate(cf, data);
  1428. }
  1429. #endif
  1430. return CURLE_OK;
  1431. }
  1432. static bool
  1433. valid_cert_encoding(const CERT_CONTEXT *cert_context)
  1434. {
  1435. return (cert_context != NULL) &&
  1436. ((cert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
  1437. (cert_context->pbCertEncoded != NULL) &&
  1438. (cert_context->cbCertEncoded > 0);
  1439. }
  1440. typedef bool(*Read_crt_func)(const CERT_CONTEXT *ccert_context, void *arg);
  1441. static void
  1442. traverse_cert_store(const CERT_CONTEXT *context, Read_crt_func func,
  1443. void *arg)
  1444. {
  1445. const CERT_CONTEXT *current_context = NULL;
  1446. bool should_continue = true;
  1447. while(should_continue &&
  1448. (current_context = CertEnumCertificatesInStore(
  1449. context->hCertStore,
  1450. current_context)) != NULL)
  1451. should_continue = func(current_context, arg);
  1452. if(current_context)
  1453. CertFreeCertificateContext(current_context);
  1454. }
  1455. static bool
  1456. cert_counter_callback(const CERT_CONTEXT *ccert_context, void *certs_count)
  1457. {
  1458. if(valid_cert_encoding(ccert_context))
  1459. (*(int *)certs_count)++;
  1460. return true;
  1461. }
  1462. struct Adder_args
  1463. {
  1464. struct Curl_easy *data;
  1465. CURLcode result;
  1466. int idx;
  1467. int certs_count;
  1468. };
  1469. static bool
  1470. add_cert_to_certinfo(const CERT_CONTEXT *ccert_context, void *raw_arg)
  1471. {
  1472. struct Adder_args *args = (struct Adder_args*)raw_arg;
  1473. args->result = CURLE_OK;
  1474. if(valid_cert_encoding(ccert_context)) {
  1475. const char *beg = (const char *) ccert_context->pbCertEncoded;
  1476. const char *end = beg + ccert_context->cbCertEncoded;
  1477. int insert_index = (args->certs_count - 1) - args->idx;
  1478. args->result = Curl_extract_certinfo(args->data, insert_index,
  1479. beg, end);
  1480. args->idx++;
  1481. }
  1482. return args->result == CURLE_OK;
  1483. }
  1484. static CURLcode
  1485. schannel_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data)
  1486. {
  1487. struct ssl_connect_data *connssl = cf->ctx;
  1488. struct schannel_ssl_backend_data *backend =
  1489. (struct schannel_ssl_backend_data *)connssl->backend;
  1490. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1491. CURLcode result = CURLE_OK;
  1492. SECURITY_STATUS sspi_status = SEC_E_OK;
  1493. CERT_CONTEXT *ccert_context = NULL;
  1494. #ifdef HAS_ALPN
  1495. SecPkgContext_ApplicationProtocol alpn_result;
  1496. #endif
  1497. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  1498. DEBUGASSERT(backend);
  1499. DEBUGF(infof(data,
  1500. "schannel: SSL/TLS connection with %s port %d (step 3/3)",
  1501. connssl->hostname, connssl->port));
  1502. if(!backend->cred)
  1503. return CURLE_SSL_CONNECT_ERROR;
  1504. /* check if the required context attributes are met */
  1505. if(backend->ret_flags != backend->req_flags) {
  1506. if(!(backend->ret_flags & ISC_RET_SEQUENCE_DETECT))
  1507. failf(data, "schannel: failed to setup sequence detection");
  1508. if(!(backend->ret_flags & ISC_RET_REPLAY_DETECT))
  1509. failf(data, "schannel: failed to setup replay detection");
  1510. if(!(backend->ret_flags & ISC_RET_CONFIDENTIALITY))
  1511. failf(data, "schannel: failed to setup confidentiality");
  1512. if(!(backend->ret_flags & ISC_RET_ALLOCATED_MEMORY))
  1513. failf(data, "schannel: failed to setup memory allocation");
  1514. if(!(backend->ret_flags & ISC_RET_STREAM))
  1515. failf(data, "schannel: failed to setup stream orientation");
  1516. return CURLE_SSL_CONNECT_ERROR;
  1517. }
  1518. #ifdef HAS_ALPN
  1519. if(backend->use_alpn) {
  1520. sspi_status =
  1521. s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
  1522. SECPKG_ATTR_APPLICATION_PROTOCOL,
  1523. &alpn_result);
  1524. if(sspi_status != SEC_E_OK) {
  1525. failf(data, "schannel: failed to retrieve ALPN result");
  1526. return CURLE_SSL_CONNECT_ERROR;
  1527. }
  1528. if(alpn_result.ProtoNegoStatus ==
  1529. SecApplicationProtocolNegotiationStatus_Success) {
  1530. unsigned char prev_alpn = cf->conn->alpn;
  1531. Curl_alpn_set_negotiated(cf, data, alpn_result.ProtocolId,
  1532. alpn_result.ProtocolIdSize);
  1533. if(backend->recv_renegotiating) {
  1534. if(prev_alpn != cf->conn->alpn &&
  1535. prev_alpn != CURL_HTTP_VERSION_NONE) {
  1536. /* Renegotiation selected a different protocol now, we cannot
  1537. * deal with this */
  1538. failf(data, "schannel: server selected an ALPN protocol too late");
  1539. return CURLE_SSL_CONNECT_ERROR;
  1540. }
  1541. }
  1542. }
  1543. else {
  1544. if(!backend->recv_renegotiating)
  1545. Curl_alpn_set_negotiated(cf, data, NULL, 0);
  1546. }
  1547. }
  1548. #endif
  1549. /* save the current session data for possible re-use */
  1550. if(ssl_config->primary.sessionid) {
  1551. bool incache;
  1552. bool added = FALSE;
  1553. struct Curl_schannel_cred *old_cred = NULL;
  1554. Curl_ssl_sessionid_lock(data);
  1555. incache = !(Curl_ssl_getsessionid(cf, data, (void **)&old_cred, NULL));
  1556. if(incache) {
  1557. if(old_cred != backend->cred) {
  1558. DEBUGF(infof(data,
  1559. "schannel: old credential handle is stale, removing"));
  1560. /* we're not taking old_cred ownership here, no refcount++ is needed */
  1561. Curl_ssl_delsessionid(data, (void *)old_cred);
  1562. incache = FALSE;
  1563. }
  1564. }
  1565. if(!incache) {
  1566. result = Curl_ssl_addsessionid(cf, data, backend->cred,
  1567. sizeof(struct Curl_schannel_cred),
  1568. &added);
  1569. if(result) {
  1570. Curl_ssl_sessionid_unlock(data);
  1571. failf(data, "schannel: failed to store credential handle");
  1572. return result;
  1573. }
  1574. else if(added) {
  1575. /* this cred session is now also referenced by sessionid cache */
  1576. backend->cred->refcount++;
  1577. DEBUGF(infof(data,
  1578. "schannel: stored credential handle in session cache"));
  1579. }
  1580. }
  1581. Curl_ssl_sessionid_unlock(data);
  1582. }
  1583. if(data->set.ssl.certinfo) {
  1584. int certs_count = 0;
  1585. sspi_status =
  1586. s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
  1587. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  1588. &ccert_context);
  1589. if((sspi_status != SEC_E_OK) || !ccert_context) {
  1590. failf(data, "schannel: failed to retrieve remote cert context");
  1591. return CURLE_PEER_FAILED_VERIFICATION;
  1592. }
  1593. traverse_cert_store(ccert_context, cert_counter_callback, &certs_count);
  1594. result = Curl_ssl_init_certinfo(data, certs_count);
  1595. if(!result) {
  1596. struct Adder_args args;
  1597. args.data = data;
  1598. args.idx = 0;
  1599. args.certs_count = certs_count;
  1600. traverse_cert_store(ccert_context, add_cert_to_certinfo, &args);
  1601. result = args.result;
  1602. }
  1603. CertFreeCertificateContext(ccert_context);
  1604. if(result)
  1605. return result;
  1606. }
  1607. connssl->connecting_state = ssl_connect_done;
  1608. return CURLE_OK;
  1609. }
  1610. static CURLcode
  1611. schannel_connect_common(struct Curl_cfilter *cf,
  1612. struct Curl_easy *data,
  1613. bool nonblocking, bool *done)
  1614. {
  1615. CURLcode result;
  1616. struct ssl_connect_data *connssl = cf->ctx;
  1617. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  1618. timediff_t timeout_ms;
  1619. int what;
  1620. /* check if the connection has already been established */
  1621. if(ssl_connection_complete == connssl->state) {
  1622. *done = TRUE;
  1623. return CURLE_OK;
  1624. }
  1625. if(ssl_connect_1 == connssl->connecting_state) {
  1626. /* check out how much more time we're allowed */
  1627. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1628. if(timeout_ms < 0) {
  1629. /* no need to continue if time already is up */
  1630. failf(data, "SSL/TLS connection timeout");
  1631. return CURLE_OPERATION_TIMEDOUT;
  1632. }
  1633. result = schannel_connect_step1(cf, data);
  1634. if(result)
  1635. return result;
  1636. }
  1637. while(ssl_connect_2 == connssl->connecting_state ||
  1638. ssl_connect_2_reading == connssl->connecting_state ||
  1639. ssl_connect_2_writing == connssl->connecting_state) {
  1640. /* check out how much more time we're allowed */
  1641. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1642. if(timeout_ms < 0) {
  1643. /* no need to continue if time already is up */
  1644. failf(data, "SSL/TLS connection timeout");
  1645. return CURLE_OPERATION_TIMEDOUT;
  1646. }
  1647. /* if ssl is expecting something, check if it's available. */
  1648. if(connssl->connecting_state == ssl_connect_2_reading
  1649. || connssl->connecting_state == ssl_connect_2_writing) {
  1650. curl_socket_t writefd = ssl_connect_2_writing ==
  1651. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  1652. curl_socket_t readfd = ssl_connect_2_reading ==
  1653. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  1654. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  1655. nonblocking ? 0 : timeout_ms);
  1656. if(what < 0) {
  1657. /* fatal error */
  1658. failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO);
  1659. return CURLE_SSL_CONNECT_ERROR;
  1660. }
  1661. else if(0 == what) {
  1662. if(nonblocking) {
  1663. *done = FALSE;
  1664. return CURLE_OK;
  1665. }
  1666. else {
  1667. /* timeout */
  1668. failf(data, "SSL/TLS connection timeout");
  1669. return CURLE_OPERATION_TIMEDOUT;
  1670. }
  1671. }
  1672. /* socket is readable or writable */
  1673. }
  1674. /* Run transaction, and return to the caller if it failed or if
  1675. * this connection is part of a multi handle and this loop would
  1676. * execute again. This permits the owner of a multi handle to
  1677. * abort a connection attempt before step2 has completed while
  1678. * ensuring that a client using select() or epoll() will always
  1679. * have a valid fdset to wait on.
  1680. */
  1681. result = schannel_connect_step2(cf, data);
  1682. if(result || (nonblocking &&
  1683. (ssl_connect_2 == connssl->connecting_state ||
  1684. ssl_connect_2_reading == connssl->connecting_state ||
  1685. ssl_connect_2_writing == connssl->connecting_state)))
  1686. return result;
  1687. } /* repeat step2 until all transactions are done. */
  1688. if(ssl_connect_3 == connssl->connecting_state) {
  1689. result = schannel_connect_step3(cf, data);
  1690. if(result)
  1691. return result;
  1692. }
  1693. if(ssl_connect_done == connssl->connecting_state) {
  1694. connssl->state = ssl_connection_complete;
  1695. #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS
  1696. /* When SSPI is used in combination with Schannel
  1697. * we need the Schannel context to create the Schannel
  1698. * binding to pass the IIS extended protection checks.
  1699. * Available on Windows 7 or later.
  1700. */
  1701. {
  1702. struct schannel_ssl_backend_data *backend =
  1703. (struct schannel_ssl_backend_data *)connssl->backend;
  1704. DEBUGASSERT(backend);
  1705. cf->conn->sslContext = &backend->ctxt->ctxt_handle;
  1706. }
  1707. #endif
  1708. *done = TRUE;
  1709. }
  1710. else
  1711. *done = FALSE;
  1712. /* reset our connection state machine */
  1713. connssl->connecting_state = ssl_connect_1;
  1714. return CURLE_OK;
  1715. }
  1716. static ssize_t
  1717. schannel_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1718. const void *buf, size_t len, CURLcode *err)
  1719. {
  1720. ssize_t written = -1;
  1721. size_t data_len = 0;
  1722. unsigned char *ptr = NULL;
  1723. struct ssl_connect_data *connssl = cf->ctx;
  1724. SecBuffer outbuf[4];
  1725. SecBufferDesc outbuf_desc;
  1726. SECURITY_STATUS sspi_status = SEC_E_OK;
  1727. CURLcode result;
  1728. struct schannel_ssl_backend_data *backend =
  1729. (struct schannel_ssl_backend_data *)connssl->backend;
  1730. DEBUGASSERT(backend);
  1731. /* check if the maximum stream sizes were queried */
  1732. if(backend->stream_sizes.cbMaximumMessage == 0) {
  1733. sspi_status = s_pSecFn->QueryContextAttributes(
  1734. &backend->ctxt->ctxt_handle,
  1735. SECPKG_ATTR_STREAM_SIZES,
  1736. &backend->stream_sizes);
  1737. if(sspi_status != SEC_E_OK) {
  1738. *err = CURLE_SEND_ERROR;
  1739. return -1;
  1740. }
  1741. }
  1742. /* check if the buffer is longer than the maximum message length */
  1743. if(len > backend->stream_sizes.cbMaximumMessage) {
  1744. len = backend->stream_sizes.cbMaximumMessage;
  1745. }
  1746. /* calculate the complete message length and allocate a buffer for it */
  1747. data_len = backend->stream_sizes.cbHeader + len +
  1748. backend->stream_sizes.cbTrailer;
  1749. ptr = (unsigned char *) malloc(data_len);
  1750. if(!ptr) {
  1751. *err = CURLE_OUT_OF_MEMORY;
  1752. return -1;
  1753. }
  1754. /* setup output buffers (header, data, trailer, empty) */
  1755. InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
  1756. ptr, backend->stream_sizes.cbHeader);
  1757. InitSecBuffer(&outbuf[1], SECBUFFER_DATA,
  1758. ptr + backend->stream_sizes.cbHeader, curlx_uztoul(len));
  1759. InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
  1760. ptr + backend->stream_sizes.cbHeader + len,
  1761. backend->stream_sizes.cbTrailer);
  1762. InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
  1763. InitSecBufferDesc(&outbuf_desc, outbuf, 4);
  1764. /* copy data into output buffer */
  1765. memcpy(outbuf[1].pvBuffer, buf, len);
  1766. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */
  1767. sspi_status = s_pSecFn->EncryptMessage(&backend->ctxt->ctxt_handle, 0,
  1768. &outbuf_desc, 0);
  1769. /* check if the message was encrypted */
  1770. if(sspi_status == SEC_E_OK) {
  1771. written = 0;
  1772. /* send the encrypted message including header, data and trailer */
  1773. len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer;
  1774. /*
  1775. It's important to send the full message which includes the header,
  1776. encrypted payload, and trailer. Until the client receives all the
  1777. data a coherent message has not been delivered and the client
  1778. can't read any of it.
  1779. If we wanted to buffer the unwritten encrypted bytes, we would
  1780. tell the client that all data it has requested to be sent has been
  1781. sent. The unwritten encrypted bytes would be the first bytes to
  1782. send on the next invocation.
  1783. Here's the catch with this - if we tell the client that all the
  1784. bytes have been sent, will the client call this method again to
  1785. send the buffered data? Looking at who calls this function, it
  1786. seems the answer is NO.
  1787. */
  1788. /* send entire message or fail */
  1789. while(len > (size_t)written) {
  1790. ssize_t this_write = 0;
  1791. int what;
  1792. timediff_t timeout_ms = Curl_timeleft(data, NULL, FALSE);
  1793. if(timeout_ms < 0) {
  1794. /* we already got the timeout */
  1795. failf(data, "schannel: timed out sending data "
  1796. "(bytes sent: %zd)", written);
  1797. *err = CURLE_OPERATION_TIMEDOUT;
  1798. written = -1;
  1799. break;
  1800. }
  1801. else if(!timeout_ms)
  1802. timeout_ms = TIMEDIFF_T_MAX;
  1803. what = SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), timeout_ms);
  1804. if(what < 0) {
  1805. /* fatal error */
  1806. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1807. *err = CURLE_SEND_ERROR;
  1808. written = -1;
  1809. break;
  1810. }
  1811. else if(0 == what) {
  1812. failf(data, "schannel: timed out sending data "
  1813. "(bytes sent: %zd)", written);
  1814. *err = CURLE_OPERATION_TIMEDOUT;
  1815. written = -1;
  1816. break;
  1817. }
  1818. /* socket is writable */
  1819. this_write = Curl_conn_cf_send(cf->next, data,
  1820. ptr + written, len - written,
  1821. &result);
  1822. if(result == CURLE_AGAIN)
  1823. continue;
  1824. else if(result != CURLE_OK) {
  1825. *err = result;
  1826. written = -1;
  1827. break;
  1828. }
  1829. written += this_write;
  1830. }
  1831. }
  1832. else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) {
  1833. *err = CURLE_OUT_OF_MEMORY;
  1834. }
  1835. else{
  1836. *err = CURLE_SEND_ERROR;
  1837. }
  1838. Curl_safefree(ptr);
  1839. if(len == (size_t)written)
  1840. /* Encrypted message including header, data and trailer entirely sent.
  1841. The return value is the number of unencrypted bytes that were sent. */
  1842. written = outbuf[1].cbBuffer;
  1843. return written;
  1844. }
  1845. static ssize_t
  1846. schannel_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1847. char *buf, size_t len, CURLcode *err)
  1848. {
  1849. size_t size = 0;
  1850. ssize_t nread = -1;
  1851. struct ssl_connect_data *connssl = cf->ctx;
  1852. unsigned char *reallocated_buffer;
  1853. size_t reallocated_length;
  1854. bool done = FALSE;
  1855. SecBuffer inbuf[4];
  1856. SecBufferDesc inbuf_desc;
  1857. SECURITY_STATUS sspi_status = SEC_E_OK;
  1858. /* we want the length of the encrypted buffer to be at least large enough
  1859. that it can hold all the bytes requested and some TLS record overhead. */
  1860. size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1861. struct schannel_ssl_backend_data *backend =
  1862. (struct schannel_ssl_backend_data *)connssl->backend;
  1863. DEBUGASSERT(backend);
  1864. /****************************************************************************
  1865. * Don't return or set backend->recv_unrecoverable_err unless in the cleanup.
  1866. * The pattern for return error is set *err, optional infof, goto cleanup.
  1867. *
  1868. * Our priority is to always return as much decrypted data to the caller as
  1869. * possible, even if an error occurs. The state of the decrypted buffer must
  1870. * always be valid. Transfer of decrypted data to the caller's buffer is
  1871. * handled in the cleanup.
  1872. */
  1873. DEBUGF(infof(data, "schannel: client wants to read %zu bytes", len));
  1874. *err = CURLE_OK;
  1875. if(len && len <= backend->decdata_offset) {
  1876. infof(data, "schannel: enough decrypted data is already available");
  1877. goto cleanup;
  1878. }
  1879. else if(backend->recv_unrecoverable_err) {
  1880. *err = backend->recv_unrecoverable_err;
  1881. infof(data, "schannel: an unrecoverable error occurred in a prior call");
  1882. goto cleanup;
  1883. }
  1884. else if(backend->recv_sspi_close_notify) {
  1885. /* once a server has indicated shutdown there is no more encrypted data */
  1886. infof(data, "schannel: server indicated shutdown in a prior call");
  1887. goto cleanup;
  1888. }
  1889. /* It's debatable what to return when !len. Regardless we can't return
  1890. immediately because there may be data to decrypt (in the case we want to
  1891. decrypt all encrypted cached data) so handle !len later in cleanup.
  1892. */
  1893. else if(len && !backend->recv_connection_closed) {
  1894. /* increase enc buffer in order to fit the requested amount of data */
  1895. size = backend->encdata_length - backend->encdata_offset;
  1896. if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE ||
  1897. backend->encdata_length < min_encdata_length) {
  1898. reallocated_length = backend->encdata_offset +
  1899. CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1900. if(reallocated_length < min_encdata_length) {
  1901. reallocated_length = min_encdata_length;
  1902. }
  1903. reallocated_buffer = realloc(backend->encdata_buffer,
  1904. reallocated_length);
  1905. if(!reallocated_buffer) {
  1906. *err = CURLE_OUT_OF_MEMORY;
  1907. failf(data, "schannel: unable to re-allocate memory");
  1908. goto cleanup;
  1909. }
  1910. backend->encdata_buffer = reallocated_buffer;
  1911. backend->encdata_length = reallocated_length;
  1912. size = backend->encdata_length - backend->encdata_offset;
  1913. DEBUGF(infof(data, "schannel: encdata_buffer resized %zu",
  1914. backend->encdata_length));
  1915. }
  1916. DEBUGF(infof(data,
  1917. "schannel: encrypted data buffer: offset %zu length %zu",
  1918. backend->encdata_offset, backend->encdata_length));
  1919. /* read encrypted data from socket */
  1920. nread = Curl_conn_cf_recv(cf->next, data,
  1921. (char *)(backend->encdata_buffer +
  1922. backend->encdata_offset),
  1923. size, err);
  1924. if(*err) {
  1925. nread = -1;
  1926. if(*err == CURLE_AGAIN)
  1927. DEBUGF(infof(data,
  1928. "schannel: recv returned CURLE_AGAIN"));
  1929. else if(*err == CURLE_RECV_ERROR)
  1930. infof(data, "schannel: recv returned CURLE_RECV_ERROR");
  1931. else
  1932. infof(data, "schannel: recv returned error %d", *err);
  1933. }
  1934. else if(nread == 0) {
  1935. backend->recv_connection_closed = true;
  1936. DEBUGF(infof(data, "schannel: server closed the connection"));
  1937. }
  1938. else if(nread > 0) {
  1939. backend->encdata_offset += (size_t)nread;
  1940. backend->encdata_is_incomplete = false;
  1941. DEBUGF(infof(data, "schannel: encrypted data got %zd", nread));
  1942. }
  1943. }
  1944. DEBUGF(infof(data,
  1945. "schannel: encrypted data buffer: offset %zu length %zu",
  1946. backend->encdata_offset, backend->encdata_length));
  1947. /* decrypt loop */
  1948. while(backend->encdata_offset > 0 && sspi_status == SEC_E_OK &&
  1949. (!len || backend->decdata_offset < len ||
  1950. backend->recv_connection_closed)) {
  1951. /* prepare data buffer for DecryptMessage call */
  1952. InitSecBuffer(&inbuf[0], SECBUFFER_DATA, backend->encdata_buffer,
  1953. curlx_uztoul(backend->encdata_offset));
  1954. /* we need 3 more empty input buffers for possible output */
  1955. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  1956. InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0);
  1957. InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0);
  1958. InitSecBufferDesc(&inbuf_desc, inbuf, 4);
  1959. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx
  1960. */
  1961. sspi_status = s_pSecFn->DecryptMessage(&backend->ctxt->ctxt_handle,
  1962. &inbuf_desc, 0, NULL);
  1963. /* check if everything went fine (server may want to renegotiate
  1964. or shutdown the connection context) */
  1965. if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE ||
  1966. sspi_status == SEC_I_CONTEXT_EXPIRED) {
  1967. /* check for successfully decrypted data, even before actual
  1968. renegotiation or shutdown of the connection context */
  1969. if(inbuf[1].BufferType == SECBUFFER_DATA) {
  1970. DEBUGF(infof(data, "schannel: decrypted data length: %lu",
  1971. inbuf[1].cbBuffer));
  1972. /* increase buffer in order to fit the received amount of data */
  1973. size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ?
  1974. inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1975. if(backend->decdata_length - backend->decdata_offset < size ||
  1976. backend->decdata_length < len) {
  1977. /* increase internal decrypted data buffer */
  1978. reallocated_length = backend->decdata_offset + size;
  1979. /* make sure that the requested amount of data fits */
  1980. if(reallocated_length < len) {
  1981. reallocated_length = len;
  1982. }
  1983. reallocated_buffer = realloc(backend->decdata_buffer,
  1984. reallocated_length);
  1985. if(!reallocated_buffer) {
  1986. *err = CURLE_OUT_OF_MEMORY;
  1987. failf(data, "schannel: unable to re-allocate memory");
  1988. goto cleanup;
  1989. }
  1990. backend->decdata_buffer = reallocated_buffer;
  1991. backend->decdata_length = reallocated_length;
  1992. }
  1993. /* copy decrypted data to internal buffer */
  1994. size = inbuf[1].cbBuffer;
  1995. if(size) {
  1996. memcpy(backend->decdata_buffer + backend->decdata_offset,
  1997. inbuf[1].pvBuffer, size);
  1998. backend->decdata_offset += size;
  1999. }
  2000. DEBUGF(infof(data, "schannel: decrypted data added: %zu", size));
  2001. DEBUGF(infof(data,
  2002. "schannel: decrypted cached: offset %zu length %zu",
  2003. backend->decdata_offset, backend->decdata_length));
  2004. }
  2005. /* check for remaining encrypted data */
  2006. if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) {
  2007. DEBUGF(infof(data, "schannel: encrypted data length: %lu",
  2008. inbuf[3].cbBuffer));
  2009. /* check if the remaining data is less than the total amount
  2010. * and therefore begins after the already processed data
  2011. */
  2012. if(backend->encdata_offset > inbuf[3].cbBuffer) {
  2013. /* move remaining encrypted data forward to the beginning of
  2014. buffer */
  2015. memmove(backend->encdata_buffer,
  2016. (backend->encdata_buffer + backend->encdata_offset) -
  2017. inbuf[3].cbBuffer, inbuf[3].cbBuffer);
  2018. backend->encdata_offset = inbuf[3].cbBuffer;
  2019. }
  2020. DEBUGF(infof(data,
  2021. "schannel: encrypted cached: offset %zu length %zu",
  2022. backend->encdata_offset, backend->encdata_length));
  2023. }
  2024. else {
  2025. /* reset encrypted buffer offset, because there is no data remaining */
  2026. backend->encdata_offset = 0;
  2027. }
  2028. /* check if server wants to renegotiate the connection context */
  2029. if(sspi_status == SEC_I_RENEGOTIATE) {
  2030. infof(data, "schannel: remote party requests renegotiation");
  2031. if(*err && *err != CURLE_AGAIN) {
  2032. infof(data, "schannel: can't renegotiate, an error is pending");
  2033. goto cleanup;
  2034. }
  2035. /* begin renegotiation */
  2036. infof(data, "schannel: renegotiating SSL/TLS connection");
  2037. connssl->state = ssl_connection_negotiating;
  2038. connssl->connecting_state = ssl_connect_2_writing;
  2039. backend->recv_renegotiating = true;
  2040. *err = schannel_connect_common(cf, data, FALSE, &done);
  2041. backend->recv_renegotiating = false;
  2042. if(*err) {
  2043. infof(data, "schannel: renegotiation failed");
  2044. goto cleanup;
  2045. }
  2046. /* now retry receiving data */
  2047. sspi_status = SEC_E_OK;
  2048. infof(data, "schannel: SSL/TLS connection renegotiated");
  2049. continue;
  2050. }
  2051. /* check if the server closed the connection */
  2052. else if(sspi_status == SEC_I_CONTEXT_EXPIRED) {
  2053. /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not
  2054. returned so we have to work around that in cleanup. */
  2055. backend->recv_sspi_close_notify = true;
  2056. if(!backend->recv_connection_closed) {
  2057. backend->recv_connection_closed = true;
  2058. infof(data, "schannel: server closed the connection");
  2059. }
  2060. goto cleanup;
  2061. }
  2062. }
  2063. else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  2064. backend->encdata_is_incomplete = true;
  2065. if(!*err)
  2066. *err = CURLE_AGAIN;
  2067. infof(data, "schannel: failed to decrypt data, need more data");
  2068. goto cleanup;
  2069. }
  2070. else {
  2071. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  2072. char buffer[STRERROR_LEN];
  2073. #endif
  2074. *err = CURLE_RECV_ERROR;
  2075. infof(data, "schannel: failed to read data from server: %s",
  2076. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  2077. goto cleanup;
  2078. }
  2079. }
  2080. DEBUGF(infof(data,
  2081. "schannel: encrypted data buffer: offset %zu length %zu",
  2082. backend->encdata_offset, backend->encdata_length));
  2083. DEBUGF(infof(data,
  2084. "schannel: decrypted data buffer: offset %zu length %zu",
  2085. backend->decdata_offset, backend->decdata_length));
  2086. cleanup:
  2087. /* Warning- there is no guarantee the encdata state is valid at this point */
  2088. DEBUGF(infof(data, "schannel: schannel_recv cleanup"));
  2089. /* Error if the connection has closed without a close_notify.
  2090. The behavior here is a matter of debate. We don't want to be vulnerable
  2091. to a truncation attack however there's some browser precedent for
  2092. ignoring the close_notify for compatibility reasons.
  2093. Additionally, Windows 2000 (v5.0) is a special case since it seems it
  2094. doesn't return close_notify. In that case if the connection was closed we
  2095. assume it was graceful (close_notify) since there doesn't seem to be a
  2096. way to tell.
  2097. */
  2098. if(len && !backend->decdata_offset && backend->recv_connection_closed &&
  2099. !backend->recv_sspi_close_notify) {
  2100. bool isWin2k = curlx_verify_windows_version(5, 0, 0, PLATFORM_WINNT,
  2101. VERSION_EQUAL);
  2102. if(isWin2k && sspi_status == SEC_E_OK)
  2103. backend->recv_sspi_close_notify = true;
  2104. else {
  2105. *err = CURLE_RECV_ERROR;
  2106. infof(data, "schannel: server closed abruptly (missing close_notify)");
  2107. }
  2108. }
  2109. /* Any error other than CURLE_AGAIN is an unrecoverable error. */
  2110. if(*err && *err != CURLE_AGAIN)
  2111. backend->recv_unrecoverable_err = *err;
  2112. size = len < backend->decdata_offset ? len : backend->decdata_offset;
  2113. if(size) {
  2114. memcpy(buf, backend->decdata_buffer, size);
  2115. memmove(backend->decdata_buffer, backend->decdata_buffer + size,
  2116. backend->decdata_offset - size);
  2117. backend->decdata_offset -= size;
  2118. DEBUGF(infof(data, "schannel: decrypted data returned %zu", size));
  2119. DEBUGF(infof(data,
  2120. "schannel: decrypted data buffer: offset %zu length %zu",
  2121. backend->decdata_offset, backend->decdata_length));
  2122. *err = CURLE_OK;
  2123. return (ssize_t)size;
  2124. }
  2125. if(!*err && !backend->recv_connection_closed)
  2126. *err = CURLE_AGAIN;
  2127. /* It's debatable what to return when !len. We could return whatever error
  2128. we got from decryption but instead we override here so the return is
  2129. consistent.
  2130. */
  2131. if(!len)
  2132. *err = CURLE_OK;
  2133. return *err ? -1 : 0;
  2134. }
  2135. static CURLcode schannel_connect_nonblocking(struct Curl_cfilter *cf,
  2136. struct Curl_easy *data,
  2137. bool *done)
  2138. {
  2139. return schannel_connect_common(cf, data, TRUE, done);
  2140. }
  2141. static CURLcode schannel_connect(struct Curl_cfilter *cf,
  2142. struct Curl_easy *data)
  2143. {
  2144. CURLcode result;
  2145. bool done = FALSE;
  2146. result = schannel_connect_common(cf, data, FALSE, &done);
  2147. if(result)
  2148. return result;
  2149. DEBUGASSERT(done);
  2150. return CURLE_OK;
  2151. }
  2152. static bool schannel_data_pending(struct Curl_cfilter *cf,
  2153. const struct Curl_easy *data)
  2154. {
  2155. const struct ssl_connect_data *connssl = cf->ctx;
  2156. struct schannel_ssl_backend_data *backend =
  2157. (struct schannel_ssl_backend_data *)connssl->backend;
  2158. (void)data;
  2159. DEBUGASSERT(backend);
  2160. if(backend->ctxt) /* SSL/TLS is in use */
  2161. return (backend->decdata_offset > 0 ||
  2162. (backend->encdata_offset > 0 && !backend->encdata_is_incomplete));
  2163. else
  2164. return FALSE;
  2165. }
  2166. static void schannel_session_free(void *ptr)
  2167. {
  2168. /* this is expected to be called under sessionid lock */
  2169. struct Curl_schannel_cred *cred = ptr;
  2170. if(cred) {
  2171. cred->refcount--;
  2172. if(cred->refcount == 0) {
  2173. s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
  2174. curlx_unicodefree(cred->sni_hostname);
  2175. #ifdef HAS_CLIENT_CERT_PATH
  2176. if(cred->client_cert_store) {
  2177. CertCloseStore(cred->client_cert_store, 0);
  2178. cred->client_cert_store = NULL;
  2179. }
  2180. #endif
  2181. Curl_safefree(cred);
  2182. }
  2183. }
  2184. }
  2185. /* shut down the SSL connection and clean up related memory.
  2186. this function can be called multiple times on the same connection including
  2187. if the SSL connection failed (eg connection made but failed handshake). */
  2188. static int schannel_shutdown(struct Curl_cfilter *cf,
  2189. struct Curl_easy *data)
  2190. {
  2191. /* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx
  2192. * Shutting Down an Schannel Connection
  2193. */
  2194. struct ssl_connect_data *connssl = cf->ctx;
  2195. struct schannel_ssl_backend_data *backend =
  2196. (struct schannel_ssl_backend_data *)connssl->backend;
  2197. DEBUGASSERT(data);
  2198. DEBUGASSERT(backend);
  2199. if(backend->ctxt) {
  2200. infof(data, "schannel: shutting down SSL/TLS connection with %s port %d",
  2201. connssl->hostname, connssl->port);
  2202. }
  2203. if(backend->cred && backend->ctxt) {
  2204. SecBufferDesc BuffDesc;
  2205. SecBuffer Buffer;
  2206. SECURITY_STATUS sspi_status;
  2207. SecBuffer outbuf;
  2208. SecBufferDesc outbuf_desc;
  2209. CURLcode result;
  2210. DWORD dwshut = SCHANNEL_SHUTDOWN;
  2211. InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
  2212. InitSecBufferDesc(&BuffDesc, &Buffer, 1);
  2213. sspi_status = s_pSecFn->ApplyControlToken(&backend->ctxt->ctxt_handle,
  2214. &BuffDesc);
  2215. if(sspi_status != SEC_E_OK) {
  2216. char buffer[STRERROR_LEN];
  2217. failf(data, "schannel: ApplyControlToken failure: %s",
  2218. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  2219. }
  2220. /* setup output buffer */
  2221. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  2222. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  2223. sspi_status = s_pSecFn->InitializeSecurityContext(
  2224. &backend->cred->cred_handle,
  2225. &backend->ctxt->ctxt_handle,
  2226. backend->cred->sni_hostname,
  2227. backend->req_flags,
  2228. 0,
  2229. 0,
  2230. NULL,
  2231. 0,
  2232. &backend->ctxt->ctxt_handle,
  2233. &outbuf_desc,
  2234. &backend->ret_flags,
  2235. &backend->ctxt->time_stamp);
  2236. if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) {
  2237. /* send close message which is in output buffer */
  2238. ssize_t written = Curl_conn_cf_send(cf->next, data,
  2239. outbuf.pvBuffer, outbuf.cbBuffer,
  2240. &result);
  2241. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  2242. if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
  2243. infof(data, "schannel: failed to send close msg: %s"
  2244. " (bytes written: %zd)", curl_easy_strerror(result), written);
  2245. }
  2246. }
  2247. }
  2248. /* free SSPI Schannel API security context handle */
  2249. if(backend->ctxt) {
  2250. DEBUGF(infof(data, "schannel: clear security context handle"));
  2251. s_pSecFn->DeleteSecurityContext(&backend->ctxt->ctxt_handle);
  2252. Curl_safefree(backend->ctxt);
  2253. }
  2254. /* free SSPI Schannel API credential handle */
  2255. if(backend->cred) {
  2256. Curl_ssl_sessionid_lock(data);
  2257. schannel_session_free(backend->cred);
  2258. Curl_ssl_sessionid_unlock(data);
  2259. backend->cred = NULL;
  2260. }
  2261. /* free internal buffer for received encrypted data */
  2262. if(backend->encdata_buffer) {
  2263. Curl_safefree(backend->encdata_buffer);
  2264. backend->encdata_length = 0;
  2265. backend->encdata_offset = 0;
  2266. backend->encdata_is_incomplete = false;
  2267. }
  2268. /* free internal buffer for received decrypted data */
  2269. if(backend->decdata_buffer) {
  2270. Curl_safefree(backend->decdata_buffer);
  2271. backend->decdata_length = 0;
  2272. backend->decdata_offset = 0;
  2273. }
  2274. return CURLE_OK;
  2275. }
  2276. static void schannel_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  2277. {
  2278. schannel_shutdown(cf, data);
  2279. }
  2280. static int schannel_init(void)
  2281. {
  2282. return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0);
  2283. }
  2284. static void schannel_cleanup(void)
  2285. {
  2286. Curl_sspi_global_cleanup();
  2287. }
  2288. static size_t schannel_version(char *buffer, size_t size)
  2289. {
  2290. size = msnprintf(buffer, size, "Schannel");
  2291. return size;
  2292. }
  2293. static CURLcode schannel_random(struct Curl_easy *data UNUSED_PARAM,
  2294. unsigned char *entropy, size_t length)
  2295. {
  2296. (void)data;
  2297. return Curl_win32_random(entropy, length);
  2298. }
  2299. static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf,
  2300. struct Curl_easy *data,
  2301. const char *pinnedpubkey)
  2302. {
  2303. struct ssl_connect_data *connssl = cf->ctx;
  2304. struct schannel_ssl_backend_data *backend =
  2305. (struct schannel_ssl_backend_data *)connssl->backend;
  2306. CERT_CONTEXT *pCertContextServer = NULL;
  2307. /* Result is returned to caller */
  2308. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  2309. DEBUGASSERT(backend);
  2310. /* if a path wasn't specified, don't pin */
  2311. if(!pinnedpubkey)
  2312. return CURLE_OK;
  2313. do {
  2314. SECURITY_STATUS sspi_status;
  2315. const char *x509_der;
  2316. DWORD x509_der_len;
  2317. struct Curl_X509certificate x509_parsed;
  2318. struct Curl_asn1Element *pubkey;
  2319. sspi_status =
  2320. s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
  2321. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  2322. &pCertContextServer);
  2323. if((sspi_status != SEC_E_OK) || !pCertContextServer) {
  2324. char buffer[STRERROR_LEN];
  2325. failf(data, "schannel: Failed to read remote certificate context: %s",
  2326. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  2327. break; /* failed */
  2328. }
  2329. if(!(((pCertContextServer->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
  2330. (pCertContextServer->cbCertEncoded > 0)))
  2331. break;
  2332. x509_der = (const char *)pCertContextServer->pbCertEncoded;
  2333. x509_der_len = pCertContextServer->cbCertEncoded;
  2334. memset(&x509_parsed, 0, sizeof(x509_parsed));
  2335. if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
  2336. break;
  2337. pubkey = &x509_parsed.subjectPublicKeyInfo;
  2338. if(!pubkey->header || pubkey->end <= pubkey->header) {
  2339. failf(data, "SSL: failed retrieving public key from server certificate");
  2340. break;
  2341. }
  2342. result = Curl_pin_peer_pubkey(data,
  2343. pinnedpubkey,
  2344. (const unsigned char *)pubkey->header,
  2345. (size_t)(pubkey->end - pubkey->header));
  2346. if(result) {
  2347. failf(data, "SSL: public key does not match pinned public key");
  2348. }
  2349. } while(0);
  2350. if(pCertContextServer)
  2351. CertFreeCertificateContext(pCertContextServer);
  2352. return result;
  2353. }
  2354. static void schannel_checksum(const unsigned char *input,
  2355. size_t inputlen,
  2356. unsigned char *checksum,
  2357. size_t checksumlen,
  2358. DWORD provType,
  2359. const unsigned int algId)
  2360. {
  2361. HCRYPTPROV hProv = 0;
  2362. HCRYPTHASH hHash = 0;
  2363. DWORD cbHashSize = 0;
  2364. DWORD dwHashSizeLen = (DWORD)sizeof(cbHashSize);
  2365. DWORD dwChecksumLen = (DWORD)checksumlen;
  2366. /* since this can fail in multiple ways, zero memory first so we never
  2367. * return old data
  2368. */
  2369. memset(checksum, 0, checksumlen);
  2370. if(!CryptAcquireContext(&hProv, NULL, NULL, provType,
  2371. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2372. return; /* failed */
  2373. do {
  2374. if(!CryptCreateHash(hProv, algId, 0, 0, &hHash))
  2375. break; /* failed */
  2376. /* workaround for original MinGW, should be (const BYTE*) */
  2377. if(!CryptHashData(hHash, (BYTE*)input, (DWORD)inputlen, 0))
  2378. break; /* failed */
  2379. /* get hash size */
  2380. if(!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize,
  2381. &dwHashSizeLen, 0))
  2382. break; /* failed */
  2383. /* check hash size */
  2384. if(checksumlen < cbHashSize)
  2385. break; /* failed */
  2386. if(CryptGetHashParam(hHash, HP_HASHVAL, checksum, &dwChecksumLen, 0))
  2387. break; /* failed */
  2388. } while(0);
  2389. if(hHash)
  2390. CryptDestroyHash(hHash);
  2391. if(hProv)
  2392. CryptReleaseContext(hProv, 0);
  2393. }
  2394. static CURLcode schannel_sha256sum(const unsigned char *input,
  2395. size_t inputlen,
  2396. unsigned char *sha256sum,
  2397. size_t sha256len)
  2398. {
  2399. schannel_checksum(input, inputlen, sha256sum, sha256len,
  2400. PROV_RSA_AES, CALG_SHA_256);
  2401. return CURLE_OK;
  2402. }
  2403. static void *schannel_get_internals(struct ssl_connect_data *connssl,
  2404. CURLINFO info UNUSED_PARAM)
  2405. {
  2406. struct schannel_ssl_backend_data *backend =
  2407. (struct schannel_ssl_backend_data *)connssl->backend;
  2408. (void)info;
  2409. DEBUGASSERT(backend);
  2410. return &backend->ctxt->ctxt_handle;
  2411. }
  2412. const struct Curl_ssl Curl_ssl_schannel = {
  2413. { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */
  2414. SSLSUPP_CERTINFO |
  2415. #ifdef HAS_MANUAL_VERIFY_API
  2416. SSLSUPP_CAINFO_BLOB |
  2417. #endif
  2418. SSLSUPP_PINNEDPUBKEY |
  2419. SSLSUPP_TLS13_CIPHERSUITES |
  2420. SSLSUPP_HTTPS_PROXY,
  2421. sizeof(struct schannel_ssl_backend_data),
  2422. schannel_init, /* init */
  2423. schannel_cleanup, /* cleanup */
  2424. schannel_version, /* version */
  2425. Curl_none_check_cxn, /* check_cxn */
  2426. schannel_shutdown, /* shutdown */
  2427. schannel_data_pending, /* data_pending */
  2428. schannel_random, /* random */
  2429. Curl_none_cert_status_request, /* cert_status_request */
  2430. schannel_connect, /* connect */
  2431. schannel_connect_nonblocking, /* connect_nonblocking */
  2432. Curl_ssl_get_select_socks, /* getsock */
  2433. schannel_get_internals, /* get_internals */
  2434. schannel_close, /* close_one */
  2435. Curl_none_close_all, /* close_all */
  2436. schannel_session_free, /* session_free */
  2437. Curl_none_set_engine, /* set_engine */
  2438. Curl_none_set_engine_default, /* set_engine_default */
  2439. Curl_none_engines_list, /* engines_list */
  2440. Curl_none_false_start, /* false_start */
  2441. schannel_sha256sum, /* sha256sum */
  2442. NULL, /* associate_connection */
  2443. NULL, /* disassociate_connection */
  2444. NULL, /* free_multi_ssl_backend_data */
  2445. schannel_recv, /* recv decrypted data */
  2446. schannel_send, /* send data to encrypt */
  2447. };
  2448. #endif /* USE_SCHANNEL */