schannel.c 99 KB

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