2
0

schannel.c 91 KB

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