schannel.c 93 KB

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