schannel.c 97 KB

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