openssl.c 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /*
  23. * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
  24. * but vtls.c should ever call or use these functions.
  25. */
  26. /*
  27. * The original SSLeay-using code for curl was written by Linas Vepstas and
  28. * Sampo Kellomaki 1998.
  29. */
  30. #include "curl_setup.h"
  31. #ifdef USE_OPENSSL
  32. #ifdef HAVE_LIMITS_H
  33. #include <limits.h>
  34. #endif
  35. #include "urldata.h"
  36. #include "sendf.h"
  37. #include "formdata.h" /* for the boundary function */
  38. #include "url.h" /* for the ssl config check function */
  39. #include "inet_pton.h"
  40. #include "openssl.h"
  41. #include "connect.h"
  42. #include "slist.h"
  43. #include "select.h"
  44. #include "vtls.h"
  45. #include "strcase.h"
  46. #include "hostcheck.h"
  47. #include "curl_printf.h"
  48. #include <openssl/ssl.h>
  49. #include <openssl/rand.h>
  50. #include <openssl/x509v3.h>
  51. #ifndef OPENSSL_NO_DSA
  52. #include <openssl/dsa.h>
  53. #endif
  54. #include <openssl/dh.h>
  55. #include <openssl/err.h>
  56. #include <openssl/md5.h>
  57. #include <openssl/conf.h>
  58. #include <openssl/bn.h>
  59. #include <openssl/rsa.h>
  60. #ifdef HAVE_OPENSSL_PKCS12_H
  61. #include <openssl/pkcs12.h>
  62. #endif
  63. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
  64. #include <openssl/ocsp.h>
  65. #endif
  66. #include "warnless.h"
  67. #include "non-ascii.h" /* for Curl_convert_from_utf8 prototype */
  68. /* The last #include files should be: */
  69. #include "curl_memory.h"
  70. #include "memdebug.h"
  71. #ifndef OPENSSL_VERSION_NUMBER
  72. #error "OPENSSL_VERSION_NUMBER not defined"
  73. #endif
  74. #if defined(HAVE_OPENSSL_ENGINE_H)
  75. #include <openssl/ui.h>
  76. #endif
  77. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  78. #define SSL_METHOD_QUAL const
  79. #else
  80. #define SSL_METHOD_QUAL
  81. #endif
  82. #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
  83. #define HAVE_ERR_REMOVE_THREAD_STATE 1
  84. #endif
  85. #if !defined(HAVE_SSLV2_CLIENT_METHOD) || \
  86. OPENSSL_VERSION_NUMBER >= 0x10100000L /* 1.1.0+ has no SSLv2 */
  87. #undef OPENSSL_NO_SSL2 /* undef first to avoid compiler warnings */
  88. #define OPENSSL_NO_SSL2
  89. #endif
  90. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
  91. !defined(LIBRESSL_VERSION_NUMBER)
  92. #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
  93. #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
  94. #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
  95. #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
  96. #define CONST_EXTS const
  97. #define CONST_ASN1_BIT_STRING const
  98. #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
  99. #else
  100. /* For OpenSSL before 1.1.0 */
  101. #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
  102. #define X509_get0_notBefore(x) X509_get_notBefore(x)
  103. #define X509_get0_notAfter(x) X509_get_notAfter(x)
  104. #define CONST_EXTS /* nope */
  105. #define CONST_ASN1_BIT_STRING /* nope */
  106. #ifdef LIBRESSL_VERSION_NUMBER
  107. static unsigned long OpenSSL_version_num(void)
  108. {
  109. return LIBRESSL_VERSION_NUMBER;
  110. }
  111. #else
  112. #define OpenSSL_version_num() SSLeay()
  113. #endif
  114. #endif
  115. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
  116. !defined(LIBRESSL_VERSION_NUMBER)
  117. #define HAVE_X509_GET0_SIGNATURE 1
  118. #endif
  119. #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
  120. OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
  121. !defined(OPENSSL_NO_COMP)
  122. #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
  123. #endif
  124. #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
  125. /* not present in older OpenSSL */
  126. #define OPENSSL_load_builtin_modules(x)
  127. #endif
  128. #if defined(LIBRESSL_VERSION_NUMBER)
  129. #define OSSL_PACKAGE "LibreSSL"
  130. #elif defined(OPENSSL_IS_BORINGSSL)
  131. #define OSSL_PACKAGE "BoringSSL"
  132. #else
  133. #define OSSL_PACKAGE "OpenSSL"
  134. #endif
  135. /*
  136. * Number of bytes to read from the random number seed file. This must be
  137. * a finite value (because some entropy "files" like /dev/urandom have
  138. * an infinite length), but must be large enough to provide enough
  139. * entropy to properly seed OpenSSL's PRNG.
  140. */
  141. #define RAND_LOAD_LENGTH 1024
  142. static const char *SSL_ERROR_to_str(int err)
  143. {
  144. switch(err) {
  145. case SSL_ERROR_NONE:
  146. return "SSL_ERROR_NONE";
  147. case SSL_ERROR_SSL:
  148. return "SSL_ERROR_SSL";
  149. case SSL_ERROR_WANT_READ:
  150. return "SSL_ERROR_WANT_READ";
  151. case SSL_ERROR_WANT_WRITE:
  152. return "SSL_ERROR_WANT_WRITE";
  153. case SSL_ERROR_WANT_X509_LOOKUP:
  154. return "SSL_ERROR_WANT_X509_LOOKUP";
  155. case SSL_ERROR_SYSCALL:
  156. return "SSL_ERROR_SYSCALL";
  157. case SSL_ERROR_ZERO_RETURN:
  158. return "SSL_ERROR_ZERO_RETURN";
  159. case SSL_ERROR_WANT_CONNECT:
  160. return "SSL_ERROR_WANT_CONNECT";
  161. case SSL_ERROR_WANT_ACCEPT:
  162. return "SSL_ERROR_WANT_ACCEPT";
  163. #if defined(SSL_ERROR_WANT_ASYNC)
  164. case SSL_ERROR_WANT_ASYNC:
  165. return "SSL_ERROR_WANT_ASYNC";
  166. #endif
  167. #if defined(SSL_ERROR_WANT_ASYNC_JOB)
  168. case SSL_ERROR_WANT_ASYNC_JOB:
  169. return "SSL_ERROR_WANT_ASYNC_JOB";
  170. #endif
  171. #if defined(SSL_ERROR_WANT_EARLY)
  172. case SSL_ERROR_WANT_EARLY:
  173. return "SSL_ERROR_WANT_EARLY";
  174. #endif
  175. default:
  176. return "SSL_ERROR unknown";
  177. }
  178. }
  179. /* Return error string for last OpenSSL error
  180. */
  181. static char *ossl_strerror(unsigned long error, char *buf, size_t size)
  182. {
  183. ERR_error_string_n(error, buf, size);
  184. return buf;
  185. }
  186. static int passwd_callback(char *buf, int num, int encrypting,
  187. void *global_passwd)
  188. {
  189. DEBUGASSERT(0 == encrypting);
  190. if(!encrypting) {
  191. int klen = curlx_uztosi(strlen((char *)global_passwd));
  192. if(num > klen) {
  193. memcpy(buf, global_passwd, klen+1);
  194. return klen;
  195. }
  196. }
  197. return 0;
  198. }
  199. /*
  200. * rand_enough() returns TRUE if we have seeded the random engine properly.
  201. */
  202. static bool rand_enough(void)
  203. {
  204. return (0 != RAND_status()) ? TRUE : FALSE;
  205. }
  206. static CURLcode Curl_ossl_seed(struct Curl_easy *data)
  207. {
  208. /* we have the "SSL is seeded" boolean static to prevent multiple
  209. time-consuming seedings in vain */
  210. static bool ssl_seeded = FALSE;
  211. char *buf = data->state.buffer; /* point to the big buffer */
  212. int nread=0;
  213. if(ssl_seeded)
  214. return CURLE_OK;
  215. if(rand_enough()) {
  216. /* OpenSSL 1.1.0+ will return here */
  217. ssl_seeded = TRUE;
  218. return CURLE_OK;
  219. }
  220. #ifndef RANDOM_FILE
  221. /* if RANDOM_FILE isn't defined, we only perform this if an option tells
  222. us to! */
  223. if(data->set.str[STRING_SSL_RANDOM_FILE])
  224. #define RANDOM_FILE "" /* doesn't matter won't be used */
  225. #endif
  226. {
  227. /* let the option override the define */
  228. nread += RAND_load_file((data->set.str[STRING_SSL_RANDOM_FILE]?
  229. data->set.str[STRING_SSL_RANDOM_FILE]:
  230. RANDOM_FILE),
  231. RAND_LOAD_LENGTH);
  232. if(rand_enough())
  233. return nread;
  234. }
  235. #if defined(HAVE_RAND_EGD)
  236. /* only available in OpenSSL 0.9.5 and later */
  237. /* EGD_SOCKET is set at configure time or not at all */
  238. #ifndef EGD_SOCKET
  239. /* If we don't have the define set, we only do this if the egd-option
  240. is set */
  241. if(data->set.str[STRING_SSL_EGDSOCKET])
  242. #define EGD_SOCKET "" /* doesn't matter won't be used */
  243. #endif
  244. {
  245. /* If there's an option and a define, the option overrides the
  246. define */
  247. int ret = RAND_egd(data->set.str[STRING_SSL_EGDSOCKET]?
  248. data->set.str[STRING_SSL_EGDSOCKET]:EGD_SOCKET);
  249. if(-1 != ret) {
  250. nread += ret;
  251. if(rand_enough())
  252. return nread;
  253. }
  254. }
  255. #endif
  256. /* If we get here, it means we need to seed the PRNG using a "silly"
  257. approach! */
  258. do {
  259. unsigned char randb[64];
  260. int len = sizeof(randb);
  261. if(!RAND_bytes(randb, len))
  262. break;
  263. RAND_add(randb, len, (len >> 1));
  264. } while(!rand_enough());
  265. /* generates a default path for the random seed file */
  266. buf[0]=0; /* blank it first */
  267. RAND_file_name(buf, BUFSIZE);
  268. if(buf[0]) {
  269. /* we got a file name to try */
  270. nread += RAND_load_file(buf, RAND_LOAD_LENGTH);
  271. if(rand_enough())
  272. return nread;
  273. }
  274. infof(data, "libcurl is now using a weak random seed!\n");
  275. return CURLE_SSL_CONNECT_ERROR; /* confusing error code */
  276. }
  277. #ifndef SSL_FILETYPE_ENGINE
  278. #define SSL_FILETYPE_ENGINE 42
  279. #endif
  280. #ifndef SSL_FILETYPE_PKCS12
  281. #define SSL_FILETYPE_PKCS12 43
  282. #endif
  283. static int do_file_type(const char *type)
  284. {
  285. if(!type || !type[0])
  286. return SSL_FILETYPE_PEM;
  287. if(strcasecompare(type, "PEM"))
  288. return SSL_FILETYPE_PEM;
  289. if(strcasecompare(type, "DER"))
  290. return SSL_FILETYPE_ASN1;
  291. if(strcasecompare(type, "ENG"))
  292. return SSL_FILETYPE_ENGINE;
  293. if(strcasecompare(type, "P12"))
  294. return SSL_FILETYPE_PKCS12;
  295. return -1;
  296. }
  297. #if defined(HAVE_OPENSSL_ENGINE_H)
  298. /*
  299. * Supply default password to the engine user interface conversation.
  300. * The password is passed by OpenSSL engine from ENGINE_load_private_key()
  301. * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
  302. */
  303. static int ssl_ui_reader(UI *ui, UI_STRING *uis)
  304. {
  305. const char *password;
  306. switch(UI_get_string_type(uis)) {
  307. case UIT_PROMPT:
  308. case UIT_VERIFY:
  309. password = (const char *)UI_get0_user_data(ui);
  310. if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  311. UI_set_result(ui, uis, password);
  312. return 1;
  313. }
  314. default:
  315. break;
  316. }
  317. return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
  318. }
  319. /*
  320. * Suppress interactive request for a default password if available.
  321. */
  322. static int ssl_ui_writer(UI *ui, UI_STRING *uis)
  323. {
  324. switch(UI_get_string_type(uis)) {
  325. case UIT_PROMPT:
  326. case UIT_VERIFY:
  327. if(UI_get0_user_data(ui) &&
  328. (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  329. return 1;
  330. }
  331. default:
  332. break;
  333. }
  334. return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
  335. }
  336. #endif
  337. static
  338. int cert_stuff(struct connectdata *conn,
  339. SSL_CTX* ctx,
  340. char *cert_file,
  341. const char *cert_type,
  342. char *key_file,
  343. const char *key_type,
  344. char *key_passwd)
  345. {
  346. struct Curl_easy *data = conn->data;
  347. char error_buffer[256];
  348. int file_type = do_file_type(cert_type);
  349. if(cert_file || (file_type == SSL_FILETYPE_ENGINE)) {
  350. SSL *ssl;
  351. X509 *x509;
  352. int cert_done = 0;
  353. if(key_passwd) {
  354. /* set the password in the callback userdata */
  355. SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
  356. /* Set passwd callback: */
  357. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  358. }
  359. switch(file_type) {
  360. case SSL_FILETYPE_PEM:
  361. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  362. if(SSL_CTX_use_certificate_chain_file(ctx,
  363. cert_file) != 1) {
  364. failf(data,
  365. "could not load PEM client certificate, " OSSL_PACKAGE
  366. " error %s, "
  367. "(no key found, wrong pass phrase, or wrong file format?)",
  368. ossl_strerror(ERR_get_error(), error_buffer,
  369. sizeof(error_buffer)) );
  370. return 0;
  371. }
  372. break;
  373. case SSL_FILETYPE_ASN1:
  374. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  375. we use the case above for PEM so this can only be performed with
  376. ASN1 files. */
  377. if(SSL_CTX_use_certificate_file(ctx,
  378. cert_file,
  379. file_type) != 1) {
  380. failf(data,
  381. "could not load ASN1 client certificate, " OSSL_PACKAGE
  382. " error %s, "
  383. "(no key found, wrong pass phrase, or wrong file format?)",
  384. ossl_strerror(ERR_get_error(), error_buffer,
  385. sizeof(error_buffer)) );
  386. return 0;
  387. }
  388. break;
  389. case SSL_FILETYPE_ENGINE:
  390. #if defined(HAVE_OPENSSL_ENGINE_H) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
  391. {
  392. if(data->state.engine) {
  393. const char *cmd_name = "LOAD_CERT_CTRL";
  394. struct {
  395. const char *cert_id;
  396. X509 *cert;
  397. } params;
  398. params.cert_id = cert_file;
  399. params.cert = NULL;
  400. /* Does the engine supports LOAD_CERT_CTRL ? */
  401. if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
  402. 0, (void *)cmd_name, NULL)) {
  403. failf(data, "ssl engine does not support loading certificates");
  404. return 0;
  405. }
  406. /* Load the certificate from the engine */
  407. if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
  408. 0, &params, NULL, 1)) {
  409. failf(data, "ssl engine cannot load client cert with id"
  410. " '%s' [%s]", cert_file,
  411. ossl_strerror(ERR_get_error(), error_buffer,
  412. sizeof(error_buffer)));
  413. return 0;
  414. }
  415. if(!params.cert) {
  416. failf(data, "ssl engine didn't initialized the certificate "
  417. "properly.");
  418. return 0;
  419. }
  420. if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
  421. failf(data, "unable to set client certificate");
  422. X509_free(params.cert);
  423. return 0;
  424. }
  425. X509_free(params.cert); /* we don't need the handle any more... */
  426. }
  427. else {
  428. failf(data, "crypto engine not set, can't load certificate");
  429. return 0;
  430. }
  431. }
  432. break;
  433. #else
  434. failf(data, "file type ENG for certificate not implemented");
  435. return 0;
  436. #endif
  437. case SSL_FILETYPE_PKCS12:
  438. {
  439. #ifdef HAVE_OPENSSL_PKCS12_H
  440. FILE *f;
  441. PKCS12 *p12;
  442. EVP_PKEY *pri;
  443. STACK_OF(X509) *ca = NULL;
  444. f = fopen(cert_file, "rb");
  445. if(!f) {
  446. failf(data, "could not open PKCS12 file '%s'", cert_file);
  447. return 0;
  448. }
  449. p12 = d2i_PKCS12_fp(f, NULL);
  450. fclose(f);
  451. if(!p12) {
  452. failf(data, "error reading PKCS12 file '%s'", cert_file);
  453. return 0;
  454. }
  455. PKCS12_PBE_add();
  456. if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
  457. &ca)) {
  458. failf(data,
  459. "could not parse PKCS12 file, check password, " OSSL_PACKAGE
  460. " error %s",
  461. ossl_strerror(ERR_get_error(), error_buffer,
  462. sizeof(error_buffer)) );
  463. PKCS12_free(p12);
  464. return 0;
  465. }
  466. PKCS12_free(p12);
  467. if(SSL_CTX_use_certificate(ctx, x509) != 1) {
  468. failf(data,
  469. "could not load PKCS12 client certificate, " OSSL_PACKAGE
  470. " error %s",
  471. ossl_strerror(ERR_get_error(), error_buffer,
  472. sizeof(error_buffer)) );
  473. goto fail;
  474. }
  475. if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
  476. failf(data, "unable to use private key from PKCS12 file '%s'",
  477. cert_file);
  478. goto fail;
  479. }
  480. if(!SSL_CTX_check_private_key (ctx)) {
  481. failf(data, "private key from PKCS12 file '%s' "
  482. "does not match certificate in same file", cert_file);
  483. goto fail;
  484. }
  485. /* Set Certificate Verification chain */
  486. if(ca) {
  487. while(sk_X509_num(ca)) {
  488. /*
  489. * Note that sk_X509_pop() is used below to make sure the cert is
  490. * removed from the stack properly before getting passed to
  491. * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
  492. * we used sk_X509_value() instead, but then we'd clean it in the
  493. * subsequent sk_X509_pop_free() call.
  494. */
  495. X509 *x = sk_X509_pop(ca);
  496. if(!SSL_CTX_add_client_CA(ctx, x)) {
  497. X509_free(x);
  498. failf(data, "cannot add certificate to client CA list");
  499. goto fail;
  500. }
  501. if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
  502. X509_free(x);
  503. failf(data, "cannot add certificate to certificate chain");
  504. goto fail;
  505. }
  506. }
  507. }
  508. cert_done = 1;
  509. fail:
  510. EVP_PKEY_free(pri);
  511. X509_free(x509);
  512. sk_X509_pop_free(ca, X509_free);
  513. if(!cert_done)
  514. return 0; /* failure! */
  515. break;
  516. #else
  517. failf(data, "file type P12 for certificate not supported");
  518. return 0;
  519. #endif
  520. }
  521. default:
  522. failf(data, "not supported file type '%s' for certificate", cert_type);
  523. return 0;
  524. }
  525. file_type = do_file_type(key_type);
  526. switch(file_type) {
  527. case SSL_FILETYPE_PEM:
  528. if(cert_done)
  529. break;
  530. if(!key_file)
  531. /* cert & key can only be in PEM case in the same file */
  532. key_file=cert_file;
  533. /* FALLTHROUGH */
  534. case SSL_FILETYPE_ASN1:
  535. if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
  536. failf(data, "unable to set private key file: '%s' type %s",
  537. key_file, key_type?key_type:"PEM");
  538. return 0;
  539. }
  540. break;
  541. case SSL_FILETYPE_ENGINE:
  542. #ifdef HAVE_OPENSSL_ENGINE_H
  543. { /* XXXX still needs some work */
  544. EVP_PKEY *priv_key = NULL;
  545. if(data->state.engine) {
  546. UI_METHOD *ui_method =
  547. UI_create_method((char *)"curl user interface");
  548. if(!ui_method) {
  549. failf(data, "unable do create " OSSL_PACKAGE
  550. " user-interface method");
  551. return 0;
  552. }
  553. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  554. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  555. UI_method_set_reader(ui_method, ssl_ui_reader);
  556. UI_method_set_writer(ui_method, ssl_ui_writer);
  557. /* the typecast below was added to please mingw32 */
  558. priv_key = (EVP_PKEY *)
  559. ENGINE_load_private_key(data->state.engine, key_file,
  560. ui_method,
  561. key_passwd);
  562. UI_destroy_method(ui_method);
  563. if(!priv_key) {
  564. failf(data, "failed to load private key from crypto engine");
  565. return 0;
  566. }
  567. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  568. failf(data, "unable to set private key");
  569. EVP_PKEY_free(priv_key);
  570. return 0;
  571. }
  572. EVP_PKEY_free(priv_key); /* we don't need the handle any more... */
  573. }
  574. else {
  575. failf(data, "crypto engine not set, can't load private key");
  576. return 0;
  577. }
  578. }
  579. break;
  580. #else
  581. failf(data, "file type ENG for private key not supported");
  582. return 0;
  583. #endif
  584. case SSL_FILETYPE_PKCS12:
  585. if(!cert_done) {
  586. failf(data, "file type P12 for private key not supported");
  587. return 0;
  588. }
  589. break;
  590. default:
  591. failf(data, "not supported file type for private key");
  592. return 0;
  593. }
  594. ssl=SSL_new(ctx);
  595. if(!ssl) {
  596. failf(data, "unable to create an SSL structure");
  597. return 0;
  598. }
  599. x509=SSL_get_certificate(ssl);
  600. /* This version was provided by Evan Jordan and is supposed to not
  601. leak memory as the previous version: */
  602. if(x509) {
  603. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  604. EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
  605. EVP_PKEY_free(pktmp);
  606. }
  607. SSL_free(ssl);
  608. /* If we are using DSA, we can copy the parameters from
  609. * the private key */
  610. /* Now we know that a key and cert have been set against
  611. * the SSL context */
  612. if(!SSL_CTX_check_private_key(ctx)) {
  613. failf(data, "Private key does not match the certificate public key");
  614. return 0;
  615. }
  616. }
  617. return 1;
  618. }
  619. /* returns non-zero on failure */
  620. static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
  621. {
  622. #if 0
  623. return X509_NAME_oneline(a, buf, size);
  624. #else
  625. BIO *bio_out = BIO_new(BIO_s_mem());
  626. BUF_MEM *biomem;
  627. int rc;
  628. if(!bio_out)
  629. return 1; /* alloc failed! */
  630. rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
  631. BIO_get_mem_ptr(bio_out, &biomem);
  632. if((size_t)biomem->length < size)
  633. size = biomem->length;
  634. else
  635. size--; /* don't overwrite the buffer end */
  636. memcpy(buf, biomem->data, size);
  637. buf[size]=0;
  638. BIO_free(bio_out);
  639. return !rc;
  640. #endif
  641. }
  642. /**
  643. * Global SSL init
  644. *
  645. * @retval 0 error initializing SSL
  646. * @retval 1 SSL initialized successfully
  647. */
  648. int Curl_ossl_init(void)
  649. {
  650. OPENSSL_load_builtin_modules();
  651. #ifdef HAVE_ENGINE_LOAD_BUILTIN_ENGINES
  652. ENGINE_load_builtin_engines();
  653. #endif
  654. /* OPENSSL_config(NULL); is "strongly recommended" to use but unfortunately
  655. that function makes an exit() call on wrongly formatted config files
  656. which makes it hard to use in some situations. OPENSSL_config() itself
  657. calls CONF_modules_load_file() and we use that instead and we ignore
  658. its return code! */
  659. /* CONF_MFLAGS_DEFAULT_SECTION introduced some time between 0.9.8b and
  660. 0.9.8e */
  661. #ifndef CONF_MFLAGS_DEFAULT_SECTION
  662. #define CONF_MFLAGS_DEFAULT_SECTION 0x0
  663. #endif
  664. CONF_modules_load_file(NULL, NULL,
  665. CONF_MFLAGS_DEFAULT_SECTION|
  666. CONF_MFLAGS_IGNORE_MISSING_FILE);
  667. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  668. !defined(LIBRESSL_VERSION_NUMBER)
  669. /* OpenSSL 1.1.0+ takes care of initialization itself */
  670. #else
  671. /* Lets get nice error messages */
  672. SSL_load_error_strings();
  673. /* Init the global ciphers and digests */
  674. if(!SSLeay_add_ssl_algorithms())
  675. return 0;
  676. OpenSSL_add_all_algorithms();
  677. #endif
  678. return 1;
  679. }
  680. /* Global cleanup */
  681. void Curl_ossl_cleanup(void)
  682. {
  683. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  684. !defined(LIBRESSL_VERSION_NUMBER)
  685. /* OpenSSL 1.1 deprecates all these cleanup functions and
  686. turns them into no-ops in OpenSSL 1.0 compatibility mode */
  687. #else
  688. /* Free ciphers and digests lists */
  689. EVP_cleanup();
  690. #ifdef HAVE_ENGINE_CLEANUP
  691. /* Free engine list */
  692. ENGINE_cleanup();
  693. #endif
  694. /* Free OpenSSL error strings */
  695. ERR_free_strings();
  696. /* Free thread local error state, destroying hash upon zero refcount */
  697. #ifdef HAVE_ERR_REMOVE_THREAD_STATE
  698. ERR_remove_thread_state(NULL);
  699. #else
  700. ERR_remove_state(0);
  701. #endif
  702. /* Free all memory allocated by all configuration modules */
  703. CONF_modules_free();
  704. #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
  705. SSL_COMP_free_compression_methods();
  706. #endif
  707. #endif
  708. }
  709. /*
  710. * This function is used to determine connection status.
  711. *
  712. * Return codes:
  713. * 1 means the connection is still in place
  714. * 0 means the connection has been closed
  715. * -1 means the connection status is unknown
  716. */
  717. int Curl_ossl_check_cxn(struct connectdata *conn)
  718. {
  719. /* SSL_peek takes data out of the raw recv buffer without peeking so we use
  720. recv MSG_PEEK instead. Bug #795 */
  721. #ifdef MSG_PEEK
  722. char buf;
  723. ssize_t nread;
  724. nread = recv((RECV_TYPE_ARG1)conn->sock[FIRSTSOCKET], (RECV_TYPE_ARG2)&buf,
  725. (RECV_TYPE_ARG3)1, (RECV_TYPE_ARG4)MSG_PEEK);
  726. if(nread == 0)
  727. return 0; /* connection has been closed */
  728. if(nread == 1)
  729. return 1; /* connection still in place */
  730. else if(nread == -1) {
  731. int err = SOCKERRNO;
  732. if(err == EINPROGRESS ||
  733. #if defined(EAGAIN) && (EAGAIN != EWOULDBLOCK)
  734. err == EAGAIN ||
  735. #endif
  736. err == EWOULDBLOCK)
  737. return 1; /* connection still in place */
  738. if(err == ECONNRESET ||
  739. #ifdef ECONNABORTED
  740. err == ECONNABORTED ||
  741. #endif
  742. #ifdef ENETDOWN
  743. err == ENETDOWN ||
  744. #endif
  745. #ifdef ENETRESET
  746. err == ENETRESET ||
  747. #endif
  748. #ifdef ESHUTDOWN
  749. err == ESHUTDOWN ||
  750. #endif
  751. #ifdef ETIMEDOUT
  752. err == ETIMEDOUT ||
  753. #endif
  754. err == ENOTCONN)
  755. return 0; /* connection has been closed */
  756. }
  757. #endif
  758. return -1; /* connection status unknown */
  759. }
  760. /* Selects an OpenSSL crypto engine
  761. */
  762. CURLcode Curl_ossl_set_engine(struct Curl_easy *data, const char *engine)
  763. {
  764. #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
  765. ENGINE *e;
  766. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  767. e = ENGINE_by_id(engine);
  768. #else
  769. /* avoid memory leak */
  770. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  771. const char *e_id = ENGINE_get_id(e);
  772. if(!strcmp(engine, e_id))
  773. break;
  774. }
  775. #endif
  776. if(!e) {
  777. failf(data, "SSL Engine '%s' not found", engine);
  778. return CURLE_SSL_ENGINE_NOTFOUND;
  779. }
  780. if(data->state.engine) {
  781. ENGINE_finish(data->state.engine);
  782. ENGINE_free(data->state.engine);
  783. data->state.engine = NULL;
  784. }
  785. if(!ENGINE_init(e)) {
  786. char buf[256];
  787. ENGINE_free(e);
  788. failf(data, "Failed to initialise SSL Engine '%s':\n%s",
  789. engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
  790. return CURLE_SSL_ENGINE_INITFAILED;
  791. }
  792. data->state.engine = e;
  793. return CURLE_OK;
  794. #else
  795. (void)engine;
  796. failf(data, "SSL Engine not supported");
  797. return CURLE_SSL_ENGINE_NOTFOUND;
  798. #endif
  799. }
  800. /* Sets engine as default for all SSL operations
  801. */
  802. CURLcode Curl_ossl_set_engine_default(struct Curl_easy *data)
  803. {
  804. #ifdef HAVE_OPENSSL_ENGINE_H
  805. if(data->state.engine) {
  806. if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
  807. infof(data, "set default crypto engine '%s'\n",
  808. ENGINE_get_id(data->state.engine));
  809. }
  810. else {
  811. failf(data, "set default crypto engine '%s' failed",
  812. ENGINE_get_id(data->state.engine));
  813. return CURLE_SSL_ENGINE_SETFAILED;
  814. }
  815. }
  816. #else
  817. (void) data;
  818. #endif
  819. return CURLE_OK;
  820. }
  821. /* Return list of OpenSSL crypto engine names.
  822. */
  823. struct curl_slist *Curl_ossl_engines_list(struct Curl_easy *data)
  824. {
  825. struct curl_slist *list = NULL;
  826. #if defined(USE_OPENSSL) && defined(HAVE_OPENSSL_ENGINE_H)
  827. struct curl_slist *beg;
  828. ENGINE *e;
  829. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  830. beg = curl_slist_append(list, ENGINE_get_id(e));
  831. if(!beg) {
  832. curl_slist_free_all(list);
  833. return NULL;
  834. }
  835. list = beg;
  836. }
  837. #endif
  838. (void) data;
  839. return list;
  840. }
  841. static void ossl_close(struct ssl_connect_data *connssl)
  842. {
  843. if(connssl->handle) {
  844. (void)SSL_shutdown(connssl->handle);
  845. SSL_set_connect_state(connssl->handle);
  846. SSL_free(connssl->handle);
  847. connssl->handle = NULL;
  848. }
  849. if(connssl->ctx) {
  850. SSL_CTX_free(connssl->ctx);
  851. connssl->ctx = NULL;
  852. }
  853. }
  854. /*
  855. * This function is called when an SSL connection is closed.
  856. */
  857. void Curl_ossl_close(struct connectdata *conn, int sockindex)
  858. {
  859. ossl_close(&conn->ssl[sockindex]);
  860. ossl_close(&conn->proxy_ssl[sockindex]);
  861. }
  862. /*
  863. * This function is called to shut down the SSL layer but keep the
  864. * socket open (CCC - Clear Command Channel)
  865. */
  866. int Curl_ossl_shutdown(struct connectdata *conn, int sockindex)
  867. {
  868. int retval = 0;
  869. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  870. struct Curl_easy *data = conn->data;
  871. char buf[256]; /* We will use this for the OpenSSL error buffer, so it has
  872. to be at least 256 bytes long. */
  873. unsigned long sslerror;
  874. ssize_t nread;
  875. int buffsize;
  876. int err;
  877. int done = 0;
  878. /* This has only been tested on the proftpd server, and the mod_tls code
  879. sends a close notify alert without waiting for a close notify alert in
  880. response. Thus we wait for a close notify alert from the server, but
  881. we do not send one. Let's hope other servers do the same... */
  882. if(data->set.ftp_ccc == CURLFTPSSL_CCC_ACTIVE)
  883. (void)SSL_shutdown(connssl->handle);
  884. if(connssl->handle) {
  885. buffsize = (int)sizeof(buf);
  886. while(!done) {
  887. int what = SOCKET_READABLE(conn->sock[sockindex],
  888. SSL_SHUTDOWN_TIMEOUT);
  889. if(what > 0) {
  890. ERR_clear_error();
  891. /* Something to read, let's do it and hope that it is the close
  892. notify alert from the server */
  893. nread = (ssize_t)SSL_read(conn->ssl[sockindex].handle, buf,
  894. buffsize);
  895. err = SSL_get_error(conn->ssl[sockindex].handle, (int)nread);
  896. switch(err) {
  897. case SSL_ERROR_NONE: /* this is not an error */
  898. case SSL_ERROR_ZERO_RETURN: /* no more data */
  899. /* This is the expected response. There was no data but only
  900. the close notify alert */
  901. done = 1;
  902. break;
  903. case SSL_ERROR_WANT_READ:
  904. /* there's data pending, re-invoke SSL_read() */
  905. infof(data, "SSL_ERROR_WANT_READ\n");
  906. break;
  907. case SSL_ERROR_WANT_WRITE:
  908. /* SSL wants a write. Really odd. Let's bail out. */
  909. infof(data, "SSL_ERROR_WANT_WRITE\n");
  910. done = 1;
  911. break;
  912. default:
  913. /* openssl/ssl.h says "look at error stack/return value/errno" */
  914. sslerror = ERR_get_error();
  915. failf(conn->data, OSSL_PACKAGE " SSL_read on shutdown: %s, errno %d",
  916. (sslerror ?
  917. ossl_strerror(sslerror, buf, sizeof(buf)) :
  918. SSL_ERROR_to_str(err)),
  919. SOCKERRNO);
  920. done = 1;
  921. break;
  922. }
  923. }
  924. else if(0 == what) {
  925. /* timeout */
  926. failf(data, "SSL shutdown timeout");
  927. done = 1;
  928. }
  929. else {
  930. /* anything that gets here is fatally bad */
  931. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  932. retval = -1;
  933. done = 1;
  934. }
  935. } /* while()-loop for the select() */
  936. if(data->set.verbose) {
  937. #ifdef HAVE_SSL_GET_SHUTDOWN
  938. switch(SSL_get_shutdown(connssl->handle)) {
  939. case SSL_SENT_SHUTDOWN:
  940. infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN\n");
  941. break;
  942. case SSL_RECEIVED_SHUTDOWN:
  943. infof(data, "SSL_get_shutdown() returned SSL_RECEIVED_SHUTDOWN\n");
  944. break;
  945. case SSL_SENT_SHUTDOWN|SSL_RECEIVED_SHUTDOWN:
  946. infof(data, "SSL_get_shutdown() returned SSL_SENT_SHUTDOWN|"
  947. "SSL_RECEIVED__SHUTDOWN\n");
  948. break;
  949. }
  950. #endif
  951. }
  952. SSL_free(connssl->handle);
  953. connssl->handle = NULL;
  954. }
  955. return retval;
  956. }
  957. void Curl_ossl_session_free(void *ptr)
  958. {
  959. /* free the ID */
  960. SSL_SESSION_free(ptr);
  961. }
  962. /*
  963. * This function is called when the 'data' struct is going away. Close
  964. * down everything and free all resources!
  965. */
  966. void Curl_ossl_close_all(struct Curl_easy *data)
  967. {
  968. #ifdef HAVE_OPENSSL_ENGINE_H
  969. if(data->state.engine) {
  970. ENGINE_finish(data->state.engine);
  971. ENGINE_free(data->state.engine);
  972. data->state.engine = NULL;
  973. }
  974. #else
  975. (void)data;
  976. #endif
  977. #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
  978. defined(HAVE_ERR_REMOVE_THREAD_STATE)
  979. /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
  980. so we need to clean it here in case the thread will be killed. All OpenSSL
  981. code should extract the error in association with the error so clearing
  982. this queue here should be harmless at worst. */
  983. ERR_remove_thread_state(NULL);
  984. #endif
  985. }
  986. /* ====================================================== */
  987. /* Quote from RFC2818 section 3.1 "Server Identity"
  988. If a subjectAltName extension of type dNSName is present, that MUST
  989. be used as the identity. Otherwise, the (most specific) Common Name
  990. field in the Subject field of the certificate MUST be used. Although
  991. the use of the Common Name is existing practice, it is deprecated and
  992. Certification Authorities are encouraged to use the dNSName instead.
  993. Matching is performed using the matching rules specified by
  994. [RFC2459]. If more than one identity of a given type is present in
  995. the certificate (e.g., more than one dNSName name, a match in any one
  996. of the set is considered acceptable.) Names may contain the wildcard
  997. character * which is considered to match any single domain name
  998. component or component fragment. E.g., *.a.com matches foo.a.com but
  999. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  1000. In some cases, the URI is specified as an IP address rather than a
  1001. hostname. In this case, the iPAddress subjectAltName must be present
  1002. in the certificate and must exactly match the IP in the URI.
  1003. */
  1004. static CURLcode verifyhost(struct connectdata *conn, X509 *server_cert)
  1005. {
  1006. bool matched = FALSE;
  1007. int target = GEN_DNS; /* target type, GEN_DNS or GEN_IPADD */
  1008. size_t addrlen = 0;
  1009. struct Curl_easy *data = conn->data;
  1010. STACK_OF(GENERAL_NAME) *altnames;
  1011. #ifdef ENABLE_IPV6
  1012. struct in6_addr addr;
  1013. #else
  1014. struct in_addr addr;
  1015. #endif
  1016. CURLcode result = CURLE_OK;
  1017. bool dNSName = FALSE; /* if a dNSName field exists in the cert */
  1018. bool iPAddress = FALSE; /* if a iPAddress field exists in the cert */
  1019. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  1020. conn->host.name;
  1021. const char * const dispname = SSL_IS_PROXY() ?
  1022. conn->http_proxy.host.dispname : conn->host.dispname;
  1023. #ifdef ENABLE_IPV6
  1024. if(conn->bits.ipv6_ip &&
  1025. Curl_inet_pton(AF_INET6, hostname, &addr)) {
  1026. target = GEN_IPADD;
  1027. addrlen = sizeof(struct in6_addr);
  1028. }
  1029. else
  1030. #endif
  1031. if(Curl_inet_pton(AF_INET, hostname, &addr)) {
  1032. target = GEN_IPADD;
  1033. addrlen = sizeof(struct in_addr);
  1034. }
  1035. /* get a "list" of alternative names */
  1036. altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
  1037. if(altnames) {
  1038. int numalts;
  1039. int i;
  1040. bool dnsmatched = FALSE;
  1041. bool ipmatched = FALSE;
  1042. /* get amount of alternatives, RFC2459 claims there MUST be at least
  1043. one, but we don't depend on it... */
  1044. numalts = sk_GENERAL_NAME_num(altnames);
  1045. /* loop through all alternatives - until a dnsmatch */
  1046. for(i=0; (i < numalts) && !dnsmatched; i++) {
  1047. /* get a handle to alternative name number i */
  1048. const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
  1049. if(check->type == GEN_DNS)
  1050. dNSName = TRUE;
  1051. else if(check->type == GEN_IPADD)
  1052. iPAddress = TRUE;
  1053. /* only check alternatives of the same type the target is */
  1054. if(check->type == target) {
  1055. /* get data and length */
  1056. const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
  1057. size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
  1058. switch(target) {
  1059. case GEN_DNS: /* name/pattern comparison */
  1060. /* The OpenSSL man page explicitly says: "In general it cannot be
  1061. assumed that the data returned by ASN1_STRING_data() is null
  1062. terminated or does not contain embedded nulls." But also that
  1063. "The actual format of the data will depend on the actual string
  1064. type itself: for example for and IA5String the data will be ASCII"
  1065. Gisle researched the OpenSSL sources:
  1066. "I checked the 0.9.6 and 0.9.8 sources before my patch and
  1067. it always 0-terminates an IA5String."
  1068. */
  1069. if((altlen == strlen(altptr)) &&
  1070. /* if this isn't true, there was an embedded zero in the name
  1071. string and we cannot match it. */
  1072. Curl_cert_hostcheck(altptr, hostname)) {
  1073. dnsmatched = TRUE;
  1074. infof(data,
  1075. " subjectAltName: host \"%s\" matched cert's \"%s\"\n",
  1076. dispname, altptr);
  1077. }
  1078. break;
  1079. case GEN_IPADD: /* IP address comparison */
  1080. /* compare alternative IP address if the data chunk is the same size
  1081. our server IP address is */
  1082. if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
  1083. ipmatched = TRUE;
  1084. infof(data,
  1085. " subjectAltName: host \"%s\" matched cert's IP address!\n",
  1086. dispname);
  1087. }
  1088. break;
  1089. }
  1090. }
  1091. }
  1092. GENERAL_NAMES_free(altnames);
  1093. if(dnsmatched || ipmatched)
  1094. matched = TRUE;
  1095. }
  1096. if(matched)
  1097. /* an alternative name matched */
  1098. ;
  1099. else if(dNSName || iPAddress) {
  1100. infof(data, " subjectAltName does not match %s\n", dispname);
  1101. failf(data, "SSL: no alternative certificate subject name matches "
  1102. "target host name '%s'", dispname);
  1103. result = CURLE_PEER_FAILED_VERIFICATION;
  1104. }
  1105. else {
  1106. /* we have to look to the last occurrence of a commonName in the
  1107. distinguished one to get the most significant one. */
  1108. int j, i=-1;
  1109. /* The following is done because of a bug in 0.9.6b */
  1110. unsigned char *nulstr = (unsigned char *)"";
  1111. unsigned char *peer_CN = nulstr;
  1112. X509_NAME *name = X509_get_subject_name(server_cert);
  1113. if(name)
  1114. while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i))>=0)
  1115. i=j;
  1116. /* we have the name entry and we will now convert this to a string
  1117. that we can use for comparison. Doing this we support BMPstring,
  1118. UTF8 etc. */
  1119. if(i>=0) {
  1120. ASN1_STRING *tmp =
  1121. X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
  1122. /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
  1123. is already UTF-8 encoded. We check for this case and copy the raw
  1124. string manually to avoid the problem. This code can be made
  1125. conditional in the future when OpenSSL has been fixed. Work-around
  1126. brought by Alexis S. L. Carvalho. */
  1127. if(tmp) {
  1128. if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
  1129. j = ASN1_STRING_length(tmp);
  1130. if(j >= 0) {
  1131. peer_CN = OPENSSL_malloc(j+1);
  1132. if(peer_CN) {
  1133. memcpy(peer_CN, ASN1_STRING_get0_data(tmp), j);
  1134. peer_CN[j] = '\0';
  1135. }
  1136. }
  1137. }
  1138. else /* not a UTF8 name */
  1139. j = ASN1_STRING_to_UTF8(&peer_CN, tmp);
  1140. if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != j)) {
  1141. /* there was a terminating zero before the end of string, this
  1142. cannot match and we return failure! */
  1143. failf(data, "SSL: illegal cert name field");
  1144. result = CURLE_PEER_FAILED_VERIFICATION;
  1145. }
  1146. }
  1147. }
  1148. if(peer_CN == nulstr)
  1149. peer_CN = NULL;
  1150. else {
  1151. /* convert peer_CN from UTF8 */
  1152. CURLcode rc = Curl_convert_from_utf8(data, peer_CN, strlen(peer_CN));
  1153. /* Curl_convert_from_utf8 calls failf if unsuccessful */
  1154. if(rc) {
  1155. OPENSSL_free(peer_CN);
  1156. return rc;
  1157. }
  1158. }
  1159. if(result)
  1160. /* error already detected, pass through */
  1161. ;
  1162. else if(!peer_CN) {
  1163. failf(data,
  1164. "SSL: unable to obtain common name from peer certificate");
  1165. result = CURLE_PEER_FAILED_VERIFICATION;
  1166. }
  1167. else if(!Curl_cert_hostcheck((const char *)peer_CN, hostname)) {
  1168. failf(data, "SSL: certificate subject name '%s' does not match "
  1169. "target host name '%s'", peer_CN, dispname);
  1170. result = CURLE_PEER_FAILED_VERIFICATION;
  1171. }
  1172. else {
  1173. infof(data, " common name: %s (matched)\n", peer_CN);
  1174. }
  1175. if(peer_CN)
  1176. OPENSSL_free(peer_CN);
  1177. }
  1178. return result;
  1179. }
  1180. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  1181. !defined(OPENSSL_NO_OCSP)
  1182. static CURLcode verifystatus(struct connectdata *conn,
  1183. struct ssl_connect_data *connssl)
  1184. {
  1185. int i, ocsp_status;
  1186. const unsigned char *p;
  1187. CURLcode result = CURLE_OK;
  1188. struct Curl_easy *data = conn->data;
  1189. OCSP_RESPONSE *rsp = NULL;
  1190. OCSP_BASICRESP *br = NULL;
  1191. X509_STORE *st = NULL;
  1192. STACK_OF(X509) *ch = NULL;
  1193. long len = SSL_get_tlsext_status_ocsp_resp(connssl->handle, &p);
  1194. if(!p) {
  1195. failf(data, "No OCSP response received");
  1196. result = CURLE_SSL_INVALIDCERTSTATUS;
  1197. goto end;
  1198. }
  1199. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  1200. if(!rsp) {
  1201. failf(data, "Invalid OCSP response");
  1202. result = CURLE_SSL_INVALIDCERTSTATUS;
  1203. goto end;
  1204. }
  1205. ocsp_status = OCSP_response_status(rsp);
  1206. if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  1207. failf(data, "Invalid OCSP response status: %s (%d)",
  1208. OCSP_response_status_str(ocsp_status), ocsp_status);
  1209. result = CURLE_SSL_INVALIDCERTSTATUS;
  1210. goto end;
  1211. }
  1212. br = OCSP_response_get1_basic(rsp);
  1213. if(!br) {
  1214. failf(data, "Invalid OCSP response");
  1215. result = CURLE_SSL_INVALIDCERTSTATUS;
  1216. goto end;
  1217. }
  1218. ch = SSL_get_peer_cert_chain(connssl->handle);
  1219. st = SSL_CTX_get_cert_store(connssl->ctx);
  1220. #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
  1221. defined(LIBRESSL_VERSION_NUMBER))
  1222. /* The authorized responder cert in the OCSP response MUST be signed by the
  1223. peer cert's issuer (see RFC6960 section 4.2.2.2). If that's a root cert,
  1224. no problem, but if it's an intermediate cert OpenSSL has a bug where it
  1225. expects this issuer to be present in the chain embedded in the OCSP
  1226. response. So we add it if necessary. */
  1227. /* First make sure the peer cert chain includes both a peer and an issuer,
  1228. and the OCSP response contains a responder cert. */
  1229. if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
  1230. X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
  1231. /* Find issuer of responder cert and add it to the OCSP response chain */
  1232. for(i = 0; i < sk_X509_num(ch); i++) {
  1233. X509 *issuer = sk_X509_value(ch, i);
  1234. if(X509_check_issued(issuer, responder) == X509_V_OK) {
  1235. if(!OCSP_basic_add1_cert(br, issuer)) {
  1236. failf(data, "Could not add issuer cert to OCSP response");
  1237. result = CURLE_SSL_INVALIDCERTSTATUS;
  1238. goto end;
  1239. }
  1240. }
  1241. }
  1242. }
  1243. #endif
  1244. if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
  1245. failf(data, "OCSP response verification failed");
  1246. result = CURLE_SSL_INVALIDCERTSTATUS;
  1247. goto end;
  1248. }
  1249. for(i = 0; i < OCSP_resp_count(br); i++) {
  1250. int cert_status, crl_reason;
  1251. OCSP_SINGLERESP *single = NULL;
  1252. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  1253. single = OCSP_resp_get0(br, i);
  1254. if(!single)
  1255. continue;
  1256. cert_status = OCSP_single_get0_status(single, &crl_reason, &rev,
  1257. &thisupd, &nextupd);
  1258. if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
  1259. failf(data, "OCSP response has expired");
  1260. result = CURLE_SSL_INVALIDCERTSTATUS;
  1261. goto end;
  1262. }
  1263. infof(data, "SSL certificate status: %s (%d)\n",
  1264. OCSP_cert_status_str(cert_status), cert_status);
  1265. switch(cert_status) {
  1266. case V_OCSP_CERTSTATUS_GOOD:
  1267. break;
  1268. case V_OCSP_CERTSTATUS_REVOKED:
  1269. result = CURLE_SSL_INVALIDCERTSTATUS;
  1270. failf(data, "SSL certificate revocation reason: %s (%d)",
  1271. OCSP_crl_reason_str(crl_reason), crl_reason);
  1272. goto end;
  1273. case V_OCSP_CERTSTATUS_UNKNOWN:
  1274. result = CURLE_SSL_INVALIDCERTSTATUS;
  1275. goto end;
  1276. }
  1277. }
  1278. end:
  1279. if(br) OCSP_BASICRESP_free(br);
  1280. OCSP_RESPONSE_free(rsp);
  1281. return result;
  1282. }
  1283. #endif
  1284. #endif /* USE_OPENSSL */
  1285. /* The SSL_CTRL_SET_MSG_CALLBACK doesn't exist in ancient OpenSSL versions
  1286. and thus this cannot be done there. */
  1287. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  1288. static const char *ssl_msg_type(int ssl_ver, int msg)
  1289. {
  1290. #ifdef SSL2_VERSION_MAJOR
  1291. if(ssl_ver == SSL2_VERSION_MAJOR) {
  1292. switch(msg) {
  1293. case SSL2_MT_ERROR:
  1294. return "Error";
  1295. case SSL2_MT_CLIENT_HELLO:
  1296. return "Client hello";
  1297. case SSL2_MT_CLIENT_MASTER_KEY:
  1298. return "Client key";
  1299. case SSL2_MT_CLIENT_FINISHED:
  1300. return "Client finished";
  1301. case SSL2_MT_SERVER_HELLO:
  1302. return "Server hello";
  1303. case SSL2_MT_SERVER_VERIFY:
  1304. return "Server verify";
  1305. case SSL2_MT_SERVER_FINISHED:
  1306. return "Server finished";
  1307. case SSL2_MT_REQUEST_CERTIFICATE:
  1308. return "Request CERT";
  1309. case SSL2_MT_CLIENT_CERTIFICATE:
  1310. return "Client CERT";
  1311. }
  1312. }
  1313. else
  1314. #endif
  1315. if(ssl_ver == SSL3_VERSION_MAJOR) {
  1316. switch(msg) {
  1317. case SSL3_MT_HELLO_REQUEST:
  1318. return "Hello request";
  1319. case SSL3_MT_CLIENT_HELLO:
  1320. return "Client hello";
  1321. case SSL3_MT_SERVER_HELLO:
  1322. return "Server hello";
  1323. #ifdef SSL3_MT_NEWSESSION_TICKET
  1324. case SSL3_MT_NEWSESSION_TICKET:
  1325. return "Newsession Ticket";
  1326. #endif
  1327. case SSL3_MT_CERTIFICATE:
  1328. return "Certificate";
  1329. case SSL3_MT_SERVER_KEY_EXCHANGE:
  1330. return "Server key exchange";
  1331. case SSL3_MT_CLIENT_KEY_EXCHANGE:
  1332. return "Client key exchange";
  1333. case SSL3_MT_CERTIFICATE_REQUEST:
  1334. return "Request CERT";
  1335. case SSL3_MT_SERVER_DONE:
  1336. return "Server finished";
  1337. case SSL3_MT_CERTIFICATE_VERIFY:
  1338. return "CERT verify";
  1339. case SSL3_MT_FINISHED:
  1340. return "Finished";
  1341. #ifdef SSL3_MT_CERTIFICATE_STATUS
  1342. case SSL3_MT_CERTIFICATE_STATUS:
  1343. return "Certificate Status";
  1344. #endif
  1345. }
  1346. }
  1347. return "Unknown";
  1348. }
  1349. static const char *tls_rt_type(int type)
  1350. {
  1351. switch(type) {
  1352. #ifdef SSL3_RT_HEADER
  1353. case SSL3_RT_HEADER:
  1354. return "TLS header";
  1355. #endif
  1356. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1357. return "TLS change cipher";
  1358. case SSL3_RT_ALERT:
  1359. return "TLS alert";
  1360. case SSL3_RT_HANDSHAKE:
  1361. return "TLS handshake";
  1362. case SSL3_RT_APPLICATION_DATA:
  1363. return "TLS app data";
  1364. default:
  1365. return "TLS Unknown";
  1366. }
  1367. }
  1368. /*
  1369. * Our callback from the SSL/TLS layers.
  1370. */
  1371. static void ssl_tls_trace(int direction, int ssl_ver, int content_type,
  1372. const void *buf, size_t len, SSL *ssl,
  1373. void *userp)
  1374. {
  1375. struct Curl_easy *data;
  1376. const char *msg_name, *tls_rt_name;
  1377. char ssl_buf[1024];
  1378. char unknown[32];
  1379. int msg_type, txt_len;
  1380. const char *verstr = NULL;
  1381. struct connectdata *conn = userp;
  1382. if(!conn || !conn->data || !conn->data->set.fdebug ||
  1383. (direction != 0 && direction != 1))
  1384. return;
  1385. data = conn->data;
  1386. switch(ssl_ver) {
  1387. #ifdef SSL2_VERSION /* removed in recent versions */
  1388. case SSL2_VERSION:
  1389. verstr = "SSLv2";
  1390. break;
  1391. #endif
  1392. #ifdef SSL3_VERSION
  1393. case SSL3_VERSION:
  1394. verstr = "SSLv3";
  1395. break;
  1396. #endif
  1397. case TLS1_VERSION:
  1398. verstr = "TLSv1.0";
  1399. break;
  1400. #ifdef TLS1_1_VERSION
  1401. case TLS1_1_VERSION:
  1402. verstr = "TLSv1.1";
  1403. break;
  1404. #endif
  1405. #ifdef TLS1_2_VERSION
  1406. case TLS1_2_VERSION:
  1407. verstr = "TLSv1.2";
  1408. break;
  1409. #endif
  1410. #ifdef TLS1_3_VERSION
  1411. case TLS1_3_VERSION:
  1412. verstr = "TLSv1.3";
  1413. break;
  1414. #endif
  1415. case 0:
  1416. break;
  1417. default:
  1418. snprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
  1419. verstr = unknown;
  1420. break;
  1421. }
  1422. if(ssl_ver) {
  1423. /* the info given when the version is zero is not that useful for us */
  1424. ssl_ver >>= 8; /* check the upper 8 bits only below */
  1425. /* SSLv2 doesn't seem to have TLS record-type headers, so OpenSSL
  1426. * always pass-up content-type as 0. But the interesting message-type
  1427. * is at 'buf[0]'.
  1428. */
  1429. if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
  1430. tls_rt_name = tls_rt_type(content_type);
  1431. else
  1432. tls_rt_name = "";
  1433. msg_type = *(char *)buf;
  1434. msg_name = ssl_msg_type(ssl_ver, msg_type);
  1435. txt_len = snprintf(ssl_buf, sizeof(ssl_buf), "%s (%s), %s, %s (%d):\n",
  1436. verstr, direction?"OUT":"IN",
  1437. tls_rt_name, msg_name, msg_type);
  1438. Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len, NULL);
  1439. }
  1440. Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
  1441. CURLINFO_SSL_DATA_IN, (char *)buf, len, NULL);
  1442. (void) ssl;
  1443. }
  1444. #endif
  1445. #ifdef USE_OPENSSL
  1446. /* ====================================================== */
  1447. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  1448. # define use_sni(x) sni = (x)
  1449. #else
  1450. # define use_sni(x) Curl_nop_stmt
  1451. #endif
  1452. /* Check for OpenSSL 1.0.2 which has ALPN support. */
  1453. #undef HAS_ALPN
  1454. #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
  1455. && !defined(OPENSSL_NO_TLSEXT)
  1456. # define HAS_ALPN 1
  1457. #endif
  1458. /* Check for OpenSSL 1.0.1 which has NPN support. */
  1459. #undef HAS_NPN
  1460. #if OPENSSL_VERSION_NUMBER >= 0x10001000L \
  1461. && !defined(OPENSSL_NO_TLSEXT) \
  1462. && !defined(OPENSSL_NO_NEXTPROTONEG)
  1463. # define HAS_NPN 1
  1464. #endif
  1465. #ifdef HAS_NPN
  1466. /*
  1467. * in is a list of length prefixed strings. this function has to select
  1468. * the protocol we want to use from the list and write its string into out.
  1469. */
  1470. static int
  1471. select_next_protocol(unsigned char **out, unsigned char *outlen,
  1472. const unsigned char *in, unsigned int inlen,
  1473. const char *key, unsigned int keylen)
  1474. {
  1475. unsigned int i;
  1476. for(i = 0; i + keylen <= inlen; i += in[i] + 1) {
  1477. if(memcmp(&in[i + 1], key, keylen) == 0) {
  1478. *out = (unsigned char *) &in[i + 1];
  1479. *outlen = in[i];
  1480. return 0;
  1481. }
  1482. }
  1483. return -1;
  1484. }
  1485. static int
  1486. select_next_proto_cb(SSL *ssl,
  1487. unsigned char **out, unsigned char *outlen,
  1488. const unsigned char *in, unsigned int inlen,
  1489. void *arg)
  1490. {
  1491. struct connectdata *conn = (struct connectdata*) arg;
  1492. (void)ssl;
  1493. #ifdef USE_NGHTTP2
  1494. if(conn->data->set.httpversion >= CURL_HTTP_VERSION_2 &&
  1495. !select_next_protocol(out, outlen, in, inlen, NGHTTP2_PROTO_VERSION_ID,
  1496. NGHTTP2_PROTO_VERSION_ID_LEN)) {
  1497. infof(conn->data, "NPN, negotiated HTTP2 (%s)\n",
  1498. NGHTTP2_PROTO_VERSION_ID);
  1499. conn->negnpn = CURL_HTTP_VERSION_2;
  1500. return SSL_TLSEXT_ERR_OK;
  1501. }
  1502. #endif
  1503. if(!select_next_protocol(out, outlen, in, inlen, ALPN_HTTP_1_1,
  1504. ALPN_HTTP_1_1_LENGTH)) {
  1505. infof(conn->data, "NPN, negotiated HTTP1.1\n");
  1506. conn->negnpn = CURL_HTTP_VERSION_1_1;
  1507. return SSL_TLSEXT_ERR_OK;
  1508. }
  1509. infof(conn->data, "NPN, no overlap, use HTTP1.1\n");
  1510. *out = (unsigned char *)ALPN_HTTP_1_1;
  1511. *outlen = ALPN_HTTP_1_1_LENGTH;
  1512. conn->negnpn = CURL_HTTP_VERSION_1_1;
  1513. return SSL_TLSEXT_ERR_OK;
  1514. }
  1515. #endif /* HAS_NPN */
  1516. static const char *
  1517. get_ssl_version_txt(SSL *ssl)
  1518. {
  1519. if(!ssl)
  1520. return "";
  1521. switch(SSL_version(ssl)) {
  1522. #ifdef TLS1_3_VERSION
  1523. case TLS1_3_VERSION:
  1524. return "TLSv1.3";
  1525. #endif
  1526. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1527. case TLS1_2_VERSION:
  1528. return "TLSv1.2";
  1529. case TLS1_1_VERSION:
  1530. return "TLSv1.1";
  1531. #endif
  1532. case TLS1_VERSION:
  1533. return "TLSv1.0";
  1534. case SSL3_VERSION:
  1535. return "SSLv3";
  1536. case SSL2_VERSION:
  1537. return "SSLv2";
  1538. }
  1539. return "unknown";
  1540. }
  1541. static CURLcode
  1542. set_ssl_version_min_max(long *ctx_options, struct connectdata *conn,
  1543. int sockindex)
  1544. {
  1545. #if (OPENSSL_VERSION_NUMBER < 0x1000100FL) || !defined(TLS1_3_VERSION)
  1546. /* convoluted #if condition just to avoid compiler warnings on unused
  1547. variable */
  1548. struct Curl_easy *data = conn->data;
  1549. #endif
  1550. long ssl_version = SSL_CONN_CONFIG(version);
  1551. long ssl_version_max = SSL_CONN_CONFIG(version_max);
  1552. if(ssl_version_max == CURL_SSLVERSION_MAX_NONE) {
  1553. ssl_version_max = ssl_version << 16;
  1554. }
  1555. switch(ssl_version) {
  1556. case CURL_SSLVERSION_TLSv1_3:
  1557. #ifdef TLS1_3_VERSION
  1558. {
  1559. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1560. SSL_CTX_set_max_proto_version(connssl->ctx, TLS1_3_VERSION);
  1561. *ctx_options |= SSL_OP_NO_TLSv1_2;
  1562. }
  1563. #else
  1564. (void)sockindex;
  1565. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  1566. return CURLE_NOT_BUILT_IN;
  1567. #endif
  1568. case CURL_SSLVERSION_TLSv1_2:
  1569. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1570. *ctx_options |= SSL_OP_NO_TLSv1_1;
  1571. #else
  1572. failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
  1573. return CURLE_NOT_BUILT_IN;
  1574. #endif
  1575. /* FALLTHROUGH */
  1576. case CURL_SSLVERSION_TLSv1_1:
  1577. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1578. *ctx_options |= SSL_OP_NO_TLSv1;
  1579. #else
  1580. failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
  1581. return CURLE_NOT_BUILT_IN;
  1582. #endif
  1583. /* FALLTHROUGH */
  1584. case CURL_SSLVERSION_TLSv1_0:
  1585. *ctx_options |= SSL_OP_NO_SSLv2;
  1586. *ctx_options |= SSL_OP_NO_SSLv3;
  1587. break;
  1588. }
  1589. switch(ssl_version_max) {
  1590. case CURL_SSLVERSION_MAX_TLSv1_0:
  1591. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1592. *ctx_options |= SSL_OP_NO_TLSv1_1;
  1593. #endif
  1594. /* FALLTHROUGH */
  1595. case CURL_SSLVERSION_MAX_TLSv1_1:
  1596. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1597. *ctx_options |= SSL_OP_NO_TLSv1_2;
  1598. #endif
  1599. /* FALLTHROUGH */
  1600. case CURL_SSLVERSION_MAX_TLSv1_2:
  1601. case CURL_SSLVERSION_MAX_DEFAULT:
  1602. #ifdef TLS1_3_VERSION
  1603. *ctx_options |= SSL_OP_NO_TLSv1_3;
  1604. #endif
  1605. break;
  1606. case CURL_SSLVERSION_MAX_TLSv1_3:
  1607. #ifdef TLS1_3_VERSION
  1608. break;
  1609. #else
  1610. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  1611. return CURLE_NOT_BUILT_IN;
  1612. #endif
  1613. }
  1614. return CURLE_OK;
  1615. }
  1616. static CURLcode ossl_connect_step1(struct connectdata *conn, int sockindex)
  1617. {
  1618. CURLcode result = CURLE_OK;
  1619. char *ciphers;
  1620. struct Curl_easy *data = conn->data;
  1621. SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
  1622. X509_LOOKUP *lookup = NULL;
  1623. curl_socket_t sockfd = conn->sock[sockindex];
  1624. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  1625. long ctx_options = 0;
  1626. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  1627. bool sni;
  1628. const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name :
  1629. conn->host.name;
  1630. #ifdef ENABLE_IPV6
  1631. struct in6_addr addr;
  1632. #else
  1633. struct in_addr addr;
  1634. #endif
  1635. #endif
  1636. long * const certverifyresult = SSL_IS_PROXY() ?
  1637. &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
  1638. const long int ssl_version = SSL_CONN_CONFIG(version);
  1639. #ifdef USE_TLS_SRP
  1640. const enum CURL_TLSAUTH ssl_authtype = SSL_SET_OPTION(authtype);
  1641. #endif
  1642. char * const ssl_cert = SSL_SET_OPTION(cert);
  1643. const char * const ssl_cert_type = SSL_SET_OPTION(cert_type);
  1644. const char * const ssl_cafile = SSL_CONN_CONFIG(CAfile);
  1645. const char * const ssl_capath = SSL_CONN_CONFIG(CApath);
  1646. const bool verifypeer = SSL_CONN_CONFIG(verifypeer);
  1647. const char * const ssl_crlfile = SSL_SET_OPTION(CRLfile);
  1648. char error_buffer[256];
  1649. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  1650. /* Make funny stuff to get random input */
  1651. result = Curl_ossl_seed(data);
  1652. if(result)
  1653. return result;
  1654. *certverifyresult = !X509_V_OK;
  1655. /* check to see if we've been told to use an explicit SSL/TLS version */
  1656. switch(ssl_version) {
  1657. case CURL_SSLVERSION_DEFAULT:
  1658. case CURL_SSLVERSION_TLSv1:
  1659. case CURL_SSLVERSION_TLSv1_0:
  1660. case CURL_SSLVERSION_TLSv1_1:
  1661. case CURL_SSLVERSION_TLSv1_2:
  1662. case CURL_SSLVERSION_TLSv1_3:
  1663. /* it will be handled later with the context options */
  1664. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  1665. !defined(LIBRESSL_VERSION_NUMBER)
  1666. req_method = TLS_client_method();
  1667. #else
  1668. req_method = SSLv23_client_method();
  1669. #endif
  1670. use_sni(TRUE);
  1671. break;
  1672. case CURL_SSLVERSION_SSLv2:
  1673. #ifdef OPENSSL_NO_SSL2
  1674. failf(data, OSSL_PACKAGE " was built without SSLv2 support");
  1675. return CURLE_NOT_BUILT_IN;
  1676. #else
  1677. #ifdef USE_TLS_SRP
  1678. if(ssl_authtype == CURL_TLSAUTH_SRP)
  1679. return CURLE_SSL_CONNECT_ERROR;
  1680. #endif
  1681. req_method = SSLv2_client_method();
  1682. use_sni(FALSE);
  1683. break;
  1684. #endif
  1685. case CURL_SSLVERSION_SSLv3:
  1686. #ifdef OPENSSL_NO_SSL3_METHOD
  1687. failf(data, OSSL_PACKAGE " was built without SSLv3 support");
  1688. return CURLE_NOT_BUILT_IN;
  1689. #else
  1690. #ifdef USE_TLS_SRP
  1691. if(ssl_authtype == CURL_TLSAUTH_SRP)
  1692. return CURLE_SSL_CONNECT_ERROR;
  1693. #endif
  1694. req_method = SSLv3_client_method();
  1695. use_sni(FALSE);
  1696. break;
  1697. #endif
  1698. default:
  1699. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  1700. return CURLE_SSL_CONNECT_ERROR;
  1701. }
  1702. if(connssl->ctx)
  1703. SSL_CTX_free(connssl->ctx);
  1704. connssl->ctx = SSL_CTX_new(req_method);
  1705. if(!connssl->ctx) {
  1706. failf(data, "SSL: couldn't create a context: %s",
  1707. ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
  1708. return CURLE_OUT_OF_MEMORY;
  1709. }
  1710. #ifdef SSL_MODE_RELEASE_BUFFERS
  1711. SSL_CTX_set_mode(connssl->ctx, SSL_MODE_RELEASE_BUFFERS);
  1712. #endif
  1713. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  1714. if(data->set.fdebug && data->set.verbose) {
  1715. /* the SSL trace callback is only used for verbose logging */
  1716. SSL_CTX_set_msg_callback(connssl->ctx, ssl_tls_trace);
  1717. SSL_CTX_set_msg_callback_arg(connssl->ctx, conn);
  1718. }
  1719. #endif
  1720. /* OpenSSL contains code to work-around lots of bugs and flaws in various
  1721. SSL-implementations. SSL_CTX_set_options() is used to enabled those
  1722. work-arounds. The man page for this option states that SSL_OP_ALL enables
  1723. all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
  1724. enable the bug workaround options if compatibility with somewhat broken
  1725. implementations is desired."
  1726. The "-no_ticket" option was introduced in Openssl0.9.8j. It's a flag to
  1727. disable "rfc4507bis session ticket support". rfc4507bis was later turned
  1728. into the proper RFC5077 it seems: https://tools.ietf.org/html/rfc5077
  1729. The enabled extension concerns the session management. I wonder how often
  1730. libcurl stops a connection and then resumes a TLS session. also, sending
  1731. the session data is some overhead. .I suggest that you just use your
  1732. proposed patch (which explicitly disables TICKET).
  1733. If someone writes an application with libcurl and openssl who wants to
  1734. enable the feature, one can do this in the SSL callback.
  1735. SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
  1736. interoperability with web server Netscape Enterprise Server 2.0.1 which
  1737. was released back in 1996.
  1738. Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
  1739. become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
  1740. CVE-2010-4180 when using previous OpenSSL versions we no longer enable
  1741. this option regardless of OpenSSL version and SSL_OP_ALL definition.
  1742. OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability
  1743. (https://www.openssl.org/~bodo/tls-cbc.txt). In 0.9.6e they added a bit to
  1744. SSL_OP_ALL that _disables_ that work-around despite the fact that
  1745. SSL_OP_ALL is documented to do "rather harmless" workarounds. In order to
  1746. keep the secure work-around, the SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit
  1747. must not be set.
  1748. */
  1749. ctx_options = SSL_OP_ALL;
  1750. #ifdef SSL_OP_NO_TICKET
  1751. ctx_options |= SSL_OP_NO_TICKET;
  1752. #endif
  1753. #ifdef SSL_OP_NO_COMPRESSION
  1754. ctx_options |= SSL_OP_NO_COMPRESSION;
  1755. #endif
  1756. #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
  1757. /* mitigate CVE-2010-4180 */
  1758. ctx_options &= ~SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
  1759. #endif
  1760. #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  1761. /* unless the user explicitly ask to allow the protocol vulnerability we
  1762. use the work-around */
  1763. if(!SSL_SET_OPTION(enable_beast))
  1764. ctx_options &= ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
  1765. #endif
  1766. switch(ssl_version) {
  1767. case CURL_SSLVERSION_SSLv3:
  1768. #ifdef USE_TLS_SRP
  1769. if(ssl_authtype == CURL_TLSAUTH_SRP) {
  1770. infof(data, "Set version TLSv1.x for SRP authorisation\n");
  1771. }
  1772. #endif
  1773. ctx_options |= SSL_OP_NO_SSLv2;
  1774. ctx_options |= SSL_OP_NO_TLSv1;
  1775. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1776. ctx_options |= SSL_OP_NO_TLSv1_1;
  1777. ctx_options |= SSL_OP_NO_TLSv1_2;
  1778. #ifdef TLS1_3_VERSION
  1779. ctx_options |= SSL_OP_NO_TLSv1_3;
  1780. #endif
  1781. #endif
  1782. break;
  1783. case CURL_SSLVERSION_DEFAULT:
  1784. case CURL_SSLVERSION_TLSv1:
  1785. ctx_options |= SSL_OP_NO_SSLv2;
  1786. ctx_options |= SSL_OP_NO_SSLv3;
  1787. break;
  1788. case CURL_SSLVERSION_TLSv1_0:
  1789. case CURL_SSLVERSION_TLSv1_1:
  1790. case CURL_SSLVERSION_TLSv1_2:
  1791. case CURL_SSLVERSION_TLSv1_3:
  1792. result = set_ssl_version_min_max(&ctx_options, conn, sockindex);
  1793. if(result != CURLE_OK)
  1794. return result;
  1795. break;
  1796. case CURL_SSLVERSION_SSLv2:
  1797. #ifndef OPENSSL_NO_SSL2
  1798. ctx_options |= SSL_OP_NO_SSLv3;
  1799. ctx_options |= SSL_OP_NO_TLSv1;
  1800. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  1801. ctx_options |= SSL_OP_NO_TLSv1_1;
  1802. ctx_options |= SSL_OP_NO_TLSv1_2;
  1803. #ifdef TLS1_3_VERSION
  1804. ctx_options |= SSL_OP_NO_TLSv1_3;
  1805. #endif
  1806. #endif
  1807. break;
  1808. #else
  1809. failf(data, OSSL_PACKAGE " was built without SSLv2 support");
  1810. return CURLE_NOT_BUILT_IN;
  1811. #endif
  1812. default:
  1813. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  1814. return CURLE_SSL_CONNECT_ERROR;
  1815. }
  1816. SSL_CTX_set_options(connssl->ctx, ctx_options);
  1817. #ifdef HAS_NPN
  1818. if(conn->bits.tls_enable_npn)
  1819. SSL_CTX_set_next_proto_select_cb(connssl->ctx, select_next_proto_cb, conn);
  1820. #endif
  1821. #ifdef HAS_ALPN
  1822. if(conn->bits.tls_enable_alpn) {
  1823. int cur = 0;
  1824. unsigned char protocols[128];
  1825. #ifdef USE_NGHTTP2
  1826. if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
  1827. protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
  1828. memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
  1829. NGHTTP2_PROTO_VERSION_ID_LEN);
  1830. cur += NGHTTP2_PROTO_VERSION_ID_LEN;
  1831. infof(data, "ALPN, offering %s\n", NGHTTP2_PROTO_VERSION_ID);
  1832. }
  1833. #endif
  1834. protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
  1835. memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
  1836. cur += ALPN_HTTP_1_1_LENGTH;
  1837. infof(data, "ALPN, offering %s\n", ALPN_HTTP_1_1);
  1838. /* expects length prefixed preference ordered list of protocols in wire
  1839. * format
  1840. */
  1841. SSL_CTX_set_alpn_protos(connssl->ctx, protocols, cur);
  1842. }
  1843. #endif
  1844. if(ssl_cert || ssl_cert_type) {
  1845. if(!cert_stuff(conn, connssl->ctx, ssl_cert, ssl_cert_type,
  1846. SSL_SET_OPTION(key), SSL_SET_OPTION(key_type),
  1847. SSL_SET_OPTION(key_passwd))) {
  1848. /* failf() is already done in cert_stuff() */
  1849. return CURLE_SSL_CERTPROBLEM;
  1850. }
  1851. }
  1852. ciphers = SSL_CONN_CONFIG(cipher_list);
  1853. if(!ciphers)
  1854. ciphers = (char *)DEFAULT_CIPHER_SELECTION;
  1855. if(!SSL_CTX_set_cipher_list(connssl->ctx, ciphers)) {
  1856. failf(data, "failed setting cipher list: %s", ciphers);
  1857. return CURLE_SSL_CIPHER;
  1858. }
  1859. infof(data, "Cipher selection: %s\n", ciphers);
  1860. #ifdef USE_TLS_SRP
  1861. if(ssl_authtype == CURL_TLSAUTH_SRP) {
  1862. char * const ssl_username = SSL_SET_OPTION(username);
  1863. infof(data, "Using TLS-SRP username: %s\n", ssl_username);
  1864. if(!SSL_CTX_set_srp_username(connssl->ctx, ssl_username)) {
  1865. failf(data, "Unable to set SRP user name");
  1866. return CURLE_BAD_FUNCTION_ARGUMENT;
  1867. }
  1868. if(!SSL_CTX_set_srp_password(connssl->ctx, SSL_SET_OPTION(password))) {
  1869. failf(data, "failed setting SRP password");
  1870. return CURLE_BAD_FUNCTION_ARGUMENT;
  1871. }
  1872. if(!SSL_CONN_CONFIG(cipher_list)) {
  1873. infof(data, "Setting cipher list SRP\n");
  1874. if(!SSL_CTX_set_cipher_list(connssl->ctx, "SRP")) {
  1875. failf(data, "failed setting SRP cipher list");
  1876. return CURLE_SSL_CIPHER;
  1877. }
  1878. }
  1879. }
  1880. #endif
  1881. if(ssl_cafile || ssl_capath) {
  1882. /* tell SSL where to find CA certificates that are used to verify
  1883. the servers certificate. */
  1884. if(!SSL_CTX_load_verify_locations(connssl->ctx, ssl_cafile, ssl_capath)) {
  1885. if(verifypeer) {
  1886. /* Fail if we insist on successfully verifying the server. */
  1887. failf(data, "error setting certificate verify locations:\n"
  1888. " CAfile: %s\n CApath: %s",
  1889. ssl_cafile ? ssl_cafile : "none",
  1890. ssl_capath ? ssl_capath : "none");
  1891. return CURLE_SSL_CACERT_BADFILE;
  1892. }
  1893. /* Just continue with a warning if no strict certificate verification
  1894. is required. */
  1895. infof(data, "error setting certificate verify locations,"
  1896. " continuing anyway:\n");
  1897. }
  1898. else {
  1899. /* Everything is fine. */
  1900. infof(data, "successfully set certificate verify locations:\n");
  1901. }
  1902. infof(data,
  1903. " CAfile: %s\n"
  1904. " CApath: %s\n",
  1905. ssl_cafile ? ssl_cafile : "none",
  1906. ssl_capath ? ssl_capath : "none");
  1907. }
  1908. #ifdef CURL_CA_FALLBACK
  1909. else if(verifypeer) {
  1910. /* verfying the peer without any CA certificates won't
  1911. work so use openssl's built in default as fallback */
  1912. SSL_CTX_set_default_verify_paths(connssl->ctx);
  1913. }
  1914. #endif
  1915. if(ssl_crlfile) {
  1916. /* tell SSL where to find CRL file that is used to check certificate
  1917. * revocation */
  1918. lookup=X509_STORE_add_lookup(SSL_CTX_get_cert_store(connssl->ctx),
  1919. X509_LOOKUP_file());
  1920. if(!lookup ||
  1921. (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
  1922. failf(data, "error loading CRL file: %s", ssl_crlfile);
  1923. return CURLE_SSL_CRL_BADFILE;
  1924. }
  1925. /* Everything is fine. */
  1926. infof(data, "successfully load CRL file:\n");
  1927. X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
  1928. X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
  1929. infof(data, " CRLfile: %s\n", ssl_crlfile);
  1930. }
  1931. /* Try building a chain using issuers in the trusted store first to avoid
  1932. problems with server-sent legacy intermediates.
  1933. Newer versions of OpenSSL do alternate chain checking by default which
  1934. gives us the same fix without as much of a performance hit (slight), so we
  1935. prefer that if available.
  1936. https://rt.openssl.org/Ticket/Display.html?id=3621&user=guest&pass=guest
  1937. */
  1938. #if defined(X509_V_FLAG_TRUSTED_FIRST) && !defined(X509_V_FLAG_NO_ALT_CHAINS)
  1939. if(verifypeer) {
  1940. X509_STORE_set_flags(SSL_CTX_get_cert_store(connssl->ctx),
  1941. X509_V_FLAG_TRUSTED_FIRST);
  1942. }
  1943. #endif
  1944. /* SSL always tries to verify the peer, this only says whether it should
  1945. * fail to connect if the verification fails, or if it should continue
  1946. * anyway. In the latter case the result of the verification is checked with
  1947. * SSL_get_verify_result() below. */
  1948. SSL_CTX_set_verify(connssl->ctx,
  1949. verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
  1950. /* give application a chance to interfere with SSL set up. */
  1951. if(data->set.ssl.fsslctx) {
  1952. result = (*data->set.ssl.fsslctx)(data, connssl->ctx,
  1953. data->set.ssl.fsslctxp);
  1954. if(result) {
  1955. failf(data, "error signaled by ssl ctx callback");
  1956. return result;
  1957. }
  1958. }
  1959. /* Lets make an SSL structure */
  1960. if(connssl->handle)
  1961. SSL_free(connssl->handle);
  1962. connssl->handle = SSL_new(connssl->ctx);
  1963. if(!connssl->handle) {
  1964. failf(data, "SSL: couldn't create a context (handle)!");
  1965. return CURLE_OUT_OF_MEMORY;
  1966. }
  1967. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  1968. !defined(OPENSSL_NO_OCSP)
  1969. if(SSL_CONN_CONFIG(verifystatus))
  1970. SSL_set_tlsext_status_type(connssl->handle, TLSEXT_STATUSTYPE_ocsp);
  1971. #endif
  1972. SSL_set_connect_state(connssl->handle);
  1973. connssl->server_cert = 0x0;
  1974. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  1975. if((0 == Curl_inet_pton(AF_INET, hostname, &addr)) &&
  1976. #ifdef ENABLE_IPV6
  1977. (0 == Curl_inet_pton(AF_INET6, hostname, &addr)) &&
  1978. #endif
  1979. sni &&
  1980. !SSL_set_tlsext_host_name(connssl->handle, hostname))
  1981. infof(data, "WARNING: failed to configure server name indication (SNI) "
  1982. "TLS extension\n");
  1983. #endif
  1984. /* Check if there's a cached ID we can/should use here! */
  1985. if(SSL_SET_OPTION(primary.sessionid)) {
  1986. void *ssl_sessionid = NULL;
  1987. Curl_ssl_sessionid_lock(conn);
  1988. if(!Curl_ssl_getsessionid(conn, &ssl_sessionid, NULL, sockindex)) {
  1989. /* we got a session id, use it! */
  1990. if(!SSL_set_session(connssl->handle, ssl_sessionid)) {
  1991. Curl_ssl_sessionid_unlock(conn);
  1992. failf(data, "SSL: SSL_set_session failed: %s",
  1993. ossl_strerror(ERR_get_error(), error_buffer,
  1994. sizeof(error_buffer)));
  1995. return CURLE_SSL_CONNECT_ERROR;
  1996. }
  1997. /* Informational message */
  1998. infof(data, "SSL re-using session ID\n");
  1999. }
  2000. Curl_ssl_sessionid_unlock(conn);
  2001. }
  2002. if(conn->proxy_ssl[sockindex].use) {
  2003. BIO *const bio = BIO_new(BIO_f_ssl());
  2004. DEBUGASSERT(ssl_connection_complete == conn->proxy_ssl[sockindex].state);
  2005. DEBUGASSERT(conn->proxy_ssl[sockindex].handle != NULL);
  2006. DEBUGASSERT(bio != NULL);
  2007. BIO_set_ssl(bio, conn->proxy_ssl[sockindex].handle, FALSE);
  2008. SSL_set_bio(connssl->handle, bio, bio);
  2009. }
  2010. else if(!SSL_set_fd(connssl->handle, (int)sockfd)) {
  2011. /* pass the raw socket into the SSL layers */
  2012. failf(data, "SSL: SSL_set_fd failed: %s",
  2013. ossl_strerror(ERR_get_error(), error_buffer, sizeof(error_buffer)));
  2014. return CURLE_SSL_CONNECT_ERROR;
  2015. }
  2016. connssl->connecting_state = ssl_connect_2;
  2017. return CURLE_OK;
  2018. }
  2019. static CURLcode ossl_connect_step2(struct connectdata *conn, int sockindex)
  2020. {
  2021. struct Curl_easy *data = conn->data;
  2022. int err;
  2023. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  2024. long * const certverifyresult = SSL_IS_PROXY() ?
  2025. &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
  2026. DEBUGASSERT(ssl_connect_2 == connssl->connecting_state
  2027. || ssl_connect_2_reading == connssl->connecting_state
  2028. || ssl_connect_2_writing == connssl->connecting_state);
  2029. ERR_clear_error();
  2030. err = SSL_connect(connssl->handle);
  2031. /* 1 is fine
  2032. 0 is "not successful but was shut down controlled"
  2033. <0 is "handshake was not successful, because a fatal error occurred" */
  2034. if(1 != err) {
  2035. int detail = SSL_get_error(connssl->handle, err);
  2036. if(SSL_ERROR_WANT_READ == detail) {
  2037. connssl->connecting_state = ssl_connect_2_reading;
  2038. return CURLE_OK;
  2039. }
  2040. if(SSL_ERROR_WANT_WRITE == detail) {
  2041. connssl->connecting_state = ssl_connect_2_writing;
  2042. return CURLE_OK;
  2043. }
  2044. else {
  2045. /* untreated error */
  2046. unsigned long errdetail;
  2047. char error_buffer[256]="";
  2048. CURLcode result;
  2049. long lerr;
  2050. int lib;
  2051. int reason;
  2052. /* the connection failed, we're not waiting for anything else. */
  2053. connssl->connecting_state = ssl_connect_2;
  2054. /* Get the earliest error code from the thread's error queue and removes
  2055. the entry. */
  2056. errdetail = ERR_get_error();
  2057. /* Extract which lib and reason */
  2058. lib = ERR_GET_LIB(errdetail);
  2059. reason = ERR_GET_REASON(errdetail);
  2060. if((lib == ERR_LIB_SSL) &&
  2061. (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)) {
  2062. result = CURLE_SSL_CACERT;
  2063. lerr = SSL_get_verify_result(connssl->handle);
  2064. if(lerr != X509_V_OK) {
  2065. *certverifyresult = lerr;
  2066. snprintf(error_buffer, sizeof(error_buffer),
  2067. "SSL certificate problem: %s",
  2068. X509_verify_cert_error_string(lerr));
  2069. }
  2070. else
  2071. /* strcpy() is fine here as long as the string fits within
  2072. error_buffer */
  2073. strcpy(error_buffer, "SSL certificate verification failed");
  2074. }
  2075. else {
  2076. result = CURLE_SSL_CONNECT_ERROR;
  2077. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
  2078. }
  2079. /* detail is already set to the SSL error above */
  2080. /* If we e.g. use SSLv2 request-method and the server doesn't like us
  2081. * (RST connection etc.), OpenSSL gives no explanation whatsoever and
  2082. * the SO_ERROR is also lost.
  2083. */
  2084. if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
  2085. const char * const hostname = SSL_IS_PROXY() ?
  2086. conn->http_proxy.host.name : conn->host.name;
  2087. const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port;
  2088. failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%ld ",
  2089. SSL_ERROR_to_str(detail), hostname, port);
  2090. return result;
  2091. }
  2092. /* Could be a CERT problem */
  2093. failf(data, "%s", error_buffer);
  2094. return result;
  2095. }
  2096. }
  2097. else {
  2098. /* we have been connected fine, we're not waiting for anything else. */
  2099. connssl->connecting_state = ssl_connect_3;
  2100. /* Informational message */
  2101. infof(data, "SSL connection using %s / %s\n",
  2102. get_ssl_version_txt(connssl->handle),
  2103. SSL_get_cipher(connssl->handle));
  2104. #ifdef HAS_ALPN
  2105. /* Sets data and len to negotiated protocol, len is 0 if no protocol was
  2106. * negotiated
  2107. */
  2108. if(conn->bits.tls_enable_alpn) {
  2109. const unsigned char *neg_protocol;
  2110. unsigned int len;
  2111. SSL_get0_alpn_selected(connssl->handle, &neg_protocol, &len);
  2112. if(len != 0) {
  2113. infof(data, "ALPN, server accepted to use %.*s\n", len, neg_protocol);
  2114. #ifdef USE_NGHTTP2
  2115. if(len == NGHTTP2_PROTO_VERSION_ID_LEN &&
  2116. !memcmp(NGHTTP2_PROTO_VERSION_ID, neg_protocol, len)) {
  2117. conn->negnpn = CURL_HTTP_VERSION_2;
  2118. }
  2119. else
  2120. #endif
  2121. if(len == ALPN_HTTP_1_1_LENGTH &&
  2122. !memcmp(ALPN_HTTP_1_1, neg_protocol, ALPN_HTTP_1_1_LENGTH)) {
  2123. conn->negnpn = CURL_HTTP_VERSION_1_1;
  2124. }
  2125. }
  2126. else
  2127. infof(data, "ALPN, server did not agree to a protocol\n");
  2128. }
  2129. #endif
  2130. return CURLE_OK;
  2131. }
  2132. }
  2133. static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
  2134. {
  2135. int i, ilen;
  2136. ilen = (int)len;
  2137. if(ilen < 0)
  2138. return 1; /* buffer too big */
  2139. i = i2t_ASN1_OBJECT(buf, ilen, a);
  2140. if(i >= ilen)
  2141. return 1; /* buffer too small */
  2142. return 0;
  2143. }
  2144. #define push_certinfo(_label, _num) \
  2145. do { \
  2146. long info_len = BIO_get_mem_data(mem, &ptr); \
  2147. Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
  2148. if(1!=BIO_reset(mem)) \
  2149. break; \
  2150. } WHILE_FALSE
  2151. static void pubkey_show(struct Curl_easy *data,
  2152. BIO *mem,
  2153. int num,
  2154. const char *type,
  2155. const char *name,
  2156. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  2157. const
  2158. #endif
  2159. BIGNUM *bn)
  2160. {
  2161. char *ptr;
  2162. char namebuf[32];
  2163. snprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
  2164. if(bn)
  2165. BN_print(mem, bn);
  2166. push_certinfo(namebuf, num);
  2167. }
  2168. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  2169. #define print_pubkey_BN(_type, _name, _num) \
  2170. pubkey_show(data, mem, _num, #_type, #_name, _name)
  2171. #else
  2172. #define print_pubkey_BN(_type, _name, _num) \
  2173. do { \
  2174. if(_type->_name) { \
  2175. pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
  2176. } \
  2177. } WHILE_FALSE
  2178. #endif
  2179. static int X509V3_ext(struct Curl_easy *data,
  2180. int certnum,
  2181. CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
  2182. {
  2183. int i;
  2184. size_t j;
  2185. if((int)sk_X509_EXTENSION_num(exts) <= 0)
  2186. /* no extensions, bail out */
  2187. return 1;
  2188. for(i=0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
  2189. ASN1_OBJECT *obj;
  2190. X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i);
  2191. BUF_MEM *biomem;
  2192. char buf[512];
  2193. char *ptr=buf;
  2194. char namebuf[128];
  2195. BIO *bio_out = BIO_new(BIO_s_mem());
  2196. if(!bio_out)
  2197. return 1;
  2198. obj = X509_EXTENSION_get_object(ext);
  2199. asn1_object_dump(obj, namebuf, sizeof(namebuf));
  2200. if(!X509V3_EXT_print(bio_out, ext, 0, 0))
  2201. ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
  2202. BIO_get_mem_ptr(bio_out, &biomem);
  2203. for(j = 0; j < (size_t)biomem->length; j++) {
  2204. const char *sep="";
  2205. if(biomem->data[j] == '\n') {
  2206. sep=", ";
  2207. j++; /* skip the newline */
  2208. };
  2209. while((j<(size_t)biomem->length) && (biomem->data[j] == ' '))
  2210. j++;
  2211. if(j<(size_t)biomem->length)
  2212. ptr+=snprintf(ptr, sizeof(buf)-(ptr-buf), "%s%c", sep,
  2213. biomem->data[j]);
  2214. }
  2215. Curl_ssl_push_certinfo(data, certnum, namebuf, buf);
  2216. BIO_free(bio_out);
  2217. }
  2218. return 0; /* all is fine */
  2219. }
  2220. static CURLcode get_cert_chain(struct connectdata *conn,
  2221. struct ssl_connect_data *connssl)
  2222. {
  2223. CURLcode result;
  2224. STACK_OF(X509) *sk;
  2225. int i;
  2226. struct Curl_easy *data = conn->data;
  2227. int numcerts;
  2228. BIO *mem;
  2229. sk = SSL_get_peer_cert_chain(connssl->handle);
  2230. if(!sk) {
  2231. return CURLE_OUT_OF_MEMORY;
  2232. }
  2233. numcerts = sk_X509_num(sk);
  2234. result = Curl_ssl_init_certinfo(data, numcerts);
  2235. if(result) {
  2236. return result;
  2237. }
  2238. mem = BIO_new(BIO_s_mem());
  2239. for(i = 0; i < numcerts; i++) {
  2240. ASN1_INTEGER *num;
  2241. X509 *x = sk_X509_value(sk, i);
  2242. EVP_PKEY *pubkey=NULL;
  2243. int j;
  2244. char *ptr;
  2245. CONST_ASN1_BIT_STRING ASN1_BIT_STRING *psig = NULL;
  2246. X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  2247. push_certinfo("Subject", i);
  2248. X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  2249. push_certinfo("Issuer", i);
  2250. BIO_printf(mem, "%lx", X509_get_version(x));
  2251. push_certinfo("Version", i);
  2252. num = X509_get_serialNumber(x);
  2253. if(num->type == V_ASN1_NEG_INTEGER)
  2254. BIO_puts(mem, "-");
  2255. for(j = 0; j < num->length; j++)
  2256. BIO_printf(mem, "%02x", num->data[j]);
  2257. push_certinfo("Serial Number", i);
  2258. #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
  2259. {
  2260. const X509_ALGOR *palg = NULL;
  2261. ASN1_STRING *a = ASN1_STRING_new();
  2262. if(a) {
  2263. X509_get0_signature(&psig, &palg, x);
  2264. X509_signature_print(mem, palg, a);
  2265. ASN1_STRING_free(a);
  2266. if(palg) {
  2267. i2a_ASN1_OBJECT(mem, palg->algorithm);
  2268. push_certinfo("Public Key Algorithm", i);
  2269. }
  2270. }
  2271. X509V3_ext(data, i, X509_get0_extensions(x));
  2272. }
  2273. #else
  2274. {
  2275. /* before OpenSSL 1.0.2 */
  2276. X509_CINF *cinf = x->cert_info;
  2277. i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
  2278. push_certinfo("Signature Algorithm", i);
  2279. i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
  2280. push_certinfo("Public Key Algorithm", i);
  2281. X509V3_ext(data, i, cinf->extensions);
  2282. psig = x->signature;
  2283. }
  2284. #endif
  2285. ASN1_TIME_print(mem, X509_get0_notBefore(x));
  2286. push_certinfo("Start date", i);
  2287. ASN1_TIME_print(mem, X509_get0_notAfter(x));
  2288. push_certinfo("Expire date", i);
  2289. pubkey = X509_get_pubkey(x);
  2290. if(!pubkey)
  2291. infof(data, " Unable to load public key\n");
  2292. else {
  2293. int pktype;
  2294. #ifdef HAVE_OPAQUE_EVP_PKEY
  2295. pktype = EVP_PKEY_id(pubkey);
  2296. #else
  2297. pktype = pubkey->type;
  2298. #endif
  2299. switch(pktype) {
  2300. case EVP_PKEY_RSA:
  2301. {
  2302. RSA *rsa;
  2303. #ifdef HAVE_OPAQUE_EVP_PKEY
  2304. rsa = EVP_PKEY_get0_RSA(pubkey);
  2305. #else
  2306. rsa = pubkey->pkey.rsa;
  2307. #endif
  2308. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  2309. {
  2310. const BIGNUM *n;
  2311. const BIGNUM *e;
  2312. RSA_get0_key(rsa, &n, &e, NULL);
  2313. BN_print(mem, n);
  2314. push_certinfo("RSA Public Key", i);
  2315. print_pubkey_BN(rsa, n, i);
  2316. print_pubkey_BN(rsa, e, i);
  2317. }
  2318. #else
  2319. BIO_printf(mem, "%d", BN_num_bits(rsa->n));
  2320. push_certinfo("RSA Public Key", i);
  2321. print_pubkey_BN(rsa, n, i);
  2322. print_pubkey_BN(rsa, e, i);
  2323. #endif
  2324. break;
  2325. }
  2326. case EVP_PKEY_DSA:
  2327. {
  2328. #ifndef OPENSSL_NO_DSA
  2329. DSA *dsa;
  2330. #ifdef HAVE_OPAQUE_EVP_PKEY
  2331. dsa = EVP_PKEY_get0_DSA(pubkey);
  2332. #else
  2333. dsa = pubkey->pkey.dsa;
  2334. #endif
  2335. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  2336. {
  2337. const BIGNUM *p;
  2338. const BIGNUM *q;
  2339. const BIGNUM *g;
  2340. const BIGNUM *pub_key;
  2341. DSA_get0_pqg(dsa, &p, &q, &g);
  2342. DSA_get0_key(dsa, &pub_key, NULL);
  2343. print_pubkey_BN(dsa, p, i);
  2344. print_pubkey_BN(dsa, q, i);
  2345. print_pubkey_BN(dsa, g, i);
  2346. print_pubkey_BN(dsa, pub_key, i);
  2347. }
  2348. #else
  2349. print_pubkey_BN(dsa, p, i);
  2350. print_pubkey_BN(dsa, q, i);
  2351. print_pubkey_BN(dsa, g, i);
  2352. print_pubkey_BN(dsa, pub_key, i);
  2353. #endif
  2354. #endif /* !OPENSSL_NO_DSA */
  2355. break;
  2356. }
  2357. case EVP_PKEY_DH:
  2358. {
  2359. DH *dh;
  2360. #ifdef HAVE_OPAQUE_EVP_PKEY
  2361. dh = EVP_PKEY_get0_DH(pubkey);
  2362. #else
  2363. dh = pubkey->pkey.dh;
  2364. #endif
  2365. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  2366. {
  2367. const BIGNUM *p;
  2368. const BIGNUM *q;
  2369. const BIGNUM *g;
  2370. const BIGNUM *pub_key;
  2371. DH_get0_pqg(dh, &p, &q, &g);
  2372. DH_get0_key(dh, &pub_key, NULL);
  2373. print_pubkey_BN(dh, p, i);
  2374. print_pubkey_BN(dh, q, i);
  2375. print_pubkey_BN(dh, g, i);
  2376. print_pubkey_BN(dh, pub_key, i);
  2377. }
  2378. #else
  2379. print_pubkey_BN(dh, p, i);
  2380. print_pubkey_BN(dh, g, i);
  2381. print_pubkey_BN(dh, pub_key, i);
  2382. #endif
  2383. break;
  2384. }
  2385. #if 0
  2386. case EVP_PKEY_EC: /* symbol not present in OpenSSL 0.9.6 */
  2387. /* left TODO */
  2388. break;
  2389. #endif
  2390. }
  2391. EVP_PKEY_free(pubkey);
  2392. }
  2393. if(psig) {
  2394. for(j = 0; j < psig->length; j++)
  2395. BIO_printf(mem, "%02x:", psig->data[j]);
  2396. push_certinfo("Signature", i);
  2397. }
  2398. PEM_write_bio_X509(mem, x);
  2399. push_certinfo("Cert", i);
  2400. }
  2401. BIO_free(mem);
  2402. return CURLE_OK;
  2403. }
  2404. /*
  2405. * Heavily modified from:
  2406. * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
  2407. */
  2408. static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
  2409. const char *pinnedpubkey)
  2410. {
  2411. /* Scratch */
  2412. int len1 = 0, len2 = 0;
  2413. unsigned char *buff1 = NULL, *temp = NULL;
  2414. /* Result is returned to caller */
  2415. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  2416. /* if a path wasn't specified, don't pin */
  2417. if(!pinnedpubkey)
  2418. return CURLE_OK;
  2419. if(!cert)
  2420. return result;
  2421. do {
  2422. /* Begin Gyrations to get the subjectPublicKeyInfo */
  2423. /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
  2424. /* https://groups.google.com/group/mailing.openssl.users/browse_thread
  2425. /thread/d61858dae102c6c7 */
  2426. len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
  2427. if(len1 < 1)
  2428. break; /* failed */
  2429. /* https://www.openssl.org/docs/crypto/buffer.html */
  2430. buff1 = temp = malloc(len1);
  2431. if(!buff1)
  2432. break; /* failed */
  2433. /* https://www.openssl.org/docs/crypto/d2i_X509.html */
  2434. len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
  2435. /*
  2436. * These checks are verifying we got back the same values as when we
  2437. * sized the buffer. It's pretty weak since they should always be the
  2438. * same. But it gives us something to test.
  2439. */
  2440. if((len1 != len2) || !temp || ((temp - buff1) != len1))
  2441. break; /* failed */
  2442. /* End Gyrations */
  2443. /* The one good exit point */
  2444. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  2445. } while(0);
  2446. /* https://www.openssl.org/docs/crypto/buffer.html */
  2447. if(buff1)
  2448. free(buff1);
  2449. return result;
  2450. }
  2451. /*
  2452. * Get the server cert, verify it and show it etc, only call failf() if the
  2453. * 'strict' argument is TRUE as otherwise all this is for informational
  2454. * purposes only!
  2455. *
  2456. * We check certificates to authenticate the server; otherwise we risk
  2457. * man-in-the-middle attack.
  2458. */
  2459. static CURLcode servercert(struct connectdata *conn,
  2460. struct ssl_connect_data *connssl,
  2461. bool strict)
  2462. {
  2463. CURLcode result = CURLE_OK;
  2464. int rc;
  2465. long lerr, len;
  2466. struct Curl_easy *data = conn->data;
  2467. X509 *issuer;
  2468. FILE *fp;
  2469. char *buffer = data->state.buffer;
  2470. const char *ptr;
  2471. long * const certverifyresult = SSL_IS_PROXY() ?
  2472. &data->set.proxy_ssl.certverifyresult : &data->set.ssl.certverifyresult;
  2473. BIO *mem = BIO_new(BIO_s_mem());
  2474. if(data->set.ssl.certinfo)
  2475. /* we've been asked to gather certificate info! */
  2476. (void)get_cert_chain(conn, connssl);
  2477. connssl->server_cert = SSL_get_peer_certificate(connssl->handle);
  2478. if(!connssl->server_cert) {
  2479. if(!strict)
  2480. return CURLE_OK;
  2481. failf(data, "SSL: couldn't get peer certificate!");
  2482. return CURLE_PEER_FAILED_VERIFICATION;
  2483. }
  2484. infof(data, "%s certificate:\n", SSL_IS_PROXY() ? "Proxy" : "Server");
  2485. rc = x509_name_oneline(X509_get_subject_name(connssl->server_cert),
  2486. buffer, BUFSIZE);
  2487. infof(data, " subject: %s\n", rc?"[NONE]":buffer);
  2488. ASN1_TIME_print(mem, X509_get0_notBefore(connssl->server_cert));
  2489. len = BIO_get_mem_data(mem, (char **) &ptr);
  2490. infof(data, " start date: %.*s\n", len, ptr);
  2491. rc = BIO_reset(mem);
  2492. ASN1_TIME_print(mem, X509_get0_notAfter(connssl->server_cert));
  2493. len = BIO_get_mem_data(mem, (char **) &ptr);
  2494. infof(data, " expire date: %.*s\n", len, ptr);
  2495. rc = BIO_reset(mem);
  2496. BIO_free(mem);
  2497. if(SSL_CONN_CONFIG(verifyhost)) {
  2498. result = verifyhost(conn, connssl->server_cert);
  2499. if(result) {
  2500. X509_free(connssl->server_cert);
  2501. connssl->server_cert = NULL;
  2502. return result;
  2503. }
  2504. }
  2505. rc = x509_name_oneline(X509_get_issuer_name(connssl->server_cert),
  2506. buffer, BUFSIZE);
  2507. if(rc) {
  2508. if(strict)
  2509. failf(data, "SSL: couldn't get X509-issuer name!");
  2510. result = CURLE_SSL_CONNECT_ERROR;
  2511. }
  2512. else {
  2513. infof(data, " issuer: %s\n", buffer);
  2514. /* We could do all sorts of certificate verification stuff here before
  2515. deallocating the certificate. */
  2516. /* e.g. match issuer name with provided issuer certificate */
  2517. if(SSL_SET_OPTION(issuercert)) {
  2518. fp = fopen(SSL_SET_OPTION(issuercert), FOPEN_READTEXT);
  2519. if(!fp) {
  2520. if(strict)
  2521. failf(data, "SSL: Unable to open issuer cert (%s)",
  2522. SSL_SET_OPTION(issuercert));
  2523. X509_free(connssl->server_cert);
  2524. connssl->server_cert = NULL;
  2525. return CURLE_SSL_ISSUER_ERROR;
  2526. }
  2527. issuer = PEM_read_X509(fp, NULL, ZERO_NULL, NULL);
  2528. if(!issuer) {
  2529. if(strict)
  2530. failf(data, "SSL: Unable to read issuer cert (%s)",
  2531. SSL_SET_OPTION(issuercert));
  2532. X509_free(connssl->server_cert);
  2533. X509_free(issuer);
  2534. fclose(fp);
  2535. return CURLE_SSL_ISSUER_ERROR;
  2536. }
  2537. fclose(fp);
  2538. if(X509_check_issued(issuer, connssl->server_cert) != X509_V_OK) {
  2539. if(strict)
  2540. failf(data, "SSL: Certificate issuer check failed (%s)",
  2541. SSL_SET_OPTION(issuercert));
  2542. X509_free(connssl->server_cert);
  2543. X509_free(issuer);
  2544. connssl->server_cert = NULL;
  2545. return CURLE_SSL_ISSUER_ERROR;
  2546. }
  2547. infof(data, " SSL certificate issuer check ok (%s)\n",
  2548. SSL_SET_OPTION(issuercert));
  2549. X509_free(issuer);
  2550. }
  2551. lerr = *certverifyresult = SSL_get_verify_result(connssl->handle);
  2552. if(*certverifyresult != X509_V_OK) {
  2553. if(SSL_CONN_CONFIG(verifypeer)) {
  2554. /* We probably never reach this, because SSL_connect() will fail
  2555. and we return earlier if verifypeer is set? */
  2556. if(strict)
  2557. failf(data, "SSL certificate verify result: %s (%ld)",
  2558. X509_verify_cert_error_string(lerr), lerr);
  2559. result = CURLE_PEER_FAILED_VERIFICATION;
  2560. }
  2561. else
  2562. infof(data, " SSL certificate verify result: %s (%ld),"
  2563. " continuing anyway.\n",
  2564. X509_verify_cert_error_string(lerr), lerr);
  2565. }
  2566. else
  2567. infof(data, " SSL certificate verify ok.\n");
  2568. }
  2569. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  2570. !defined(OPENSSL_NO_OCSP)
  2571. if(SSL_CONN_CONFIG(verifystatus)) {
  2572. result = verifystatus(conn, connssl);
  2573. if(result) {
  2574. X509_free(connssl->server_cert);
  2575. connssl->server_cert = NULL;
  2576. return result;
  2577. }
  2578. }
  2579. #endif
  2580. if(!strict)
  2581. /* when not strict, we don't bother about the verify cert problems */
  2582. result = CURLE_OK;
  2583. ptr = SSL_IS_PROXY() ? data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY] :
  2584. data->set.str[STRING_SSL_PINNEDPUBLICKEY_ORIG];
  2585. if(!result && ptr) {
  2586. result = pkp_pin_peer_pubkey(data, connssl->server_cert, ptr);
  2587. if(result)
  2588. failf(data, "SSL: public key does not match pinned public key!");
  2589. }
  2590. X509_free(connssl->server_cert);
  2591. connssl->server_cert = NULL;
  2592. connssl->connecting_state = ssl_connect_done;
  2593. return result;
  2594. }
  2595. static CURLcode ossl_connect_step3(struct connectdata *conn, int sockindex)
  2596. {
  2597. CURLcode result = CURLE_OK;
  2598. struct Curl_easy *data = conn->data;
  2599. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  2600. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  2601. if(SSL_SET_OPTION(primary.sessionid)) {
  2602. bool incache;
  2603. SSL_SESSION *our_ssl_sessionid;
  2604. void *old_ssl_sessionid = NULL;
  2605. our_ssl_sessionid = SSL_get1_session(connssl->handle);
  2606. /* SSL_get1_session() will increment the reference count and the session
  2607. will stay in memory until explicitly freed with SSL_SESSION_free(3),
  2608. regardless of its state. */
  2609. Curl_ssl_sessionid_lock(conn);
  2610. incache = !(Curl_ssl_getsessionid(conn, &old_ssl_sessionid, NULL,
  2611. sockindex));
  2612. if(incache) {
  2613. if(old_ssl_sessionid != our_ssl_sessionid) {
  2614. infof(data, "old SSL session ID is stale, removing\n");
  2615. Curl_ssl_delsessionid(conn, old_ssl_sessionid);
  2616. incache = FALSE;
  2617. }
  2618. }
  2619. if(!incache) {
  2620. result = Curl_ssl_addsessionid(conn, our_ssl_sessionid,
  2621. 0 /* unknown size */, sockindex);
  2622. if(result) {
  2623. Curl_ssl_sessionid_unlock(conn);
  2624. failf(data, "failed to store ssl session");
  2625. return result;
  2626. }
  2627. }
  2628. else {
  2629. /* Session was incache, so refcount already incremented earlier.
  2630. * Avoid further increments with each SSL_get1_session() call.
  2631. * This does not free the session as refcount remains > 0
  2632. */
  2633. SSL_SESSION_free(our_ssl_sessionid);
  2634. }
  2635. Curl_ssl_sessionid_unlock(conn);
  2636. }
  2637. /*
  2638. * We check certificates to authenticate the server; otherwise we risk
  2639. * man-in-the-middle attack; NEVERTHELESS, if we're told explicitly not to
  2640. * verify the peer ignore faults and failures from the server cert
  2641. * operations.
  2642. */
  2643. result = servercert(conn, connssl, (SSL_CONN_CONFIG(verifypeer) ||
  2644. SSL_CONN_CONFIG(verifyhost)));
  2645. if(!result)
  2646. connssl->connecting_state = ssl_connect_done;
  2647. return result;
  2648. }
  2649. static Curl_recv ossl_recv;
  2650. static Curl_send ossl_send;
  2651. static CURLcode ossl_connect_common(struct connectdata *conn,
  2652. int sockindex,
  2653. bool nonblocking,
  2654. bool *done)
  2655. {
  2656. CURLcode result;
  2657. struct Curl_easy *data = conn->data;
  2658. struct ssl_connect_data *connssl = &conn->ssl[sockindex];
  2659. curl_socket_t sockfd = conn->sock[sockindex];
  2660. time_t timeout_ms;
  2661. int what;
  2662. /* check if the connection has already been established */
  2663. if(ssl_connection_complete == connssl->state) {
  2664. *done = TRUE;
  2665. return CURLE_OK;
  2666. }
  2667. if(ssl_connect_1 == connssl->connecting_state) {
  2668. /* Find out how much more time we're allowed */
  2669. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  2670. if(timeout_ms < 0) {
  2671. /* no need to continue if time already is up */
  2672. failf(data, "SSL connection timeout");
  2673. return CURLE_OPERATION_TIMEDOUT;
  2674. }
  2675. result = ossl_connect_step1(conn, sockindex);
  2676. if(result)
  2677. return result;
  2678. }
  2679. while(ssl_connect_2 == connssl->connecting_state ||
  2680. ssl_connect_2_reading == connssl->connecting_state ||
  2681. ssl_connect_2_writing == connssl->connecting_state) {
  2682. /* check allowed time left */
  2683. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  2684. if(timeout_ms < 0) {
  2685. /* no need to continue if time already is up */
  2686. failf(data, "SSL connection timeout");
  2687. return CURLE_OPERATION_TIMEDOUT;
  2688. }
  2689. /* if ssl is expecting something, check if it's available. */
  2690. if(connssl->connecting_state == ssl_connect_2_reading ||
  2691. connssl->connecting_state == ssl_connect_2_writing) {
  2692. curl_socket_t writefd = ssl_connect_2_writing==
  2693. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  2694. curl_socket_t readfd = ssl_connect_2_reading==
  2695. connssl->connecting_state?sockfd:CURL_SOCKET_BAD;
  2696. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  2697. nonblocking?0:timeout_ms);
  2698. if(what < 0) {
  2699. /* fatal error */
  2700. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  2701. return CURLE_SSL_CONNECT_ERROR;
  2702. }
  2703. if(0 == what) {
  2704. if(nonblocking) {
  2705. *done = FALSE;
  2706. return CURLE_OK;
  2707. }
  2708. /* timeout */
  2709. failf(data, "SSL connection timeout");
  2710. return CURLE_OPERATION_TIMEDOUT;
  2711. }
  2712. /* socket is readable or writable */
  2713. }
  2714. /* Run transaction, and return to the caller if it failed or if this
  2715. * connection is done nonblocking and this loop would execute again. This
  2716. * permits the owner of a multi handle to abort a connection attempt
  2717. * before step2 has completed while ensuring that a client using select()
  2718. * or epoll() will always have a valid fdset to wait on.
  2719. */
  2720. result = ossl_connect_step2(conn, sockindex);
  2721. if(result || (nonblocking &&
  2722. (ssl_connect_2 == connssl->connecting_state ||
  2723. ssl_connect_2_reading == connssl->connecting_state ||
  2724. ssl_connect_2_writing == connssl->connecting_state)))
  2725. return result;
  2726. } /* repeat step2 until all transactions are done. */
  2727. if(ssl_connect_3 == connssl->connecting_state) {
  2728. result = ossl_connect_step3(conn, sockindex);
  2729. if(result)
  2730. return result;
  2731. }
  2732. if(ssl_connect_done == connssl->connecting_state) {
  2733. connssl->state = ssl_connection_complete;
  2734. conn->recv[sockindex] = ossl_recv;
  2735. conn->send[sockindex] = ossl_send;
  2736. *done = TRUE;
  2737. }
  2738. else
  2739. *done = FALSE;
  2740. /* Reset our connect state machine */
  2741. connssl->connecting_state = ssl_connect_1;
  2742. return CURLE_OK;
  2743. }
  2744. CURLcode Curl_ossl_connect_nonblocking(struct connectdata *conn,
  2745. int sockindex,
  2746. bool *done)
  2747. {
  2748. return ossl_connect_common(conn, sockindex, TRUE, done);
  2749. }
  2750. CURLcode Curl_ossl_connect(struct connectdata *conn, int sockindex)
  2751. {
  2752. CURLcode result;
  2753. bool done = FALSE;
  2754. result = ossl_connect_common(conn, sockindex, FALSE, &done);
  2755. if(result)
  2756. return result;
  2757. DEBUGASSERT(done);
  2758. return CURLE_OK;
  2759. }
  2760. bool Curl_ossl_data_pending(const struct connectdata *conn, int connindex)
  2761. {
  2762. if(conn->ssl[connindex].handle)
  2763. /* SSL is in use */
  2764. return (0 != SSL_pending(conn->ssl[connindex].handle) ||
  2765. (conn->proxy_ssl[connindex].handle &&
  2766. 0 != SSL_pending(conn->proxy_ssl[connindex].handle))) ?
  2767. TRUE : FALSE;
  2768. return FALSE;
  2769. }
  2770. static ssize_t ossl_send(struct connectdata *conn,
  2771. int sockindex,
  2772. const void *mem,
  2773. size_t len,
  2774. CURLcode *curlcode)
  2775. {
  2776. /* SSL_write() is said to return 'int' while write() and send() returns
  2777. 'size_t' */
  2778. int err;
  2779. char error_buffer[256];
  2780. unsigned long sslerror;
  2781. int memlen;
  2782. int rc;
  2783. ERR_clear_error();
  2784. memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  2785. rc = SSL_write(conn->ssl[sockindex].handle, mem, memlen);
  2786. if(rc <= 0) {
  2787. err = SSL_get_error(conn->ssl[sockindex].handle, rc);
  2788. switch(err) {
  2789. case SSL_ERROR_WANT_READ:
  2790. case SSL_ERROR_WANT_WRITE:
  2791. /* The operation did not complete; the same TLS/SSL I/O function
  2792. should be called again later. This is basically an EWOULDBLOCK
  2793. equivalent. */
  2794. *curlcode = CURLE_AGAIN;
  2795. return -1;
  2796. case SSL_ERROR_SYSCALL:
  2797. failf(conn->data, "SSL_write() returned SYSCALL, errno = %d",
  2798. SOCKERRNO);
  2799. *curlcode = CURLE_SEND_ERROR;
  2800. return -1;
  2801. case SSL_ERROR_SSL:
  2802. /* A failure in the SSL library occurred, usually a protocol error.
  2803. The OpenSSL error queue contains more information on the error. */
  2804. sslerror = ERR_get_error();
  2805. if(ERR_GET_LIB(sslerror) == ERR_LIB_SSL &&
  2806. ERR_GET_REASON(sslerror) == SSL_R_BIO_NOT_SET &&
  2807. conn->ssl[sockindex].state == ssl_connection_complete &&
  2808. conn->proxy_ssl[sockindex].state == ssl_connection_complete) {
  2809. char ver[120];
  2810. Curl_ossl_version(ver, 120);
  2811. failf(conn->data, "Error: %s does not support double SSL tunneling.",
  2812. ver);
  2813. }
  2814. else
  2815. failf(conn->data, "SSL_write() error: %s",
  2816. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  2817. *curlcode = CURLE_SEND_ERROR;
  2818. return -1;
  2819. }
  2820. /* a true error */
  2821. failf(conn->data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  2822. SSL_ERROR_to_str(err), SOCKERRNO);
  2823. *curlcode = CURLE_SEND_ERROR;
  2824. return -1;
  2825. }
  2826. *curlcode = CURLE_OK;
  2827. return (ssize_t)rc; /* number of bytes */
  2828. }
  2829. static ssize_t ossl_recv(struct connectdata *conn, /* connection data */
  2830. int num, /* socketindex */
  2831. char *buf, /* store read data here */
  2832. size_t buffersize, /* max amount to read */
  2833. CURLcode *curlcode)
  2834. {
  2835. char error_buffer[256];
  2836. unsigned long sslerror;
  2837. ssize_t nread;
  2838. int buffsize;
  2839. ERR_clear_error();
  2840. buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
  2841. nread = (ssize_t)SSL_read(conn->ssl[num].handle, buf, buffsize);
  2842. if(nread <= 0) {
  2843. /* failed SSL_read */
  2844. int err = SSL_get_error(conn->ssl[num].handle, (int)nread);
  2845. switch(err) {
  2846. case SSL_ERROR_NONE: /* this is not an error */
  2847. case SSL_ERROR_ZERO_RETURN: /* no more data */
  2848. break;
  2849. case SSL_ERROR_WANT_READ:
  2850. case SSL_ERROR_WANT_WRITE:
  2851. /* there's data pending, re-invoke SSL_read() */
  2852. *curlcode = CURLE_AGAIN;
  2853. return -1;
  2854. default:
  2855. /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
  2856. value/errno" */
  2857. /* https://www.openssl.org/docs/crypto/ERR_get_error.html */
  2858. sslerror = ERR_get_error();
  2859. if((nread < 0) || sslerror) {
  2860. /* If the return code was negative or there actually is an error in the
  2861. queue */
  2862. failf(conn->data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  2863. (sslerror ?
  2864. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)) :
  2865. SSL_ERROR_to_str(err)),
  2866. SOCKERRNO);
  2867. *curlcode = CURLE_RECV_ERROR;
  2868. return -1;
  2869. }
  2870. }
  2871. }
  2872. return nread;
  2873. }
  2874. size_t Curl_ossl_version(char *buffer, size_t size)
  2875. {
  2876. #ifdef OPENSSL_IS_BORINGSSL
  2877. return snprintf(buffer, size, OSSL_PACKAGE);
  2878. #else /* OPENSSL_IS_BORINGSSL */
  2879. char sub[3];
  2880. unsigned long ssleay_value;
  2881. sub[2]='\0';
  2882. sub[1]='\0';
  2883. ssleay_value=OpenSSL_version_num();
  2884. if(ssleay_value < 0x906000) {
  2885. ssleay_value=SSLEAY_VERSION_NUMBER;
  2886. sub[0]='\0';
  2887. }
  2888. else {
  2889. if(ssleay_value&0xff0) {
  2890. int minor_ver = (ssleay_value >> 4) & 0xff;
  2891. if(minor_ver > 26) {
  2892. /* handle extended version introduced for 0.9.8za */
  2893. sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
  2894. sub[0] = 'z';
  2895. }
  2896. else {
  2897. sub[0] = (char) (minor_ver + 'a' - 1);
  2898. }
  2899. }
  2900. else
  2901. sub[0]='\0';
  2902. }
  2903. return snprintf(buffer, size, "%s/%lx.%lx.%lx%s",
  2904. OSSL_PACKAGE,
  2905. (ssleay_value>>28)&0xf,
  2906. (ssleay_value>>20)&0xff,
  2907. (ssleay_value>>12)&0xff,
  2908. sub);
  2909. #endif /* OPENSSL_IS_BORINGSSL */
  2910. }
  2911. /* can be called with data == NULL */
  2912. CURLcode Curl_ossl_random(struct Curl_easy *data, unsigned char *entropy,
  2913. size_t length)
  2914. {
  2915. int rc;
  2916. if(data) {
  2917. if(Curl_ossl_seed(data)) /* Initiate the seed if not already done */
  2918. return CURLE_FAILED_INIT; /* couldn't seed for some reason */
  2919. }
  2920. else {
  2921. if(!rand_enough())
  2922. return CURLE_FAILED_INIT;
  2923. }
  2924. /* RAND_bytes() returns 1 on success, 0 otherwise. */
  2925. rc = RAND_bytes(entropy, curlx_uztosi(length));
  2926. return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
  2927. }
  2928. void Curl_ossl_md5sum(unsigned char *tmp, /* input */
  2929. size_t tmplen,
  2930. unsigned char *md5sum /* output */,
  2931. size_t unused)
  2932. {
  2933. MD5_CTX MD5pw;
  2934. (void)unused;
  2935. MD5_Init(&MD5pw);
  2936. MD5_Update(&MD5pw, tmp, tmplen);
  2937. MD5_Final(md5sum, &MD5pw);
  2938. }
  2939. #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
  2940. void Curl_ossl_sha256sum(const unsigned char *tmp, /* input */
  2941. size_t tmplen,
  2942. unsigned char *sha256sum /* output */,
  2943. size_t unused)
  2944. {
  2945. SHA256_CTX SHA256pw;
  2946. (void)unused;
  2947. SHA256_Init(&SHA256pw);
  2948. SHA256_Update(&SHA256pw, tmp, tmplen);
  2949. SHA256_Final(sha256sum, &SHA256pw);
  2950. }
  2951. #endif
  2952. bool Curl_ossl_cert_status_request(void)
  2953. {
  2954. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  2955. !defined(OPENSSL_NO_OCSP)
  2956. return TRUE;
  2957. #else
  2958. return FALSE;
  2959. #endif
  2960. }
  2961. #endif /* USE_OPENSSL */