schannel.c 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931
  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->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, (void **)&old_cred, NULL)) {
  1001. backend->cred = old_cred;
  1002. DEBUGF(infof(data, "schannel: reusing existing credential handle"));
  1003. /* increment the reference counter of the credential/session handle */
  1004. backend->cred->refcount++;
  1005. DEBUGF(infof(data,
  1006. "schannel: incremented credential handle refcount = %d",
  1007. backend->cred->refcount));
  1008. }
  1009. Curl_ssl_sessionid_unlock(data);
  1010. }
  1011. if(!backend->cred) {
  1012. char *snihost;
  1013. result = schannel_acquire_credential_handle(cf, data);
  1014. if(result)
  1015. return result;
  1016. /* schannel_acquire_credential_handle() sets backend->cred accordingly or
  1017. it returns error otherwise. */
  1018. /* A hostname associated with the credential is needed by
  1019. InitializeSecurityContext for SNI and other reasons. */
  1020. snihost = connssl->peer.sni? connssl->peer.sni : connssl->peer.hostname;
  1021. backend->cred->sni_hostname = curlx_convert_UTF8_to_tchar(snihost);
  1022. if(!backend->cred->sni_hostname)
  1023. return CURLE_OUT_OF_MEMORY;
  1024. }
  1025. /* Warn if SNI is disabled due to use of an IP address */
  1026. if(connssl->peer.is_ip_address) {
  1027. infof(data, "schannel: using IP address, SNI is not supported by OS.");
  1028. }
  1029. #ifdef HAS_ALPN
  1030. if(backend->use_alpn) {
  1031. int cur = 0;
  1032. int list_start_index = 0;
  1033. unsigned int *extension_len = NULL;
  1034. unsigned short* list_len = NULL;
  1035. struct alpn_proto_buf proto;
  1036. /* The first four bytes will be an unsigned int indicating number
  1037. of bytes of data in the rest of the buffer. */
  1038. extension_len = (unsigned int *)(void *)(&alpn_buffer[cur]);
  1039. cur += (int)sizeof(unsigned int);
  1040. /* The next four bytes are an indicator that this buffer will contain
  1041. ALPN data, as opposed to NPN, for example. */
  1042. *(unsigned int *)(void *)&alpn_buffer[cur] =
  1043. SecApplicationProtocolNegotiationExt_ALPN;
  1044. cur += (int)sizeof(unsigned int);
  1045. /* The next two bytes will be an unsigned short indicating the number
  1046. of bytes used to list the preferred protocols. */
  1047. list_len = (unsigned short*)(void *)(&alpn_buffer[cur]);
  1048. cur += (int)sizeof(unsigned short);
  1049. list_start_index = cur;
  1050. result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);
  1051. if(result) {
  1052. failf(data, "Error setting ALPN");
  1053. return CURLE_SSL_CONNECT_ERROR;
  1054. }
  1055. memcpy(&alpn_buffer[cur], proto.data, proto.len);
  1056. cur += proto.len;
  1057. *list_len = curlx_uitous(cur - list_start_index);
  1058. *extension_len = (unsigned int)(*list_len +
  1059. sizeof(unsigned int) + sizeof(unsigned short));
  1060. InitSecBuffer(&inbuf, SECBUFFER_APPLICATION_PROTOCOLS, alpn_buffer, cur);
  1061. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  1062. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  1063. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  1064. }
  1065. else {
  1066. InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  1067. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  1068. }
  1069. #else /* HAS_ALPN */
  1070. InitSecBuffer(&inbuf, SECBUFFER_EMPTY, NULL, 0);
  1071. InitSecBufferDesc(&inbuf_desc, &inbuf, 1);
  1072. #endif
  1073. /* setup output buffer */
  1074. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  1075. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  1076. /* security request flags */
  1077. backend->req_flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |
  1078. ISC_REQ_CONFIDENTIALITY | ISC_REQ_ALLOCATE_MEMORY |
  1079. ISC_REQ_STREAM;
  1080. if(!ssl_config->auto_client_cert) {
  1081. backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
  1082. }
  1083. /* allocate memory for the security context handle */
  1084. backend->ctxt = (struct Curl_schannel_ctxt *)
  1085. calloc(1, sizeof(struct Curl_schannel_ctxt));
  1086. if(!backend->ctxt) {
  1087. failf(data, "schannel: unable to allocate memory");
  1088. return CURLE_OUT_OF_MEMORY;
  1089. }
  1090. /* Schannel InitializeSecurityContext:
  1091. https://msdn.microsoft.com/en-us/library/windows/desktop/aa375924.aspx
  1092. At the moment we don't pass inbuf unless we're using ALPN since we only
  1093. use it for that, and Wine (for which we currently disable ALPN) is giving
  1094. us problems with inbuf regardless. https://github.com/curl/curl/issues/983
  1095. */
  1096. sspi_status = s_pSecFn->InitializeSecurityContext(
  1097. &backend->cred->cred_handle, NULL, backend->cred->sni_hostname,
  1098. backend->req_flags, 0, 0,
  1099. (backend->use_alpn ? &inbuf_desc : NULL),
  1100. 0, &backend->ctxt->ctxt_handle,
  1101. &outbuf_desc, &backend->ret_flags, &backend->ctxt->time_stamp);
  1102. if(sspi_status != SEC_I_CONTINUE_NEEDED) {
  1103. char buffer[STRERROR_LEN];
  1104. Curl_safefree(backend->ctxt);
  1105. switch(sspi_status) {
  1106. case SEC_E_INSUFFICIENT_MEMORY:
  1107. failf(data, "schannel: initial InitializeSecurityContext failed: %s",
  1108. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1109. return CURLE_OUT_OF_MEMORY;
  1110. case SEC_E_WRONG_PRINCIPAL:
  1111. failf(data, "schannel: SNI or certificate check failed: %s",
  1112. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1113. return CURLE_PEER_FAILED_VERIFICATION;
  1114. /*
  1115. case SEC_E_INVALID_HANDLE:
  1116. case SEC_E_INVALID_TOKEN:
  1117. case SEC_E_LOGON_DENIED:
  1118. case SEC_E_TARGET_UNKNOWN:
  1119. case SEC_E_NO_AUTHENTICATING_AUTHORITY:
  1120. case SEC_E_INTERNAL_ERROR:
  1121. case SEC_E_NO_CREDENTIALS:
  1122. case SEC_E_UNSUPPORTED_FUNCTION:
  1123. case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
  1124. */
  1125. default:
  1126. failf(data, "schannel: initial InitializeSecurityContext failed: %s",
  1127. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1128. return CURLE_SSL_CONNECT_ERROR;
  1129. }
  1130. }
  1131. DEBUGF(infof(data, "schannel: sending initial handshake data: "
  1132. "sending %lu bytes.", outbuf.cbBuffer));
  1133. /* send initial handshake data which is now stored in output buffer */
  1134. written = Curl_conn_cf_send(cf->next, data,
  1135. outbuf.pvBuffer, outbuf.cbBuffer,
  1136. &result);
  1137. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  1138. if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
  1139. failf(data, "schannel: failed to send initial handshake data: "
  1140. "sent %zd of %lu bytes", written, outbuf.cbBuffer);
  1141. return CURLE_SSL_CONNECT_ERROR;
  1142. }
  1143. DEBUGF(infof(data, "schannel: sent initial handshake data: "
  1144. "sent %zd bytes", written));
  1145. backend->recv_unrecoverable_err = CURLE_OK;
  1146. backend->recv_sspi_close_notify = false;
  1147. backend->recv_connection_closed = false;
  1148. backend->recv_renegotiating = false;
  1149. backend->encdata_is_incomplete = false;
  1150. /* continue to second handshake step */
  1151. connssl->connecting_state = ssl_connect_2;
  1152. return CURLE_OK;
  1153. }
  1154. static CURLcode
  1155. schannel_connect_step2(struct Curl_cfilter *cf, struct Curl_easy *data)
  1156. {
  1157. struct ssl_connect_data *connssl = cf->ctx;
  1158. struct schannel_ssl_backend_data *backend =
  1159. (struct schannel_ssl_backend_data *)connssl->backend;
  1160. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1161. int i;
  1162. ssize_t nread = -1, written = -1;
  1163. unsigned char *reallocated_buffer;
  1164. SecBuffer outbuf[3];
  1165. SecBufferDesc outbuf_desc;
  1166. SecBuffer inbuf[2];
  1167. SecBufferDesc inbuf_desc;
  1168. SECURITY_STATUS sspi_status = SEC_E_OK;
  1169. CURLcode result;
  1170. bool doread;
  1171. const char *pubkey_ptr;
  1172. DEBUGASSERT(backend);
  1173. doread = (connssl->connecting_state != ssl_connect_2_writing) ? TRUE : FALSE;
  1174. DEBUGF(infof(data,
  1175. "schannel: SSL/TLS connection with %s port %d (step 2/3)",
  1176. connssl->peer.hostname, connssl->port));
  1177. if(!backend->cred || !backend->ctxt)
  1178. return CURLE_SSL_CONNECT_ERROR;
  1179. /* buffer to store previously received and decrypted data */
  1180. if(!backend->decdata_buffer) {
  1181. backend->decdata_offset = 0;
  1182. backend->decdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  1183. backend->decdata_buffer = malloc(backend->decdata_length);
  1184. if(!backend->decdata_buffer) {
  1185. failf(data, "schannel: unable to allocate memory");
  1186. return CURLE_OUT_OF_MEMORY;
  1187. }
  1188. }
  1189. /* buffer to store previously received and encrypted data */
  1190. if(!backend->encdata_buffer) {
  1191. backend->encdata_is_incomplete = false;
  1192. backend->encdata_offset = 0;
  1193. backend->encdata_length = CURL_SCHANNEL_BUFFER_INIT_SIZE;
  1194. backend->encdata_buffer = malloc(backend->encdata_length);
  1195. if(!backend->encdata_buffer) {
  1196. failf(data, "schannel: unable to allocate memory");
  1197. return CURLE_OUT_OF_MEMORY;
  1198. }
  1199. }
  1200. /* if we need a bigger buffer to read a full message, increase buffer now */
  1201. if(backend->encdata_length - backend->encdata_offset <
  1202. CURL_SCHANNEL_BUFFER_FREE_SIZE) {
  1203. /* increase internal encrypted data buffer */
  1204. size_t reallocated_length = backend->encdata_offset +
  1205. CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1206. reallocated_buffer = realloc(backend->encdata_buffer,
  1207. reallocated_length);
  1208. if(!reallocated_buffer) {
  1209. failf(data, "schannel: unable to re-allocate memory");
  1210. return CURLE_OUT_OF_MEMORY;
  1211. }
  1212. else {
  1213. backend->encdata_buffer = reallocated_buffer;
  1214. backend->encdata_length = reallocated_length;
  1215. }
  1216. }
  1217. for(;;) {
  1218. if(doread) {
  1219. /* read encrypted handshake data from socket */
  1220. nread = Curl_conn_cf_recv(cf->next, data,
  1221. (char *) (backend->encdata_buffer +
  1222. backend->encdata_offset),
  1223. backend->encdata_length -
  1224. backend->encdata_offset,
  1225. &result);
  1226. if(result == CURLE_AGAIN) {
  1227. if(connssl->connecting_state != ssl_connect_2_writing)
  1228. connssl->connecting_state = ssl_connect_2_reading;
  1229. DEBUGF(infof(data, "schannel: failed to receive handshake, "
  1230. "need more data"));
  1231. return CURLE_OK;
  1232. }
  1233. else if((result != CURLE_OK) || (nread == 0)) {
  1234. failf(data, "schannel: failed to receive handshake, "
  1235. "SSL/TLS connection failed");
  1236. return CURLE_SSL_CONNECT_ERROR;
  1237. }
  1238. /* increase encrypted data buffer offset */
  1239. backend->encdata_offset += nread;
  1240. backend->encdata_is_incomplete = false;
  1241. DEBUGF(infof(data, "schannel: encrypted data got %zd", nread));
  1242. }
  1243. DEBUGF(infof(data,
  1244. "schannel: encrypted data buffer: offset %zu length %zu",
  1245. backend->encdata_offset, backend->encdata_length));
  1246. /* setup input buffers */
  1247. InitSecBuffer(&inbuf[0], SECBUFFER_TOKEN, malloc(backend->encdata_offset),
  1248. curlx_uztoul(backend->encdata_offset));
  1249. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  1250. InitSecBufferDesc(&inbuf_desc, inbuf, 2);
  1251. /* setup output buffers */
  1252. InitSecBuffer(&outbuf[0], SECBUFFER_TOKEN, NULL, 0);
  1253. InitSecBuffer(&outbuf[1], SECBUFFER_ALERT, NULL, 0);
  1254. InitSecBuffer(&outbuf[2], SECBUFFER_EMPTY, NULL, 0);
  1255. InitSecBufferDesc(&outbuf_desc, outbuf, 3);
  1256. if(!inbuf[0].pvBuffer) {
  1257. failf(data, "schannel: unable to allocate memory");
  1258. return CURLE_OUT_OF_MEMORY;
  1259. }
  1260. /* copy received handshake data into input buffer */
  1261. memcpy(inbuf[0].pvBuffer, backend->encdata_buffer,
  1262. backend->encdata_offset);
  1263. sspi_status = s_pSecFn->InitializeSecurityContext(
  1264. &backend->cred->cred_handle, &backend->ctxt->ctxt_handle,
  1265. backend->cred->sni_hostname, backend->req_flags,
  1266. 0, 0, &inbuf_desc, 0, NULL,
  1267. &outbuf_desc, &backend->ret_flags, &backend->ctxt->time_stamp);
  1268. /* free buffer for received handshake data */
  1269. Curl_safefree(inbuf[0].pvBuffer);
  1270. /* check if the handshake was incomplete */
  1271. if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  1272. backend->encdata_is_incomplete = true;
  1273. connssl->connecting_state = ssl_connect_2_reading;
  1274. DEBUGF(infof(data,
  1275. "schannel: received incomplete message, need more data"));
  1276. return CURLE_OK;
  1277. }
  1278. /* If the server has requested a client certificate, attempt to continue
  1279. the handshake without one. This will allow connections to servers which
  1280. request a client certificate but do not require it. */
  1281. if(sspi_status == SEC_I_INCOMPLETE_CREDENTIALS &&
  1282. !(backend->req_flags & ISC_REQ_USE_SUPPLIED_CREDS)) {
  1283. backend->req_flags |= ISC_REQ_USE_SUPPLIED_CREDS;
  1284. connssl->connecting_state = ssl_connect_2_writing;
  1285. DEBUGF(infof(data,
  1286. "schannel: a client certificate has been requested"));
  1287. return CURLE_OK;
  1288. }
  1289. /* check if the handshake needs to be continued */
  1290. if(sspi_status == SEC_I_CONTINUE_NEEDED || sspi_status == SEC_E_OK) {
  1291. for(i = 0; i < 3; i++) {
  1292. /* search for handshake tokens that need to be send */
  1293. if(outbuf[i].BufferType == SECBUFFER_TOKEN && outbuf[i].cbBuffer > 0) {
  1294. DEBUGF(infof(data, "schannel: sending next handshake data: "
  1295. "sending %lu bytes.", outbuf[i].cbBuffer));
  1296. /* send handshake token to server */
  1297. written = Curl_conn_cf_send(cf->next, data,
  1298. outbuf[i].pvBuffer, outbuf[i].cbBuffer,
  1299. &result);
  1300. if((result != CURLE_OK) ||
  1301. (outbuf[i].cbBuffer != (size_t) written)) {
  1302. failf(data, "schannel: failed to send next handshake data: "
  1303. "sent %zd of %lu bytes", written, outbuf[i].cbBuffer);
  1304. return CURLE_SSL_CONNECT_ERROR;
  1305. }
  1306. }
  1307. /* free obsolete buffer */
  1308. if(outbuf[i].pvBuffer) {
  1309. s_pSecFn->FreeContextBuffer(outbuf[i].pvBuffer);
  1310. }
  1311. }
  1312. }
  1313. else {
  1314. char buffer[STRERROR_LEN];
  1315. switch(sspi_status) {
  1316. case SEC_E_INSUFFICIENT_MEMORY:
  1317. failf(data, "schannel: next InitializeSecurityContext failed: %s",
  1318. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1319. return CURLE_OUT_OF_MEMORY;
  1320. case SEC_E_WRONG_PRINCIPAL:
  1321. failf(data, "schannel: SNI or certificate check failed: %s",
  1322. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1323. return CURLE_PEER_FAILED_VERIFICATION;
  1324. case SEC_E_UNTRUSTED_ROOT:
  1325. failf(data, "schannel: %s",
  1326. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1327. return CURLE_PEER_FAILED_VERIFICATION;
  1328. /*
  1329. case SEC_E_INVALID_HANDLE:
  1330. case SEC_E_INVALID_TOKEN:
  1331. case SEC_E_LOGON_DENIED:
  1332. case SEC_E_TARGET_UNKNOWN:
  1333. case SEC_E_NO_AUTHENTICATING_AUTHORITY:
  1334. case SEC_E_INTERNAL_ERROR:
  1335. case SEC_E_NO_CREDENTIALS:
  1336. case SEC_E_UNSUPPORTED_FUNCTION:
  1337. case SEC_E_APPLICATION_PROTOCOL_MISMATCH:
  1338. */
  1339. default:
  1340. failf(data, "schannel: next InitializeSecurityContext failed: %s",
  1341. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  1342. return CURLE_SSL_CONNECT_ERROR;
  1343. }
  1344. }
  1345. /* check if there was additional remaining encrypted data */
  1346. if(inbuf[1].BufferType == SECBUFFER_EXTRA && inbuf[1].cbBuffer > 0) {
  1347. DEBUGF(infof(data, "schannel: encrypted data length: %lu",
  1348. inbuf[1].cbBuffer));
  1349. /*
  1350. There are two cases where we could be getting extra data here:
  1351. 1) If we're renegotiating a connection and the handshake is already
  1352. complete (from the server perspective), it can encrypted app data
  1353. (not handshake data) in an extra buffer at this point.
  1354. 2) (sspi_status == SEC_I_CONTINUE_NEEDED) We are negotiating a
  1355. connection and this extra data is part of the handshake.
  1356. We should process the data immediately; waiting for the socket to
  1357. be ready may fail since the server is done sending handshake data.
  1358. */
  1359. /* check if the remaining data is less than the total amount
  1360. and therefore begins after the already processed data */
  1361. if(backend->encdata_offset > inbuf[1].cbBuffer) {
  1362. memmove(backend->encdata_buffer,
  1363. (backend->encdata_buffer + backend->encdata_offset) -
  1364. inbuf[1].cbBuffer, inbuf[1].cbBuffer);
  1365. backend->encdata_offset = inbuf[1].cbBuffer;
  1366. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  1367. doread = FALSE;
  1368. continue;
  1369. }
  1370. }
  1371. }
  1372. else {
  1373. backend->encdata_offset = 0;
  1374. }
  1375. break;
  1376. }
  1377. /* check if the handshake needs to be continued */
  1378. if(sspi_status == SEC_I_CONTINUE_NEEDED) {
  1379. connssl->connecting_state = ssl_connect_2_reading;
  1380. return CURLE_OK;
  1381. }
  1382. /* check if the handshake is complete */
  1383. if(sspi_status == SEC_E_OK) {
  1384. connssl->connecting_state = ssl_connect_3;
  1385. DEBUGF(infof(data, "schannel: SSL/TLS handshake complete"));
  1386. }
  1387. pubkey_ptr = Curl_ssl_cf_is_proxy(cf)?
  1388. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  1389. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  1390. if(pubkey_ptr) {
  1391. result = schannel_pkp_pin_peer_pubkey(cf, data, pubkey_ptr);
  1392. if(result) {
  1393. failf(data, "SSL: public key does not match pinned public key");
  1394. return result;
  1395. }
  1396. }
  1397. #ifdef HAS_MANUAL_VERIFY_API
  1398. if(conn_config->verifypeer && backend->use_manual_cred_validation) {
  1399. /* Certificate verification also verifies the hostname if verifyhost */
  1400. return Curl_verify_certificate(cf, data);
  1401. }
  1402. #endif
  1403. /* Verify the hostname manually when certificate verification is disabled,
  1404. because in that case Schannel won't verify it. */
  1405. if(!conn_config->verifypeer && conn_config->verifyhost)
  1406. return Curl_verify_host(cf, data);
  1407. return CURLE_OK;
  1408. }
  1409. static bool
  1410. valid_cert_encoding(const CERT_CONTEXT *cert_context)
  1411. {
  1412. return (cert_context != NULL) &&
  1413. ((cert_context->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
  1414. (cert_context->pbCertEncoded != NULL) &&
  1415. (cert_context->cbCertEncoded > 0);
  1416. }
  1417. typedef bool(*Read_crt_func)(const CERT_CONTEXT *ccert_context,
  1418. bool reverse_order, void *arg);
  1419. static void
  1420. traverse_cert_store(const CERT_CONTEXT *context, Read_crt_func func,
  1421. void *arg)
  1422. {
  1423. const CERT_CONTEXT *current_context = NULL;
  1424. bool should_continue = true;
  1425. bool first = true;
  1426. bool reverse_order = false;
  1427. while(should_continue &&
  1428. (current_context = CertEnumCertificatesInStore(
  1429. context->hCertStore,
  1430. current_context)) != NULL) {
  1431. /* Windows 11 22H2 OS Build 22621.674 or higher enumerates certificates in
  1432. leaf-to-root order while all previous versions of Windows enumerate
  1433. certificates in root-to-leaf order. Determine the order of enumeration
  1434. by comparing SECPKG_ATTR_REMOTE_CERT_CONTEXT's pbCertContext with the
  1435. first certificate's pbCertContext. */
  1436. if(first && context->pbCertEncoded != current_context->pbCertEncoded)
  1437. reverse_order = true;
  1438. should_continue = func(current_context, reverse_order, arg);
  1439. first = false;
  1440. }
  1441. if(current_context)
  1442. CertFreeCertificateContext(current_context);
  1443. }
  1444. static bool
  1445. cert_counter_callback(const CERT_CONTEXT *ccert_context, bool reverse_order,
  1446. void *certs_count)
  1447. {
  1448. (void)reverse_order; /* unused */
  1449. if(valid_cert_encoding(ccert_context))
  1450. (*(int *)certs_count)++;
  1451. return true;
  1452. }
  1453. struct Adder_args
  1454. {
  1455. struct Curl_easy *data;
  1456. CURLcode result;
  1457. int idx;
  1458. int certs_count;
  1459. };
  1460. static bool
  1461. add_cert_to_certinfo(const CERT_CONTEXT *ccert_context, bool reverse_order,
  1462. void *raw_arg)
  1463. {
  1464. struct Adder_args *args = (struct Adder_args*)raw_arg;
  1465. args->result = CURLE_OK;
  1466. if(valid_cert_encoding(ccert_context)) {
  1467. const char *beg = (const char *) ccert_context->pbCertEncoded;
  1468. const char *end = beg + ccert_context->cbCertEncoded;
  1469. int insert_index = reverse_order ? (args->certs_count - 1) - args->idx :
  1470. args->idx;
  1471. args->result = Curl_extract_certinfo(args->data, insert_index,
  1472. beg, end);
  1473. args->idx++;
  1474. }
  1475. return args->result == CURLE_OK;
  1476. }
  1477. static CURLcode
  1478. schannel_connect_step3(struct Curl_cfilter *cf, struct Curl_easy *data)
  1479. {
  1480. struct ssl_connect_data *connssl = cf->ctx;
  1481. struct schannel_ssl_backend_data *backend =
  1482. (struct schannel_ssl_backend_data *)connssl->backend;
  1483. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1484. CURLcode result = CURLE_OK;
  1485. SECURITY_STATUS sspi_status = SEC_E_OK;
  1486. CERT_CONTEXT *ccert_context = NULL;
  1487. #ifdef HAS_ALPN
  1488. SecPkgContext_ApplicationProtocol alpn_result;
  1489. #endif
  1490. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  1491. DEBUGASSERT(backend);
  1492. DEBUGF(infof(data,
  1493. "schannel: SSL/TLS connection with %s port %d (step 3/3)",
  1494. connssl->peer.hostname, connssl->port));
  1495. if(!backend->cred)
  1496. return CURLE_SSL_CONNECT_ERROR;
  1497. /* check if the required context attributes are met */
  1498. if(backend->ret_flags != backend->req_flags) {
  1499. if(!(backend->ret_flags & ISC_RET_SEQUENCE_DETECT))
  1500. failf(data, "schannel: failed to setup sequence detection");
  1501. if(!(backend->ret_flags & ISC_RET_REPLAY_DETECT))
  1502. failf(data, "schannel: failed to setup replay detection");
  1503. if(!(backend->ret_flags & ISC_RET_CONFIDENTIALITY))
  1504. failf(data, "schannel: failed to setup confidentiality");
  1505. if(!(backend->ret_flags & ISC_RET_ALLOCATED_MEMORY))
  1506. failf(data, "schannel: failed to setup memory allocation");
  1507. if(!(backend->ret_flags & ISC_RET_STREAM))
  1508. failf(data, "schannel: failed to setup stream orientation");
  1509. return CURLE_SSL_CONNECT_ERROR;
  1510. }
  1511. #ifdef HAS_ALPN
  1512. if(backend->use_alpn) {
  1513. sspi_status =
  1514. s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
  1515. SECPKG_ATTR_APPLICATION_PROTOCOL,
  1516. &alpn_result);
  1517. if(sspi_status != SEC_E_OK) {
  1518. failf(data, "schannel: failed to retrieve ALPN result");
  1519. return CURLE_SSL_CONNECT_ERROR;
  1520. }
  1521. if(alpn_result.ProtoNegoStatus ==
  1522. SecApplicationProtocolNegotiationStatus_Success) {
  1523. unsigned char prev_alpn = cf->conn->alpn;
  1524. Curl_alpn_set_negotiated(cf, data, alpn_result.ProtocolId,
  1525. alpn_result.ProtocolIdSize);
  1526. if(backend->recv_renegotiating) {
  1527. if(prev_alpn != cf->conn->alpn &&
  1528. prev_alpn != CURL_HTTP_VERSION_NONE) {
  1529. /* Renegotiation selected a different protocol now, we cannot
  1530. * deal with this */
  1531. failf(data, "schannel: server selected an ALPN protocol too late");
  1532. return CURLE_SSL_CONNECT_ERROR;
  1533. }
  1534. }
  1535. }
  1536. else {
  1537. if(!backend->recv_renegotiating)
  1538. Curl_alpn_set_negotiated(cf, data, NULL, 0);
  1539. }
  1540. }
  1541. #endif
  1542. /* save the current session data for possible reuse */
  1543. if(ssl_config->primary.sessionid) {
  1544. bool incache;
  1545. bool added = FALSE;
  1546. struct Curl_schannel_cred *old_cred = NULL;
  1547. Curl_ssl_sessionid_lock(data);
  1548. incache = !(Curl_ssl_getsessionid(cf, data, (void **)&old_cred, NULL));
  1549. if(incache) {
  1550. if(old_cred != backend->cred) {
  1551. DEBUGF(infof(data,
  1552. "schannel: old credential handle is stale, removing"));
  1553. /* we're not taking old_cred ownership here, no refcount++ is needed */
  1554. Curl_ssl_delsessionid(data, (void *)old_cred);
  1555. incache = FALSE;
  1556. }
  1557. }
  1558. if(!incache) {
  1559. result = Curl_ssl_addsessionid(cf, data, backend->cred,
  1560. sizeof(struct Curl_schannel_cred),
  1561. &added);
  1562. if(result) {
  1563. Curl_ssl_sessionid_unlock(data);
  1564. failf(data, "schannel: failed to store credential handle");
  1565. return result;
  1566. }
  1567. else if(added) {
  1568. /* this cred session is now also referenced by sessionid cache */
  1569. backend->cred->refcount++;
  1570. DEBUGF(infof(data,
  1571. "schannel: stored credential handle in session cache"));
  1572. }
  1573. }
  1574. Curl_ssl_sessionid_unlock(data);
  1575. }
  1576. if(data->set.ssl.certinfo) {
  1577. int certs_count = 0;
  1578. sspi_status =
  1579. s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
  1580. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  1581. &ccert_context);
  1582. if((sspi_status != SEC_E_OK) || !ccert_context) {
  1583. failf(data, "schannel: failed to retrieve remote cert context");
  1584. return CURLE_PEER_FAILED_VERIFICATION;
  1585. }
  1586. traverse_cert_store(ccert_context, cert_counter_callback, &certs_count);
  1587. result = Curl_ssl_init_certinfo(data, certs_count);
  1588. if(!result) {
  1589. struct Adder_args args;
  1590. args.data = data;
  1591. args.idx = 0;
  1592. args.certs_count = certs_count;
  1593. traverse_cert_store(ccert_context, add_cert_to_certinfo, &args);
  1594. result = args.result;
  1595. }
  1596. CertFreeCertificateContext(ccert_context);
  1597. if(result)
  1598. return result;
  1599. }
  1600. connssl->connecting_state = ssl_connect_done;
  1601. return CURLE_OK;
  1602. }
  1603. static CURLcode
  1604. schannel_connect_common(struct Curl_cfilter *cf,
  1605. struct Curl_easy *data,
  1606. bool nonblocking, bool *done)
  1607. {
  1608. CURLcode result;
  1609. struct ssl_connect_data *connssl = cf->ctx;
  1610. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  1611. timediff_t timeout_ms;
  1612. int what;
  1613. /* check if the connection has already been established */
  1614. if(ssl_connection_complete == connssl->state) {
  1615. *done = TRUE;
  1616. return CURLE_OK;
  1617. }
  1618. if(ssl_connect_1 == connssl->connecting_state) {
  1619. /* check out how much more time we're allowed */
  1620. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1621. if(timeout_ms < 0) {
  1622. /* no need to continue if time already is up */
  1623. failf(data, "SSL/TLS connection timeout");
  1624. return CURLE_OPERATION_TIMEDOUT;
  1625. }
  1626. result = schannel_connect_step1(cf, data);
  1627. if(result)
  1628. return result;
  1629. }
  1630. while(ssl_connect_2 == connssl->connecting_state ||
  1631. ssl_connect_2_reading == connssl->connecting_state ||
  1632. ssl_connect_2_writing == connssl->connecting_state) {
  1633. /* check out how much more time we're allowed */
  1634. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  1635. if(timeout_ms < 0) {
  1636. /* no need to continue if time already is up */
  1637. failf(data, "SSL/TLS connection timeout");
  1638. return CURLE_OPERATION_TIMEDOUT;
  1639. }
  1640. /* if ssl is expecting something, check if it's available. */
  1641. if(connssl->connecting_state == ssl_connect_2_reading
  1642. || connssl->connecting_state == ssl_connect_2_writing) {
  1643. curl_socket_t writefd = ssl_connect_2_writing ==
  1644. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  1645. curl_socket_t readfd = ssl_connect_2_reading ==
  1646. connssl->connecting_state ? sockfd : CURL_SOCKET_BAD;
  1647. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  1648. nonblocking ? 0 : timeout_ms);
  1649. if(what < 0) {
  1650. /* fatal error */
  1651. failf(data, "select/poll on SSL/TLS socket, errno: %d", SOCKERRNO);
  1652. return CURLE_SSL_CONNECT_ERROR;
  1653. }
  1654. else if(0 == what) {
  1655. if(nonblocking) {
  1656. *done = FALSE;
  1657. return CURLE_OK;
  1658. }
  1659. else {
  1660. /* timeout */
  1661. failf(data, "SSL/TLS connection timeout");
  1662. return CURLE_OPERATION_TIMEDOUT;
  1663. }
  1664. }
  1665. /* socket is readable or writable */
  1666. }
  1667. /* Run transaction, and return to the caller if it failed or if
  1668. * this connection is part of a multi handle and this loop would
  1669. * execute again. This permits the owner of a multi handle to
  1670. * abort a connection attempt before step2 has completed while
  1671. * ensuring that a client using select() or epoll() will always
  1672. * have a valid fdset to wait on.
  1673. */
  1674. result = schannel_connect_step2(cf, data);
  1675. if(result || (nonblocking &&
  1676. (ssl_connect_2 == connssl->connecting_state ||
  1677. ssl_connect_2_reading == connssl->connecting_state ||
  1678. ssl_connect_2_writing == connssl->connecting_state)))
  1679. return result;
  1680. } /* repeat step2 until all transactions are done. */
  1681. if(ssl_connect_3 == connssl->connecting_state) {
  1682. result = schannel_connect_step3(cf, data);
  1683. if(result)
  1684. return result;
  1685. }
  1686. if(ssl_connect_done == connssl->connecting_state) {
  1687. connssl->state = ssl_connection_complete;
  1688. #ifdef SECPKG_ATTR_ENDPOINT_BINDINGS
  1689. /* When SSPI is used in combination with Schannel
  1690. * we need the Schannel context to create the Schannel
  1691. * binding to pass the IIS extended protection checks.
  1692. * Available on Windows 7 or later.
  1693. */
  1694. {
  1695. struct schannel_ssl_backend_data *backend =
  1696. (struct schannel_ssl_backend_data *)connssl->backend;
  1697. DEBUGASSERT(backend);
  1698. cf->conn->sslContext = &backend->ctxt->ctxt_handle;
  1699. }
  1700. #endif
  1701. *done = TRUE;
  1702. }
  1703. else
  1704. *done = FALSE;
  1705. /* reset our connection state machine */
  1706. connssl->connecting_state = ssl_connect_1;
  1707. return CURLE_OK;
  1708. }
  1709. static ssize_t
  1710. schannel_send(struct Curl_cfilter *cf, struct Curl_easy *data,
  1711. const void *buf, size_t len, CURLcode *err)
  1712. {
  1713. ssize_t written = -1;
  1714. size_t data_len = 0;
  1715. unsigned char *ptr = NULL;
  1716. struct ssl_connect_data *connssl = cf->ctx;
  1717. SecBuffer outbuf[4];
  1718. SecBufferDesc outbuf_desc;
  1719. SECURITY_STATUS sspi_status = SEC_E_OK;
  1720. CURLcode result;
  1721. struct schannel_ssl_backend_data *backend =
  1722. (struct schannel_ssl_backend_data *)connssl->backend;
  1723. DEBUGASSERT(backend);
  1724. /* check if the maximum stream sizes were queried */
  1725. if(backend->stream_sizes.cbMaximumMessage == 0) {
  1726. sspi_status = s_pSecFn->QueryContextAttributes(
  1727. &backend->ctxt->ctxt_handle,
  1728. SECPKG_ATTR_STREAM_SIZES,
  1729. &backend->stream_sizes);
  1730. if(sspi_status != SEC_E_OK) {
  1731. *err = CURLE_SEND_ERROR;
  1732. return -1;
  1733. }
  1734. }
  1735. /* check if the buffer is longer than the maximum message length */
  1736. if(len > backend->stream_sizes.cbMaximumMessage) {
  1737. len = backend->stream_sizes.cbMaximumMessage;
  1738. }
  1739. /* calculate the complete message length and allocate a buffer for it */
  1740. data_len = backend->stream_sizes.cbHeader + len +
  1741. backend->stream_sizes.cbTrailer;
  1742. ptr = (unsigned char *) malloc(data_len);
  1743. if(!ptr) {
  1744. *err = CURLE_OUT_OF_MEMORY;
  1745. return -1;
  1746. }
  1747. /* setup output buffers (header, data, trailer, empty) */
  1748. InitSecBuffer(&outbuf[0], SECBUFFER_STREAM_HEADER,
  1749. ptr, backend->stream_sizes.cbHeader);
  1750. InitSecBuffer(&outbuf[1], SECBUFFER_DATA,
  1751. ptr + backend->stream_sizes.cbHeader, curlx_uztoul(len));
  1752. InitSecBuffer(&outbuf[2], SECBUFFER_STREAM_TRAILER,
  1753. ptr + backend->stream_sizes.cbHeader + len,
  1754. backend->stream_sizes.cbTrailer);
  1755. InitSecBuffer(&outbuf[3], SECBUFFER_EMPTY, NULL, 0);
  1756. InitSecBufferDesc(&outbuf_desc, outbuf, 4);
  1757. /* copy data into output buffer */
  1758. memcpy(outbuf[1].pvBuffer, buf, len);
  1759. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375390.aspx */
  1760. sspi_status = s_pSecFn->EncryptMessage(&backend->ctxt->ctxt_handle, 0,
  1761. &outbuf_desc, 0);
  1762. /* check if the message was encrypted */
  1763. if(sspi_status == SEC_E_OK) {
  1764. written = 0;
  1765. /* send the encrypted message including header, data and trailer */
  1766. len = outbuf[0].cbBuffer + outbuf[1].cbBuffer + outbuf[2].cbBuffer;
  1767. /*
  1768. It's important to send the full message which includes the header,
  1769. encrypted payload, and trailer. Until the client receives all the
  1770. data a coherent message has not been delivered and the client
  1771. can't read any of it.
  1772. If we wanted to buffer the unwritten encrypted bytes, we would
  1773. tell the client that all data it has requested to be sent has been
  1774. sent. The unwritten encrypted bytes would be the first bytes to
  1775. send on the next invocation.
  1776. Here's the catch with this - if we tell the client that all the
  1777. bytes have been sent, will the client call this method again to
  1778. send the buffered data? Looking at who calls this function, it
  1779. seems the answer is NO.
  1780. */
  1781. /* send entire message or fail */
  1782. while(len > (size_t)written) {
  1783. ssize_t this_write = 0;
  1784. int what;
  1785. timediff_t timeout_ms = Curl_timeleft(data, NULL, FALSE);
  1786. if(timeout_ms < 0) {
  1787. /* we already got the timeout */
  1788. failf(data, "schannel: timed out sending data "
  1789. "(bytes sent: %zd)", written);
  1790. *err = CURLE_OPERATION_TIMEDOUT;
  1791. written = -1;
  1792. break;
  1793. }
  1794. else if(!timeout_ms)
  1795. timeout_ms = TIMEDIFF_T_MAX;
  1796. what = SOCKET_WRITABLE(Curl_conn_cf_get_socket(cf, data), timeout_ms);
  1797. if(what < 0) {
  1798. /* fatal error */
  1799. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  1800. *err = CURLE_SEND_ERROR;
  1801. written = -1;
  1802. break;
  1803. }
  1804. else if(0 == what) {
  1805. failf(data, "schannel: timed out sending data "
  1806. "(bytes sent: %zd)", written);
  1807. *err = CURLE_OPERATION_TIMEDOUT;
  1808. written = -1;
  1809. break;
  1810. }
  1811. /* socket is writable */
  1812. this_write = Curl_conn_cf_send(cf->next, data,
  1813. ptr + written, len - written,
  1814. &result);
  1815. if(result == CURLE_AGAIN)
  1816. continue;
  1817. else if(result != CURLE_OK) {
  1818. *err = result;
  1819. written = -1;
  1820. break;
  1821. }
  1822. written += this_write;
  1823. }
  1824. }
  1825. else if(sspi_status == SEC_E_INSUFFICIENT_MEMORY) {
  1826. *err = CURLE_OUT_OF_MEMORY;
  1827. }
  1828. else{
  1829. *err = CURLE_SEND_ERROR;
  1830. }
  1831. Curl_safefree(ptr);
  1832. if(len == (size_t)written)
  1833. /* Encrypted message including header, data and trailer entirely sent.
  1834. The return value is the number of unencrypted bytes that were sent. */
  1835. written = outbuf[1].cbBuffer;
  1836. return written;
  1837. }
  1838. static ssize_t
  1839. schannel_recv(struct Curl_cfilter *cf, struct Curl_easy *data,
  1840. char *buf, size_t len, CURLcode *err)
  1841. {
  1842. size_t size = 0;
  1843. ssize_t nread = -1;
  1844. struct ssl_connect_data *connssl = cf->ctx;
  1845. unsigned char *reallocated_buffer;
  1846. size_t reallocated_length;
  1847. bool done = FALSE;
  1848. SecBuffer inbuf[4];
  1849. SecBufferDesc inbuf_desc;
  1850. SECURITY_STATUS sspi_status = SEC_E_OK;
  1851. /* we want the length of the encrypted buffer to be at least large enough
  1852. that it can hold all the bytes requested and some TLS record overhead. */
  1853. size_t min_encdata_length = len + CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1854. struct schannel_ssl_backend_data *backend =
  1855. (struct schannel_ssl_backend_data *)connssl->backend;
  1856. DEBUGASSERT(backend);
  1857. /****************************************************************************
  1858. * Don't return or set backend->recv_unrecoverable_err unless in the cleanup.
  1859. * The pattern for return error is set *err, optional infof, goto cleanup.
  1860. *
  1861. * Our priority is to always return as much decrypted data to the caller as
  1862. * possible, even if an error occurs. The state of the decrypted buffer must
  1863. * always be valid. Transfer of decrypted data to the caller's buffer is
  1864. * handled in the cleanup.
  1865. */
  1866. DEBUGF(infof(data, "schannel: client wants to read %zu bytes", len));
  1867. *err = CURLE_OK;
  1868. if(len && len <= backend->decdata_offset) {
  1869. infof(data, "schannel: enough decrypted data is already available");
  1870. goto cleanup;
  1871. }
  1872. else if(backend->recv_unrecoverable_err) {
  1873. *err = backend->recv_unrecoverable_err;
  1874. infof(data, "schannel: an unrecoverable error occurred in a prior call");
  1875. goto cleanup;
  1876. }
  1877. else if(backend->recv_sspi_close_notify) {
  1878. /* once a server has indicated shutdown there is no more encrypted data */
  1879. infof(data, "schannel: server indicated shutdown in a prior call");
  1880. goto cleanup;
  1881. }
  1882. /* It's debatable what to return when !len. Regardless we can't return
  1883. immediately because there may be data to decrypt (in the case we want to
  1884. decrypt all encrypted cached data) so handle !len later in cleanup.
  1885. */
  1886. else if(len && !backend->recv_connection_closed) {
  1887. /* increase enc buffer in order to fit the requested amount of data */
  1888. size = backend->encdata_length - backend->encdata_offset;
  1889. if(size < CURL_SCHANNEL_BUFFER_FREE_SIZE ||
  1890. backend->encdata_length < min_encdata_length) {
  1891. reallocated_length = backend->encdata_offset +
  1892. CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1893. if(reallocated_length < min_encdata_length) {
  1894. reallocated_length = min_encdata_length;
  1895. }
  1896. reallocated_buffer = realloc(backend->encdata_buffer,
  1897. reallocated_length);
  1898. if(!reallocated_buffer) {
  1899. *err = CURLE_OUT_OF_MEMORY;
  1900. failf(data, "schannel: unable to re-allocate memory");
  1901. goto cleanup;
  1902. }
  1903. backend->encdata_buffer = reallocated_buffer;
  1904. backend->encdata_length = reallocated_length;
  1905. size = backend->encdata_length - backend->encdata_offset;
  1906. DEBUGF(infof(data, "schannel: encdata_buffer resized %zu",
  1907. backend->encdata_length));
  1908. }
  1909. DEBUGF(infof(data,
  1910. "schannel: encrypted data buffer: offset %zu length %zu",
  1911. backend->encdata_offset, backend->encdata_length));
  1912. /* read encrypted data from socket */
  1913. nread = Curl_conn_cf_recv(cf->next, data,
  1914. (char *)(backend->encdata_buffer +
  1915. backend->encdata_offset),
  1916. size, err);
  1917. if(*err) {
  1918. nread = -1;
  1919. if(*err == CURLE_AGAIN)
  1920. DEBUGF(infof(data,
  1921. "schannel: recv returned CURLE_AGAIN"));
  1922. else if(*err == CURLE_RECV_ERROR)
  1923. infof(data, "schannel: recv returned CURLE_RECV_ERROR");
  1924. else
  1925. infof(data, "schannel: recv returned error %d", *err);
  1926. }
  1927. else if(nread == 0) {
  1928. backend->recv_connection_closed = true;
  1929. DEBUGF(infof(data, "schannel: server closed the connection"));
  1930. }
  1931. else if(nread > 0) {
  1932. backend->encdata_offset += (size_t)nread;
  1933. backend->encdata_is_incomplete = false;
  1934. DEBUGF(infof(data, "schannel: encrypted data got %zd", nread));
  1935. }
  1936. }
  1937. DEBUGF(infof(data,
  1938. "schannel: encrypted data buffer: offset %zu length %zu",
  1939. backend->encdata_offset, backend->encdata_length));
  1940. /* decrypt loop */
  1941. while(backend->encdata_offset > 0 && sspi_status == SEC_E_OK &&
  1942. (!len || backend->decdata_offset < len ||
  1943. backend->recv_connection_closed)) {
  1944. /* prepare data buffer for DecryptMessage call */
  1945. InitSecBuffer(&inbuf[0], SECBUFFER_DATA, backend->encdata_buffer,
  1946. curlx_uztoul(backend->encdata_offset));
  1947. /* we need 3 more empty input buffers for possible output */
  1948. InitSecBuffer(&inbuf[1], SECBUFFER_EMPTY, NULL, 0);
  1949. InitSecBuffer(&inbuf[2], SECBUFFER_EMPTY, NULL, 0);
  1950. InitSecBuffer(&inbuf[3], SECBUFFER_EMPTY, NULL, 0);
  1951. InitSecBufferDesc(&inbuf_desc, inbuf, 4);
  1952. /* https://msdn.microsoft.com/en-us/library/windows/desktop/aa375348.aspx
  1953. */
  1954. sspi_status = s_pSecFn->DecryptMessage(&backend->ctxt->ctxt_handle,
  1955. &inbuf_desc, 0, NULL);
  1956. /* check if everything went fine (server may want to renegotiate
  1957. or shutdown the connection context) */
  1958. if(sspi_status == SEC_E_OK || sspi_status == SEC_I_RENEGOTIATE ||
  1959. sspi_status == SEC_I_CONTEXT_EXPIRED) {
  1960. /* check for successfully decrypted data, even before actual
  1961. renegotiation or shutdown of the connection context */
  1962. if(inbuf[1].BufferType == SECBUFFER_DATA) {
  1963. DEBUGF(infof(data, "schannel: decrypted data length: %lu",
  1964. inbuf[1].cbBuffer));
  1965. /* increase buffer in order to fit the received amount of data */
  1966. size = inbuf[1].cbBuffer > CURL_SCHANNEL_BUFFER_FREE_SIZE ?
  1967. inbuf[1].cbBuffer : CURL_SCHANNEL_BUFFER_FREE_SIZE;
  1968. if(backend->decdata_length - backend->decdata_offset < size ||
  1969. backend->decdata_length < len) {
  1970. /* increase internal decrypted data buffer */
  1971. reallocated_length = backend->decdata_offset + size;
  1972. /* make sure that the requested amount of data fits */
  1973. if(reallocated_length < len) {
  1974. reallocated_length = len;
  1975. }
  1976. reallocated_buffer = realloc(backend->decdata_buffer,
  1977. reallocated_length);
  1978. if(!reallocated_buffer) {
  1979. *err = CURLE_OUT_OF_MEMORY;
  1980. failf(data, "schannel: unable to re-allocate memory");
  1981. goto cleanup;
  1982. }
  1983. backend->decdata_buffer = reallocated_buffer;
  1984. backend->decdata_length = reallocated_length;
  1985. }
  1986. /* copy decrypted data to internal buffer */
  1987. size = inbuf[1].cbBuffer;
  1988. if(size) {
  1989. memcpy(backend->decdata_buffer + backend->decdata_offset,
  1990. inbuf[1].pvBuffer, size);
  1991. backend->decdata_offset += size;
  1992. }
  1993. DEBUGF(infof(data, "schannel: decrypted data added: %zu", size));
  1994. DEBUGF(infof(data,
  1995. "schannel: decrypted cached: offset %zu length %zu",
  1996. backend->decdata_offset, backend->decdata_length));
  1997. }
  1998. /* check for remaining encrypted data */
  1999. if(inbuf[3].BufferType == SECBUFFER_EXTRA && inbuf[3].cbBuffer > 0) {
  2000. DEBUGF(infof(data, "schannel: encrypted data length: %lu",
  2001. inbuf[3].cbBuffer));
  2002. /* check if the remaining data is less than the total amount
  2003. * and therefore begins after the already processed data
  2004. */
  2005. if(backend->encdata_offset > inbuf[3].cbBuffer) {
  2006. /* move remaining encrypted data forward to the beginning of
  2007. buffer */
  2008. memmove(backend->encdata_buffer,
  2009. (backend->encdata_buffer + backend->encdata_offset) -
  2010. inbuf[3].cbBuffer, inbuf[3].cbBuffer);
  2011. backend->encdata_offset = inbuf[3].cbBuffer;
  2012. }
  2013. DEBUGF(infof(data,
  2014. "schannel: encrypted cached: offset %zu length %zu",
  2015. backend->encdata_offset, backend->encdata_length));
  2016. }
  2017. else {
  2018. /* reset encrypted buffer offset, because there is no data remaining */
  2019. backend->encdata_offset = 0;
  2020. }
  2021. /* check if server wants to renegotiate the connection context */
  2022. if(sspi_status == SEC_I_RENEGOTIATE) {
  2023. infof(data, "schannel: remote party requests renegotiation");
  2024. if(*err && *err != CURLE_AGAIN) {
  2025. infof(data, "schannel: can't renegotiate, an error is pending");
  2026. goto cleanup;
  2027. }
  2028. /* begin renegotiation */
  2029. infof(data, "schannel: renegotiating SSL/TLS connection");
  2030. connssl->state = ssl_connection_negotiating;
  2031. connssl->connecting_state = ssl_connect_2_writing;
  2032. backend->recv_renegotiating = true;
  2033. *err = schannel_connect_common(cf, data, FALSE, &done);
  2034. backend->recv_renegotiating = false;
  2035. if(*err) {
  2036. infof(data, "schannel: renegotiation failed");
  2037. goto cleanup;
  2038. }
  2039. /* now retry receiving data */
  2040. sspi_status = SEC_E_OK;
  2041. infof(data, "schannel: SSL/TLS connection renegotiated");
  2042. continue;
  2043. }
  2044. /* check if the server closed the connection */
  2045. else if(sspi_status == SEC_I_CONTEXT_EXPIRED) {
  2046. /* In Windows 2000 SEC_I_CONTEXT_EXPIRED (close_notify) is not
  2047. returned so we have to work around that in cleanup. */
  2048. backend->recv_sspi_close_notify = true;
  2049. if(!backend->recv_connection_closed) {
  2050. backend->recv_connection_closed = true;
  2051. infof(data, "schannel: server closed the connection");
  2052. }
  2053. goto cleanup;
  2054. }
  2055. }
  2056. else if(sspi_status == SEC_E_INCOMPLETE_MESSAGE) {
  2057. backend->encdata_is_incomplete = true;
  2058. if(!*err)
  2059. *err = CURLE_AGAIN;
  2060. infof(data, "schannel: failed to decrypt data, need more data");
  2061. goto cleanup;
  2062. }
  2063. else {
  2064. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  2065. char buffer[STRERROR_LEN];
  2066. infof(data, "schannel: failed to read data from server: %s",
  2067. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  2068. #endif
  2069. *err = CURLE_RECV_ERROR;
  2070. goto cleanup;
  2071. }
  2072. }
  2073. DEBUGF(infof(data,
  2074. "schannel: encrypted data buffer: offset %zu length %zu",
  2075. backend->encdata_offset, backend->encdata_length));
  2076. DEBUGF(infof(data,
  2077. "schannel: decrypted data buffer: offset %zu length %zu",
  2078. backend->decdata_offset, backend->decdata_length));
  2079. cleanup:
  2080. /* Warning- there is no guarantee the encdata state is valid at this point */
  2081. DEBUGF(infof(data, "schannel: schannel_recv cleanup"));
  2082. /* Error if the connection has closed without a close_notify.
  2083. The behavior here is a matter of debate. We don't want to be vulnerable
  2084. to a truncation attack however there's some browser precedent for
  2085. ignoring the close_notify for compatibility reasons.
  2086. Additionally, Windows 2000 (v5.0) is a special case since it seems it
  2087. doesn't return close_notify. In that case if the connection was closed we
  2088. assume it was graceful (close_notify) since there doesn't seem to be a
  2089. way to tell.
  2090. */
  2091. if(len && !backend->decdata_offset && backend->recv_connection_closed &&
  2092. !backend->recv_sspi_close_notify) {
  2093. bool isWin2k = curlx_verify_windows_version(5, 0, 0, PLATFORM_WINNT,
  2094. VERSION_EQUAL);
  2095. if(isWin2k && sspi_status == SEC_E_OK)
  2096. backend->recv_sspi_close_notify = true;
  2097. else {
  2098. *err = CURLE_RECV_ERROR;
  2099. infof(data, "schannel: server closed abruptly (missing close_notify)");
  2100. }
  2101. }
  2102. /* Any error other than CURLE_AGAIN is an unrecoverable error. */
  2103. if(*err && *err != CURLE_AGAIN)
  2104. backend->recv_unrecoverable_err = *err;
  2105. size = len < backend->decdata_offset ? len : backend->decdata_offset;
  2106. if(size) {
  2107. memcpy(buf, backend->decdata_buffer, size);
  2108. memmove(backend->decdata_buffer, backend->decdata_buffer + size,
  2109. backend->decdata_offset - size);
  2110. backend->decdata_offset -= size;
  2111. DEBUGF(infof(data, "schannel: decrypted data returned %zu", size));
  2112. DEBUGF(infof(data,
  2113. "schannel: decrypted data buffer: offset %zu length %zu",
  2114. backend->decdata_offset, backend->decdata_length));
  2115. *err = CURLE_OK;
  2116. return (ssize_t)size;
  2117. }
  2118. if(!*err && !backend->recv_connection_closed)
  2119. *err = CURLE_AGAIN;
  2120. /* It's debatable what to return when !len. We could return whatever error
  2121. we got from decryption but instead we override here so the return is
  2122. consistent.
  2123. */
  2124. if(!len)
  2125. *err = CURLE_OK;
  2126. return *err ? -1 : 0;
  2127. }
  2128. static CURLcode schannel_connect_nonblocking(struct Curl_cfilter *cf,
  2129. struct Curl_easy *data,
  2130. bool *done)
  2131. {
  2132. return schannel_connect_common(cf, data, TRUE, done);
  2133. }
  2134. static CURLcode schannel_connect(struct Curl_cfilter *cf,
  2135. struct Curl_easy *data)
  2136. {
  2137. CURLcode result;
  2138. bool done = FALSE;
  2139. result = schannel_connect_common(cf, data, FALSE, &done);
  2140. if(result)
  2141. return result;
  2142. DEBUGASSERT(done);
  2143. return CURLE_OK;
  2144. }
  2145. static bool schannel_data_pending(struct Curl_cfilter *cf,
  2146. const struct Curl_easy *data)
  2147. {
  2148. const struct ssl_connect_data *connssl = cf->ctx;
  2149. struct schannel_ssl_backend_data *backend =
  2150. (struct schannel_ssl_backend_data *)connssl->backend;
  2151. (void)data;
  2152. DEBUGASSERT(backend);
  2153. if(backend->ctxt) /* SSL/TLS is in use */
  2154. return (backend->decdata_offset > 0 ||
  2155. (backend->encdata_offset > 0 && !backend->encdata_is_incomplete));
  2156. else
  2157. return FALSE;
  2158. }
  2159. static void schannel_session_free(void *ptr)
  2160. {
  2161. /* this is expected to be called under sessionid lock */
  2162. struct Curl_schannel_cred *cred = ptr;
  2163. if(cred) {
  2164. cred->refcount--;
  2165. if(cred->refcount == 0) {
  2166. s_pSecFn->FreeCredentialsHandle(&cred->cred_handle);
  2167. curlx_unicodefree(cred->sni_hostname);
  2168. #ifdef HAS_CLIENT_CERT_PATH
  2169. if(cred->client_cert_store) {
  2170. CertCloseStore(cred->client_cert_store, 0);
  2171. cred->client_cert_store = NULL;
  2172. }
  2173. #endif
  2174. Curl_safefree(cred);
  2175. }
  2176. }
  2177. }
  2178. /* shut down the SSL connection and clean up related memory.
  2179. this function can be called multiple times on the same connection including
  2180. if the SSL connection failed (eg connection made but failed handshake). */
  2181. static int schannel_shutdown(struct Curl_cfilter *cf,
  2182. struct Curl_easy *data)
  2183. {
  2184. /* See https://msdn.microsoft.com/en-us/library/windows/desktop/aa380138.aspx
  2185. * Shutting Down an Schannel Connection
  2186. */
  2187. struct ssl_connect_data *connssl = cf->ctx;
  2188. struct schannel_ssl_backend_data *backend =
  2189. (struct schannel_ssl_backend_data *)connssl->backend;
  2190. DEBUGASSERT(data);
  2191. DEBUGASSERT(backend);
  2192. if(backend->ctxt) {
  2193. infof(data, "schannel: shutting down SSL/TLS connection with %s port %d",
  2194. connssl->peer.hostname, connssl->port);
  2195. }
  2196. if(backend->cred && backend->ctxt) {
  2197. SecBufferDesc BuffDesc;
  2198. SecBuffer Buffer;
  2199. SECURITY_STATUS sspi_status;
  2200. SecBuffer outbuf;
  2201. SecBufferDesc outbuf_desc;
  2202. CURLcode result;
  2203. DWORD dwshut = SCHANNEL_SHUTDOWN;
  2204. InitSecBuffer(&Buffer, SECBUFFER_TOKEN, &dwshut, sizeof(dwshut));
  2205. InitSecBufferDesc(&BuffDesc, &Buffer, 1);
  2206. sspi_status = s_pSecFn->ApplyControlToken(&backend->ctxt->ctxt_handle,
  2207. &BuffDesc);
  2208. if(sspi_status != SEC_E_OK) {
  2209. char buffer[STRERROR_LEN];
  2210. failf(data, "schannel: ApplyControlToken failure: %s",
  2211. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  2212. }
  2213. /* setup output buffer */
  2214. InitSecBuffer(&outbuf, SECBUFFER_EMPTY, NULL, 0);
  2215. InitSecBufferDesc(&outbuf_desc, &outbuf, 1);
  2216. sspi_status = s_pSecFn->InitializeSecurityContext(
  2217. &backend->cred->cred_handle,
  2218. &backend->ctxt->ctxt_handle,
  2219. backend->cred->sni_hostname,
  2220. backend->req_flags,
  2221. 0,
  2222. 0,
  2223. NULL,
  2224. 0,
  2225. &backend->ctxt->ctxt_handle,
  2226. &outbuf_desc,
  2227. &backend->ret_flags,
  2228. &backend->ctxt->time_stamp);
  2229. if((sspi_status == SEC_E_OK) || (sspi_status == SEC_I_CONTEXT_EXPIRED)) {
  2230. /* send close message which is in output buffer */
  2231. ssize_t written = Curl_conn_cf_send(cf->next, data,
  2232. outbuf.pvBuffer, outbuf.cbBuffer,
  2233. &result);
  2234. s_pSecFn->FreeContextBuffer(outbuf.pvBuffer);
  2235. if((result != CURLE_OK) || (outbuf.cbBuffer != (size_t) written)) {
  2236. infof(data, "schannel: failed to send close msg: %s"
  2237. " (bytes written: %zd)", curl_easy_strerror(result), written);
  2238. }
  2239. }
  2240. }
  2241. /* free SSPI Schannel API security context handle */
  2242. if(backend->ctxt) {
  2243. DEBUGF(infof(data, "schannel: clear security context handle"));
  2244. s_pSecFn->DeleteSecurityContext(&backend->ctxt->ctxt_handle);
  2245. Curl_safefree(backend->ctxt);
  2246. }
  2247. /* free SSPI Schannel API credential handle */
  2248. if(backend->cred) {
  2249. Curl_ssl_sessionid_lock(data);
  2250. schannel_session_free(backend->cred);
  2251. Curl_ssl_sessionid_unlock(data);
  2252. backend->cred = NULL;
  2253. }
  2254. /* free internal buffer for received encrypted data */
  2255. if(backend->encdata_buffer) {
  2256. Curl_safefree(backend->encdata_buffer);
  2257. backend->encdata_length = 0;
  2258. backend->encdata_offset = 0;
  2259. backend->encdata_is_incomplete = false;
  2260. }
  2261. /* free internal buffer for received decrypted data */
  2262. if(backend->decdata_buffer) {
  2263. Curl_safefree(backend->decdata_buffer);
  2264. backend->decdata_length = 0;
  2265. backend->decdata_offset = 0;
  2266. }
  2267. return CURLE_OK;
  2268. }
  2269. static void schannel_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  2270. {
  2271. schannel_shutdown(cf, data);
  2272. }
  2273. static int schannel_init(void)
  2274. {
  2275. return (Curl_sspi_global_init() == CURLE_OK ? 1 : 0);
  2276. }
  2277. static void schannel_cleanup(void)
  2278. {
  2279. Curl_sspi_global_cleanup();
  2280. }
  2281. static size_t schannel_version(char *buffer, size_t size)
  2282. {
  2283. size = msnprintf(buffer, size, "Schannel");
  2284. return size;
  2285. }
  2286. static CURLcode schannel_random(struct Curl_easy *data UNUSED_PARAM,
  2287. unsigned char *entropy, size_t length)
  2288. {
  2289. (void)data;
  2290. return Curl_win32_random(entropy, length);
  2291. }
  2292. static CURLcode schannel_pkp_pin_peer_pubkey(struct Curl_cfilter *cf,
  2293. struct Curl_easy *data,
  2294. const char *pinnedpubkey)
  2295. {
  2296. struct ssl_connect_data *connssl = cf->ctx;
  2297. struct schannel_ssl_backend_data *backend =
  2298. (struct schannel_ssl_backend_data *)connssl->backend;
  2299. CERT_CONTEXT *pCertContextServer = NULL;
  2300. /* Result is returned to caller */
  2301. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  2302. DEBUGASSERT(backend);
  2303. /* if a path wasn't specified, don't pin */
  2304. if(!pinnedpubkey)
  2305. return CURLE_OK;
  2306. do {
  2307. SECURITY_STATUS sspi_status;
  2308. const char *x509_der;
  2309. DWORD x509_der_len;
  2310. struct Curl_X509certificate x509_parsed;
  2311. struct Curl_asn1Element *pubkey;
  2312. sspi_status =
  2313. s_pSecFn->QueryContextAttributes(&backend->ctxt->ctxt_handle,
  2314. SECPKG_ATTR_REMOTE_CERT_CONTEXT,
  2315. &pCertContextServer);
  2316. if((sspi_status != SEC_E_OK) || !pCertContextServer) {
  2317. char buffer[STRERROR_LEN];
  2318. failf(data, "schannel: Failed to read remote certificate context: %s",
  2319. Curl_sspi_strerror(sspi_status, buffer, sizeof(buffer)));
  2320. break; /* failed */
  2321. }
  2322. if(!(((pCertContextServer->dwCertEncodingType & X509_ASN_ENCODING) != 0) &&
  2323. (pCertContextServer->cbCertEncoded > 0)))
  2324. break;
  2325. x509_der = (const char *)pCertContextServer->pbCertEncoded;
  2326. x509_der_len = pCertContextServer->cbCertEncoded;
  2327. memset(&x509_parsed, 0, sizeof(x509_parsed));
  2328. if(Curl_parseX509(&x509_parsed, x509_der, x509_der + x509_der_len))
  2329. break;
  2330. pubkey = &x509_parsed.subjectPublicKeyInfo;
  2331. if(!pubkey->header || pubkey->end <= pubkey->header) {
  2332. failf(data, "SSL: failed retrieving public key from server certificate");
  2333. break;
  2334. }
  2335. result = Curl_pin_peer_pubkey(data,
  2336. pinnedpubkey,
  2337. (const unsigned char *)pubkey->header,
  2338. (size_t)(pubkey->end - pubkey->header));
  2339. if(result) {
  2340. failf(data, "SSL: public key does not match pinned public key");
  2341. }
  2342. } while(0);
  2343. if(pCertContextServer)
  2344. CertFreeCertificateContext(pCertContextServer);
  2345. return result;
  2346. }
  2347. static void schannel_checksum(const unsigned char *input,
  2348. size_t inputlen,
  2349. unsigned char *checksum,
  2350. size_t checksumlen,
  2351. DWORD provType,
  2352. const unsigned int algId)
  2353. {
  2354. HCRYPTPROV hProv = 0;
  2355. HCRYPTHASH hHash = 0;
  2356. DWORD cbHashSize = 0;
  2357. DWORD dwHashSizeLen = (DWORD)sizeof(cbHashSize);
  2358. DWORD dwChecksumLen = (DWORD)checksumlen;
  2359. /* since this can fail in multiple ways, zero memory first so we never
  2360. * return old data
  2361. */
  2362. memset(checksum, 0, checksumlen);
  2363. if(!CryptAcquireContext(&hProv, NULL, NULL, provType,
  2364. CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
  2365. return; /* failed */
  2366. do {
  2367. if(!CryptCreateHash(hProv, algId, 0, 0, &hHash))
  2368. break; /* failed */
  2369. if(!CryptHashData(hHash, input, (DWORD)inputlen, 0))
  2370. break; /* failed */
  2371. /* get hash size */
  2372. if(!CryptGetHashParam(hHash, HP_HASHSIZE, (BYTE *)&cbHashSize,
  2373. &dwHashSizeLen, 0))
  2374. break; /* failed */
  2375. /* check hash size */
  2376. if(checksumlen < cbHashSize)
  2377. break; /* failed */
  2378. if(CryptGetHashParam(hHash, HP_HASHVAL, checksum, &dwChecksumLen, 0))
  2379. break; /* failed */
  2380. } while(0);
  2381. if(hHash)
  2382. CryptDestroyHash(hHash);
  2383. if(hProv)
  2384. CryptReleaseContext(hProv, 0);
  2385. }
  2386. static CURLcode schannel_sha256sum(const unsigned char *input,
  2387. size_t inputlen,
  2388. unsigned char *sha256sum,
  2389. size_t sha256len)
  2390. {
  2391. schannel_checksum(input, inputlen, sha256sum, sha256len,
  2392. PROV_RSA_AES, CALG_SHA_256);
  2393. return CURLE_OK;
  2394. }
  2395. static void *schannel_get_internals(struct ssl_connect_data *connssl,
  2396. CURLINFO info UNUSED_PARAM)
  2397. {
  2398. struct schannel_ssl_backend_data *backend =
  2399. (struct schannel_ssl_backend_data *)connssl->backend;
  2400. (void)info;
  2401. DEBUGASSERT(backend);
  2402. return &backend->ctxt->ctxt_handle;
  2403. }
  2404. HCERTSTORE Curl_schannel_get_cached_cert_store(struct Curl_cfilter *cf,
  2405. const struct Curl_easy *data)
  2406. {
  2407. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2408. struct Curl_multi *multi = data->multi_easy ? data->multi_easy : data->multi;
  2409. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  2410. struct schannel_multi_ssl_backend_data *mbackend;
  2411. const struct ssl_general_config *cfg = &data->set.general_ssl;
  2412. timediff_t timeout_ms;
  2413. timediff_t elapsed_ms;
  2414. struct curltime now;
  2415. unsigned char info_blob_digest[CURL_SHA256_DIGEST_LENGTH];
  2416. DEBUGASSERT(multi);
  2417. if(!multi || !multi->ssl_backend_data) {
  2418. return NULL;
  2419. }
  2420. mbackend = (struct schannel_multi_ssl_backend_data *)multi->ssl_backend_data;
  2421. if(!mbackend->cert_store) {
  2422. return NULL;
  2423. }
  2424. /* zero ca_cache_timeout completely disables caching */
  2425. if(!cfg->ca_cache_timeout) {
  2426. return NULL;
  2427. }
  2428. /* check for cache timeout by using the cached_x509_store_expired timediff
  2429. calculation pattern from openssl.c.
  2430. negative timeout means retain forever. */
  2431. timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
  2432. if(timeout_ms >= 0) {
  2433. now = Curl_now();
  2434. elapsed_ms = Curl_timediff(now, mbackend->time);
  2435. if(elapsed_ms >= timeout_ms) {
  2436. return NULL;
  2437. }
  2438. }
  2439. if(ca_info_blob) {
  2440. if(!mbackend->CAinfo_blob_digest) {
  2441. return NULL;
  2442. }
  2443. if(mbackend->CAinfo_blob_size != ca_info_blob->len) {
  2444. return NULL;
  2445. }
  2446. schannel_sha256sum((const unsigned char *)ca_info_blob->data,
  2447. ca_info_blob->len,
  2448. info_blob_digest,
  2449. CURL_SHA256_DIGEST_LENGTH);
  2450. if(memcmp(mbackend->CAinfo_blob_digest,
  2451. info_blob_digest,
  2452. CURL_SHA256_DIGEST_LENGTH)) {
  2453. return NULL;
  2454. }
  2455. }
  2456. else {
  2457. if(!conn_config->CAfile || !mbackend->CAfile ||
  2458. strcmp(mbackend->CAfile, conn_config->CAfile)) {
  2459. return NULL;
  2460. }
  2461. }
  2462. return mbackend->cert_store;
  2463. }
  2464. bool Curl_schannel_set_cached_cert_store(struct Curl_cfilter *cf,
  2465. const struct Curl_easy *data,
  2466. HCERTSTORE cert_store)
  2467. {
  2468. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2469. struct Curl_multi *multi = data->multi_easy ? data->multi_easy : data->multi;
  2470. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  2471. struct schannel_multi_ssl_backend_data *mbackend;
  2472. unsigned char *CAinfo_blob_digest = NULL;
  2473. size_t CAinfo_blob_size = 0;
  2474. char *CAfile = NULL;
  2475. DEBUGASSERT(multi);
  2476. if(!multi) {
  2477. return false;
  2478. }
  2479. if(!multi->ssl_backend_data) {
  2480. multi->ssl_backend_data =
  2481. calloc(1, sizeof(struct schannel_multi_ssl_backend_data));
  2482. if(!multi->ssl_backend_data) {
  2483. return false;
  2484. }
  2485. }
  2486. mbackend = (struct schannel_multi_ssl_backend_data *)multi->ssl_backend_data;
  2487. if(ca_info_blob) {
  2488. CAinfo_blob_digest = malloc(CURL_SHA256_DIGEST_LENGTH);
  2489. if(!CAinfo_blob_digest) {
  2490. return false;
  2491. }
  2492. schannel_sha256sum((const unsigned char *)ca_info_blob->data,
  2493. ca_info_blob->len,
  2494. CAinfo_blob_digest,
  2495. CURL_SHA256_DIGEST_LENGTH);
  2496. CAinfo_blob_size = ca_info_blob->len;
  2497. }
  2498. else {
  2499. if(conn_config->CAfile) {
  2500. CAfile = strdup(conn_config->CAfile);
  2501. if(!CAfile) {
  2502. return false;
  2503. }
  2504. }
  2505. }
  2506. /* free old cache data */
  2507. if(mbackend->cert_store) {
  2508. CertCloseStore(mbackend->cert_store, 0);
  2509. }
  2510. free(mbackend->CAinfo_blob_digest);
  2511. free(mbackend->CAfile);
  2512. mbackend->time = Curl_now();
  2513. mbackend->cert_store = cert_store;
  2514. mbackend->CAinfo_blob_digest = CAinfo_blob_digest;
  2515. mbackend->CAinfo_blob_size = CAinfo_blob_size;
  2516. mbackend->CAfile = CAfile;
  2517. return true;
  2518. }
  2519. static void schannel_free_multi_ssl_backend_data(
  2520. struct multi_ssl_backend_data *msbd)
  2521. {
  2522. struct schannel_multi_ssl_backend_data *mbackend =
  2523. (struct schannel_multi_ssl_backend_data*)msbd;
  2524. if(mbackend->cert_store) {
  2525. CertCloseStore(mbackend->cert_store, 0);
  2526. }
  2527. free(mbackend->CAinfo_blob_digest);
  2528. free(mbackend->CAfile);
  2529. free(mbackend);
  2530. }
  2531. const struct Curl_ssl Curl_ssl_schannel = {
  2532. { CURLSSLBACKEND_SCHANNEL, "schannel" }, /* info */
  2533. SSLSUPP_CERTINFO |
  2534. #ifdef HAS_MANUAL_VERIFY_API
  2535. SSLSUPP_CAINFO_BLOB |
  2536. #endif
  2537. SSLSUPP_PINNEDPUBKEY |
  2538. SSLSUPP_TLS13_CIPHERSUITES |
  2539. SSLSUPP_HTTPS_PROXY,
  2540. sizeof(struct schannel_ssl_backend_data),
  2541. schannel_init, /* init */
  2542. schannel_cleanup, /* cleanup */
  2543. schannel_version, /* version */
  2544. Curl_none_check_cxn, /* check_cxn */
  2545. schannel_shutdown, /* shutdown */
  2546. schannel_data_pending, /* data_pending */
  2547. schannel_random, /* random */
  2548. Curl_none_cert_status_request, /* cert_status_request */
  2549. schannel_connect, /* connect */
  2550. schannel_connect_nonblocking, /* connect_nonblocking */
  2551. Curl_ssl_adjust_pollset, /* adjust_pollset */
  2552. schannel_get_internals, /* get_internals */
  2553. schannel_close, /* close_one */
  2554. Curl_none_close_all, /* close_all */
  2555. schannel_session_free, /* session_free */
  2556. Curl_none_set_engine, /* set_engine */
  2557. Curl_none_set_engine_default, /* set_engine_default */
  2558. Curl_none_engines_list, /* engines_list */
  2559. Curl_none_false_start, /* false_start */
  2560. schannel_sha256sum, /* sha256sum */
  2561. NULL, /* associate_connection */
  2562. NULL, /* disassociate_connection */
  2563. schannel_free_multi_ssl_backend_data, /* free_multi_ssl_backend_data */
  2564. schannel_recv, /* recv decrypted data */
  2565. schannel_send, /* send data to encrypt */
  2566. };
  2567. #endif /* USE_SCHANNEL */