schannel.c 81 KB

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