schannel.c 93 KB

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