schannel.c 99 KB

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