schannel.c 91 KB

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