schannel.c 82 KB

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