schannel.c 94 KB

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