openssl.c 154 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, 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.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. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. /*
  25. * Source file for all OpenSSL-specific code for the TLS/SSL layer. No code
  26. * but vtls.c should ever call or use these functions.
  27. */
  28. #include "curl_setup.h"
  29. #if defined(USE_QUICHE) || defined(USE_OPENSSL)
  30. #include <limits.h>
  31. /* Wincrypt must be included before anything that could include OpenSSL. */
  32. #if defined(USE_WIN32_CRYPTO)
  33. #include <wincrypt.h>
  34. /* Undefine wincrypt conflicting symbols for BoringSSL. */
  35. #undef X509_NAME
  36. #undef X509_EXTENSIONS
  37. #undef PKCS7_ISSUER_AND_SERIAL
  38. #undef PKCS7_SIGNER_INFO
  39. #undef OCSP_REQUEST
  40. #undef OCSP_RESPONSE
  41. #endif
  42. #include "urldata.h"
  43. #include "sendf.h"
  44. #include "formdata.h" /* for the boundary function */
  45. #include "url.h" /* for the ssl config check function */
  46. #include "inet_pton.h"
  47. #include "openssl.h"
  48. #include "connect.h"
  49. #include "slist.h"
  50. #include "select.h"
  51. #include "vtls.h"
  52. #include "vtls_int.h"
  53. #include "vauth/vauth.h"
  54. #include "keylog.h"
  55. #include "strcase.h"
  56. #include "hostcheck.h"
  57. #include "multiif.h"
  58. #include "strerror.h"
  59. #include "curl_printf.h"
  60. #include <openssl/ssl.h>
  61. #include <openssl/rand.h>
  62. #include <openssl/x509v3.h>
  63. #ifndef OPENSSL_NO_DSA
  64. #include <openssl/dsa.h>
  65. #endif
  66. #include <openssl/dh.h>
  67. #include <openssl/err.h>
  68. #include <openssl/md5.h>
  69. #include <openssl/conf.h>
  70. #include <openssl/bn.h>
  71. #include <openssl/rsa.h>
  72. #include <openssl/bio.h>
  73. #include <openssl/buffer.h>
  74. #include <openssl/pkcs12.h>
  75. #include <openssl/tls1.h>
  76. #include <openssl/evp.h>
  77. #ifdef USE_ECH
  78. # ifndef OPENSSL_IS_BORINGSSL
  79. # include <openssl/ech.h>
  80. # endif
  81. # include "curl_base64.h"
  82. # define ECH_ENABLED(__data__) \
  83. (__data__->set.tls_ech && \
  84. !(__data__->set.tls_ech & CURLECH_DISABLE)\
  85. )
  86. #endif /* USE_ECH */
  87. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_OCSP)
  88. #include <openssl/ocsp.h>
  89. #endif
  90. #if (OPENSSL_VERSION_NUMBER >= 0x0090700fL) && /* 0.9.7 or later */ \
  91. !defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_UI_CONSOLE)
  92. #define USE_OPENSSL_ENGINE
  93. #include <openssl/engine.h>
  94. #endif
  95. #include "warnless.h"
  96. /* The last #include files should be: */
  97. #include "curl_memory.h"
  98. #include "memdebug.h"
  99. #ifndef ARRAYSIZE
  100. #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0]))
  101. #endif
  102. /* Uncomment the ALLOW_RENEG line to a real #define if you want to allow TLS
  103. renegotiations when built with BoringSSL. Renegotiating is non-compliant
  104. with HTTP/2 and "an extremely dangerous protocol feature". Beware.
  105. #define ALLOW_RENEG 1
  106. */
  107. #ifndef OPENSSL_VERSION_NUMBER
  108. #error "OPENSSL_VERSION_NUMBER not defined"
  109. #endif
  110. #ifdef USE_OPENSSL_ENGINE
  111. #include <openssl/ui.h>
  112. #endif
  113. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  114. #define SSL_METHOD_QUAL const
  115. #else
  116. #define SSL_METHOD_QUAL
  117. #endif
  118. #if (OPENSSL_VERSION_NUMBER >= 0x10000000L)
  119. #define HAVE_ERR_REMOVE_THREAD_STATE 1
  120. #endif
  121. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && /* OpenSSL 1.1.0+ */ \
  122. !(defined(LIBRESSL_VERSION_NUMBER) && \
  123. LIBRESSL_VERSION_NUMBER < 0x20700000L)
  124. #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
  125. #define HAVE_X509_GET0_EXTENSIONS 1 /* added in 1.1.0 -pre1 */
  126. #define HAVE_OPAQUE_EVP_PKEY 1 /* since 1.1.0 -pre3 */
  127. #define HAVE_OPAQUE_RSA_DSA_DH 1 /* since 1.1.0 -pre5 */
  128. #define CONST_EXTS const
  129. #define HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED 1
  130. /* funny typecast define due to difference in API */
  131. #ifdef LIBRESSL_VERSION_NUMBER
  132. #define ARG2_X509_signature_print (X509_ALGOR *)
  133. #else
  134. #define ARG2_X509_signature_print
  135. #endif
  136. #else
  137. /* For OpenSSL before 1.1.0 */
  138. #define ASN1_STRING_get0_data(x) ASN1_STRING_data(x)
  139. #define X509_get0_notBefore(x) X509_get_notBefore(x)
  140. #define X509_get0_notAfter(x) X509_get_notAfter(x)
  141. #define CONST_EXTS /* nope */
  142. #ifndef LIBRESSL_VERSION_NUMBER
  143. #define OpenSSL_version_num() SSLeay()
  144. #endif
  145. #endif
  146. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* 1.0.2 or later */ \
  147. !(defined(LIBRESSL_VERSION_NUMBER) && \
  148. LIBRESSL_VERSION_NUMBER < 0x20700000L)
  149. #define HAVE_X509_GET0_SIGNATURE 1
  150. #endif
  151. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) /* 1.0.2 or later */
  152. #define HAVE_SSL_GET_SHUTDOWN 1
  153. #endif
  154. #if OPENSSL_VERSION_NUMBER >= 0x10002003L && \
  155. OPENSSL_VERSION_NUMBER <= 0x10002FFFL && \
  156. !defined(OPENSSL_NO_COMP)
  157. #define HAVE_SSL_COMP_FREE_COMPRESSION_METHODS 1
  158. #endif
  159. #if (OPENSSL_VERSION_NUMBER < 0x0090808fL)
  160. /* not present in older OpenSSL */
  161. #define OPENSSL_load_builtin_modules(x)
  162. #endif
  163. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  164. #define HAVE_EVP_PKEY_GET_PARAMS 1
  165. #endif
  166. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  167. #include <openssl/core_names.h>
  168. #define DECLARE_PKEY_PARAM_BIGNUM(name) BIGNUM *name = NULL
  169. #define FREE_PKEY_PARAM_BIGNUM(name) BN_clear_free(name)
  170. #else
  171. #define DECLARE_PKEY_PARAM_BIGNUM(name) const BIGNUM *name
  172. #define FREE_PKEY_PARAM_BIGNUM(name)
  173. #endif
  174. /*
  175. * Whether SSL_CTX_set_keylog_callback is available.
  176. * OpenSSL: supported since 1.1.1 https://github.com/openssl/openssl/pull/2287
  177. * BoringSSL: supported since d28f59c27bac (committed 2015-11-19)
  178. * LibreSSL: not supported. 3.5.0+ has a stub function that does nothing.
  179. */
  180. #if (OPENSSL_VERSION_NUMBER >= 0x10101000L && \
  181. !defined(LIBRESSL_VERSION_NUMBER)) || \
  182. defined(OPENSSL_IS_BORINGSSL)
  183. #define HAVE_KEYLOG_CALLBACK
  184. #endif
  185. /* Whether SSL_CTX_set_ciphersuites is available.
  186. * OpenSSL: supported since 1.1.1 (commit a53b5be6a05)
  187. * BoringSSL: no
  188. * LibreSSL: supported since 3.4.1 (released 2021-10-14)
  189. */
  190. #if ((OPENSSL_VERSION_NUMBER >= 0x10101000L && \
  191. !defined(LIBRESSL_VERSION_NUMBER)) || \
  192. (defined(LIBRESSL_VERSION_NUMBER) && \
  193. LIBRESSL_VERSION_NUMBER >= 0x3040100fL)) && \
  194. !defined(OPENSSL_IS_BORINGSSL)
  195. #define HAVE_SSL_CTX_SET_CIPHERSUITES
  196. #if !defined(OPENSSL_IS_AWSLC)
  197. #define HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  198. #endif
  199. #endif
  200. /*
  201. * Whether SSL_CTX_set1_curves_list is available.
  202. * OpenSSL: supported since 1.0.2, see
  203. * https://docs.openssl.org/master/man3/SSL_CTX_set1_curves/
  204. * BoringSSL: supported since 5fd1807d95f7 (committed 2016-09-30)
  205. * LibreSSL: since 2.5.3 (April 12, 2017)
  206. */
  207. #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) || \
  208. defined(OPENSSL_IS_BORINGSSL)
  209. #define HAVE_SSL_CTX_SET_EC_CURVES
  210. #endif
  211. #if defined(LIBRESSL_VERSION_NUMBER)
  212. #define OSSL_PACKAGE "LibreSSL"
  213. #elif defined(OPENSSL_IS_BORINGSSL)
  214. #define OSSL_PACKAGE "BoringSSL"
  215. #elif defined(OPENSSL_IS_AWSLC)
  216. #define OSSL_PACKAGE "AWS-LC"
  217. #else
  218. # if defined(USE_NGTCP2) && defined(USE_NGHTTP3)
  219. # define OSSL_PACKAGE "quictls"
  220. # else
  221. # define OSSL_PACKAGE "OpenSSL"
  222. #endif
  223. #endif
  224. #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
  225. typedef size_t numcert_t;
  226. #else
  227. typedef int numcert_t;
  228. #endif
  229. #define ossl_valsize_t numcert_t
  230. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  231. /* up2date versions of OpenSSL maintain reasonably secure defaults without
  232. * breaking compatibility, so it is better not to override the defaults in curl
  233. */
  234. #define DEFAULT_CIPHER_SELECTION NULL
  235. #else
  236. /* not the case with old versions of OpenSSL */
  237. #define DEFAULT_CIPHER_SELECTION \
  238. "ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH"
  239. #endif
  240. #ifdef HAVE_OPENSSL_SRP
  241. /* the function exists */
  242. #ifdef USE_TLS_SRP
  243. /* the functionality is not disabled */
  244. #define USE_OPENSSL_SRP
  245. #endif
  246. #endif
  247. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  248. #define HAVE_RANDOM_INIT_BY_DEFAULT 1
  249. #endif
  250. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  251. !(defined(LIBRESSL_VERSION_NUMBER) && \
  252. LIBRESSL_VERSION_NUMBER < 0x2070100fL) && \
  253. !defined(OPENSSL_IS_BORINGSSL) && \
  254. !defined(OPENSSL_IS_AWSLC)
  255. #define HAVE_OPENSSL_VERSION
  256. #endif
  257. #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
  258. typedef uint32_t sslerr_t;
  259. #else
  260. typedef unsigned long sslerr_t;
  261. #endif
  262. /*
  263. * Whether the OpenSSL version has the API needed to support sharing an
  264. * X509_STORE between connections. The API is:
  265. * * `X509_STORE_up_ref` -- Introduced: OpenSSL 1.1.0.
  266. */
  267. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* OpenSSL >= 1.1.0 */
  268. #define HAVE_SSL_X509_STORE_SHARE
  269. #endif
  270. /* What API version do we use? */
  271. #if defined(LIBRESSL_VERSION_NUMBER)
  272. #define USE_PRE_1_1_API (LIBRESSL_VERSION_NUMBER < 0x2070000f)
  273. #else /* !LIBRESSL_VERSION_NUMBER */
  274. #define USE_PRE_1_1_API (OPENSSL_VERSION_NUMBER < 0x10100000L)
  275. #endif /* !LIBRESSL_VERSION_NUMBER */
  276. #define push_certinfo(_label, _num) \
  277. do { \
  278. long info_len = BIO_get_mem_data(mem, &ptr); \
  279. Curl_ssl_push_certinfo_len(data, _num, _label, ptr, info_len); \
  280. if(1 != BIO_reset(mem)) \
  281. break; \
  282. } while(0)
  283. static void pubkey_show(struct Curl_easy *data,
  284. BIO *mem,
  285. int num,
  286. const char *type,
  287. const char *name,
  288. const BIGNUM *bn)
  289. {
  290. char *ptr;
  291. char namebuf[32];
  292. msnprintf(namebuf, sizeof(namebuf), "%s(%s)", type, name);
  293. if(bn)
  294. BN_print(mem, bn);
  295. push_certinfo(namebuf, num);
  296. }
  297. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  298. #define print_pubkey_BN(_type, _name, _num) \
  299. pubkey_show(data, mem, _num, #_type, #_name, _name)
  300. #else
  301. #define print_pubkey_BN(_type, _name, _num) \
  302. do { \
  303. if(_type->_name) { \
  304. pubkey_show(data, mem, _num, #_type, #_name, _type->_name); \
  305. } \
  306. } while(0)
  307. #endif
  308. static int asn1_object_dump(ASN1_OBJECT *a, char *buf, size_t len)
  309. {
  310. int i, ilen;
  311. ilen = (int)len;
  312. if(ilen < 0)
  313. return 1; /* buffer too big */
  314. i = i2t_ASN1_OBJECT(buf, ilen, a);
  315. if(i >= ilen)
  316. return 1; /* buffer too small */
  317. return 0;
  318. }
  319. static void X509V3_ext(struct Curl_easy *data,
  320. int certnum,
  321. CONST_EXTS STACK_OF(X509_EXTENSION) *exts)
  322. {
  323. int i;
  324. if((int)sk_X509_EXTENSION_num(exts) <= 0)
  325. /* no extensions, bail out */
  326. return;
  327. for(i = 0; i < (int)sk_X509_EXTENSION_num(exts); i++) {
  328. ASN1_OBJECT *obj;
  329. X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, (ossl_valsize_t)i);
  330. BUF_MEM *biomem;
  331. char namebuf[128];
  332. BIO *bio_out = BIO_new(BIO_s_mem());
  333. if(!bio_out)
  334. return;
  335. obj = X509_EXTENSION_get_object(ext);
  336. asn1_object_dump(obj, namebuf, sizeof(namebuf));
  337. if(!X509V3_EXT_print(bio_out, ext, 0, 0))
  338. ASN1_STRING_print(bio_out, (ASN1_STRING *)X509_EXTENSION_get_data(ext));
  339. BIO_get_mem_ptr(bio_out, &biomem);
  340. Curl_ssl_push_certinfo_len(data, certnum, namebuf, biomem->data,
  341. biomem->length);
  342. BIO_free(bio_out);
  343. }
  344. }
  345. CURLcode Curl_ossl_certchain(struct Curl_easy *data, SSL *ssl)
  346. {
  347. CURLcode result;
  348. STACK_OF(X509) *sk;
  349. int i;
  350. numcert_t numcerts;
  351. BIO *mem;
  352. DEBUGASSERT(ssl);
  353. sk = SSL_get_peer_cert_chain(ssl);
  354. if(!sk) {
  355. return CURLE_OUT_OF_MEMORY;
  356. }
  357. numcerts = sk_X509_num(sk);
  358. result = Curl_ssl_init_certinfo(data, (int)numcerts);
  359. if(result) {
  360. return result;
  361. }
  362. mem = BIO_new(BIO_s_mem());
  363. if(!mem) {
  364. return CURLE_OUT_OF_MEMORY;
  365. }
  366. for(i = 0; i < (int)numcerts; i++) {
  367. ASN1_INTEGER *num;
  368. X509 *x = sk_X509_value(sk, (ossl_valsize_t)i);
  369. EVP_PKEY *pubkey = NULL;
  370. int j;
  371. char *ptr;
  372. const ASN1_BIT_STRING *psig = NULL;
  373. X509_NAME_print_ex(mem, X509_get_subject_name(x), 0, XN_FLAG_ONELINE);
  374. push_certinfo("Subject", i);
  375. X509_NAME_print_ex(mem, X509_get_issuer_name(x), 0, XN_FLAG_ONELINE);
  376. push_certinfo("Issuer", i);
  377. BIO_printf(mem, "%lx", X509_get_version(x));
  378. push_certinfo("Version", i);
  379. num = X509_get_serialNumber(x);
  380. if(num->type == V_ASN1_NEG_INTEGER)
  381. BIO_puts(mem, "-");
  382. for(j = 0; j < num->length; j++)
  383. BIO_printf(mem, "%02x", num->data[j]);
  384. push_certinfo("Serial Number", i);
  385. #if defined(HAVE_X509_GET0_SIGNATURE) && defined(HAVE_X509_GET0_EXTENSIONS)
  386. {
  387. const X509_ALGOR *sigalg = NULL;
  388. X509_PUBKEY *xpubkey = NULL;
  389. ASN1_OBJECT *pubkeyoid = NULL;
  390. X509_get0_signature(&psig, &sigalg, x);
  391. if(sigalg) {
  392. const ASN1_OBJECT *sigalgoid = NULL;
  393. X509_ALGOR_get0(&sigalgoid, NULL, NULL, sigalg);
  394. i2a_ASN1_OBJECT(mem, sigalgoid);
  395. push_certinfo("Signature Algorithm", i);
  396. }
  397. xpubkey = X509_get_X509_PUBKEY(x);
  398. if(xpubkey) {
  399. X509_PUBKEY_get0_param(&pubkeyoid, NULL, NULL, NULL, xpubkey);
  400. if(pubkeyoid) {
  401. i2a_ASN1_OBJECT(mem, pubkeyoid);
  402. push_certinfo("Public Key Algorithm", i);
  403. }
  404. }
  405. X509V3_ext(data, i, X509_get0_extensions(x));
  406. }
  407. #else
  408. {
  409. /* before OpenSSL 1.0.2 */
  410. X509_CINF *cinf = x->cert_info;
  411. i2a_ASN1_OBJECT(mem, cinf->signature->algorithm);
  412. push_certinfo("Signature Algorithm", i);
  413. i2a_ASN1_OBJECT(mem, cinf->key->algor->algorithm);
  414. push_certinfo("Public Key Algorithm", i);
  415. X509V3_ext(data, i, cinf->extensions);
  416. psig = x->signature;
  417. }
  418. #endif
  419. ASN1_TIME_print(mem, X509_get0_notBefore(x));
  420. push_certinfo("Start date", i);
  421. ASN1_TIME_print(mem, X509_get0_notAfter(x));
  422. push_certinfo("Expire date", i);
  423. pubkey = X509_get_pubkey(x);
  424. if(!pubkey)
  425. infof(data, " Unable to load public key");
  426. else {
  427. int pktype;
  428. #ifdef HAVE_OPAQUE_EVP_PKEY
  429. pktype = EVP_PKEY_id(pubkey);
  430. #else
  431. pktype = pubkey->type;
  432. #endif
  433. switch(pktype) {
  434. case EVP_PKEY_RSA:
  435. {
  436. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  437. RSA *rsa;
  438. #ifdef HAVE_OPAQUE_EVP_PKEY
  439. rsa = EVP_PKEY_get0_RSA(pubkey);
  440. #else
  441. rsa = pubkey->pkey.rsa;
  442. #endif /* HAVE_OPAQUE_EVP_PKEY */
  443. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  444. {
  445. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  446. DECLARE_PKEY_PARAM_BIGNUM(n);
  447. DECLARE_PKEY_PARAM_BIGNUM(e);
  448. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  449. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_N, &n);
  450. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_RSA_E, &e);
  451. #else
  452. RSA_get0_key(rsa, &n, &e, NULL);
  453. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  454. BIO_printf(mem, "%d", n ? BN_num_bits(n) : 0);
  455. #else
  456. BIO_printf(mem, "%d", rsa->n ? BN_num_bits(rsa->n) : 0);
  457. #endif /* HAVE_OPAQUE_RSA_DSA_DH */
  458. push_certinfo("RSA Public Key", i);
  459. print_pubkey_BN(rsa, n, i);
  460. print_pubkey_BN(rsa, e, i);
  461. FREE_PKEY_PARAM_BIGNUM(n);
  462. FREE_PKEY_PARAM_BIGNUM(e);
  463. }
  464. break;
  465. }
  466. case EVP_PKEY_DSA:
  467. {
  468. #ifndef OPENSSL_NO_DSA
  469. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  470. DSA *dsa;
  471. #ifdef HAVE_OPAQUE_EVP_PKEY
  472. dsa = EVP_PKEY_get0_DSA(pubkey);
  473. #else
  474. dsa = pubkey->pkey.dsa;
  475. #endif /* HAVE_OPAQUE_EVP_PKEY */
  476. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  477. {
  478. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  479. DECLARE_PKEY_PARAM_BIGNUM(p);
  480. DECLARE_PKEY_PARAM_BIGNUM(q);
  481. DECLARE_PKEY_PARAM_BIGNUM(g);
  482. DECLARE_PKEY_PARAM_BIGNUM(pub_key);
  483. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  484. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
  485. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
  486. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
  487. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
  488. #else
  489. DSA_get0_pqg(dsa, &p, &q, &g);
  490. DSA_get0_key(dsa, &pub_key, NULL);
  491. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  492. #endif /* HAVE_OPAQUE_RSA_DSA_DH */
  493. print_pubkey_BN(dsa, p, i);
  494. print_pubkey_BN(dsa, q, i);
  495. print_pubkey_BN(dsa, g, i);
  496. print_pubkey_BN(dsa, pub_key, i);
  497. FREE_PKEY_PARAM_BIGNUM(p);
  498. FREE_PKEY_PARAM_BIGNUM(q);
  499. FREE_PKEY_PARAM_BIGNUM(g);
  500. FREE_PKEY_PARAM_BIGNUM(pub_key);
  501. }
  502. #endif /* !OPENSSL_NO_DSA */
  503. break;
  504. }
  505. case EVP_PKEY_DH:
  506. {
  507. #ifndef HAVE_EVP_PKEY_GET_PARAMS
  508. DH *dh;
  509. #ifdef HAVE_OPAQUE_EVP_PKEY
  510. dh = EVP_PKEY_get0_DH(pubkey);
  511. #else
  512. dh = pubkey->pkey.dh;
  513. #endif /* HAVE_OPAQUE_EVP_PKEY */
  514. #endif /* !HAVE_EVP_PKEY_GET_PARAMS */
  515. {
  516. #ifdef HAVE_OPAQUE_RSA_DSA_DH
  517. DECLARE_PKEY_PARAM_BIGNUM(p);
  518. DECLARE_PKEY_PARAM_BIGNUM(q);
  519. DECLARE_PKEY_PARAM_BIGNUM(g);
  520. DECLARE_PKEY_PARAM_BIGNUM(pub_key);
  521. #ifdef HAVE_EVP_PKEY_GET_PARAMS
  522. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_P, &p);
  523. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_Q, &q);
  524. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_FFC_G, &g);
  525. EVP_PKEY_get_bn_param(pubkey, OSSL_PKEY_PARAM_PUB_KEY, &pub_key);
  526. #else
  527. DH_get0_pqg(dh, &p, &q, &g);
  528. DH_get0_key(dh, &pub_key, NULL);
  529. #endif /* HAVE_EVP_PKEY_GET_PARAMS */
  530. print_pubkey_BN(dh, p, i);
  531. print_pubkey_BN(dh, q, i);
  532. print_pubkey_BN(dh, g, i);
  533. #else
  534. print_pubkey_BN(dh, p, i);
  535. print_pubkey_BN(dh, g, i);
  536. #endif /* HAVE_OPAQUE_RSA_DSA_DH */
  537. print_pubkey_BN(dh, pub_key, i);
  538. FREE_PKEY_PARAM_BIGNUM(p);
  539. FREE_PKEY_PARAM_BIGNUM(q);
  540. FREE_PKEY_PARAM_BIGNUM(g);
  541. FREE_PKEY_PARAM_BIGNUM(pub_key);
  542. }
  543. break;
  544. }
  545. }
  546. EVP_PKEY_free(pubkey);
  547. }
  548. if(psig) {
  549. for(j = 0; j < psig->length; j++)
  550. BIO_printf(mem, "%02x:", psig->data[j]);
  551. push_certinfo("Signature", i);
  552. }
  553. PEM_write_bio_X509(mem, x);
  554. push_certinfo("Cert", i);
  555. }
  556. BIO_free(mem);
  557. return CURLE_OK;
  558. }
  559. #endif /* quiche or OpenSSL */
  560. #ifdef USE_OPENSSL
  561. #if USE_PRE_1_1_API
  562. #if !defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER < 0x2070000fL
  563. #define BIO_set_init(x,v) ((x)->init=(v))
  564. #define BIO_get_data(x) ((x)->ptr)
  565. #define BIO_set_data(x,v) ((x)->ptr=(v))
  566. #endif
  567. #define BIO_get_shutdown(x) ((x)->shutdown)
  568. #define BIO_set_shutdown(x,v) ((x)->shutdown=(v))
  569. #endif /* USE_PRE_1_1_API */
  570. static int ossl_bio_cf_create(BIO *bio)
  571. {
  572. BIO_set_shutdown(bio, 1);
  573. BIO_set_init(bio, 1);
  574. #if USE_PRE_1_1_API
  575. bio->num = -1;
  576. #endif
  577. BIO_set_data(bio, NULL);
  578. return 1;
  579. }
  580. static int ossl_bio_cf_destroy(BIO *bio)
  581. {
  582. if(!bio)
  583. return 0;
  584. return 1;
  585. }
  586. static long ossl_bio_cf_ctrl(BIO *bio, int cmd, long num, void *ptr)
  587. {
  588. struct Curl_cfilter *cf = BIO_get_data(bio);
  589. long ret = 1;
  590. (void)cf;
  591. (void)ptr;
  592. switch(cmd) {
  593. case BIO_CTRL_GET_CLOSE:
  594. ret = (long)BIO_get_shutdown(bio);
  595. break;
  596. case BIO_CTRL_SET_CLOSE:
  597. BIO_set_shutdown(bio, (int)num);
  598. break;
  599. case BIO_CTRL_FLUSH:
  600. /* we do no delayed writes, but if we ever would, this
  601. * needs to trigger it. */
  602. ret = 1;
  603. break;
  604. case BIO_CTRL_DUP:
  605. ret = 1;
  606. break;
  607. #ifdef BIO_CTRL_EOF
  608. case BIO_CTRL_EOF:
  609. /* EOF has been reached on input? */
  610. return (!cf->next || !cf->next->connected);
  611. #endif
  612. default:
  613. ret = 0;
  614. break;
  615. }
  616. return ret;
  617. }
  618. static int ossl_bio_cf_out_write(BIO *bio, const char *buf, int blen)
  619. {
  620. struct Curl_cfilter *cf = BIO_get_data(bio);
  621. struct ssl_connect_data *connssl = cf->ctx;
  622. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  623. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  624. ssize_t nwritten;
  625. CURLcode result = CURLE_SEND_ERROR;
  626. DEBUGASSERT(data);
  627. if(blen < 0)
  628. return 0;
  629. nwritten = Curl_conn_cf_send(cf->next, data, buf, (size_t)blen, &result);
  630. CURL_TRC_CF(data, cf, "ossl_bio_cf_out_write(len=%d) -> %d, err=%d",
  631. blen, (int)nwritten, result);
  632. BIO_clear_retry_flags(bio);
  633. octx->io_result = result;
  634. if(nwritten < 0) {
  635. if(CURLE_AGAIN == result)
  636. BIO_set_retry_write(bio);
  637. }
  638. return (int)nwritten;
  639. }
  640. static int ossl_bio_cf_in_read(BIO *bio, char *buf, int blen)
  641. {
  642. struct Curl_cfilter *cf = BIO_get_data(bio);
  643. struct ssl_connect_data *connssl = cf->ctx;
  644. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  645. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  646. ssize_t nread;
  647. CURLcode result = CURLE_RECV_ERROR;
  648. DEBUGASSERT(data);
  649. /* OpenSSL catches this case, so should we. */
  650. if(!buf)
  651. return 0;
  652. if(blen < 0)
  653. return 0;
  654. nread = Curl_conn_cf_recv(cf->next, data, buf, (size_t)blen, &result);
  655. CURL_TRC_CF(data, cf, "ossl_bio_cf_in_read(len=%d) -> %d, err=%d",
  656. blen, (int)nread, result);
  657. BIO_clear_retry_flags(bio);
  658. octx->io_result = result;
  659. if(nread < 0) {
  660. if(CURLE_AGAIN == result)
  661. BIO_set_retry_read(bio);
  662. }
  663. else if(nread == 0) {
  664. connssl->peer_closed = TRUE;
  665. }
  666. /* Before returning server replies to the SSL instance, we need
  667. * to have setup the x509 store or verification will fail. */
  668. if(!octx->x509_store_setup) {
  669. result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx);
  670. if(result) {
  671. octx->io_result = result;
  672. return -1;
  673. }
  674. octx->x509_store_setup = TRUE;
  675. }
  676. return (int)nread;
  677. }
  678. #if USE_PRE_1_1_API
  679. static BIO_METHOD ossl_bio_cf_meth_1_0 = {
  680. BIO_TYPE_MEM,
  681. "OpenSSL CF BIO",
  682. ossl_bio_cf_out_write,
  683. ossl_bio_cf_in_read,
  684. NULL, /* puts is never called */
  685. NULL, /* gets is never called */
  686. ossl_bio_cf_ctrl,
  687. ossl_bio_cf_create,
  688. ossl_bio_cf_destroy,
  689. NULL
  690. };
  691. static BIO_METHOD *ossl_bio_cf_method_create(void)
  692. {
  693. return &ossl_bio_cf_meth_1_0;
  694. }
  695. #define ossl_bio_cf_method_free(m) Curl_nop_stmt
  696. #else
  697. static BIO_METHOD *ossl_bio_cf_method_create(void)
  698. {
  699. BIO_METHOD *m = BIO_meth_new(BIO_TYPE_MEM, "OpenSSL CF BIO");
  700. if(m) {
  701. BIO_meth_set_write(m, &ossl_bio_cf_out_write);
  702. BIO_meth_set_read(m, &ossl_bio_cf_in_read);
  703. BIO_meth_set_ctrl(m, &ossl_bio_cf_ctrl);
  704. BIO_meth_set_create(m, &ossl_bio_cf_create);
  705. BIO_meth_set_destroy(m, &ossl_bio_cf_destroy);
  706. }
  707. return m;
  708. }
  709. static void ossl_bio_cf_method_free(BIO_METHOD *m)
  710. {
  711. if(m)
  712. BIO_meth_free(m);
  713. }
  714. #endif
  715. /*
  716. * Number of bytes to read from the random number seed file. This must be
  717. * a finite value (because some entropy "files" like /dev/urandom have
  718. * an infinite length), but must be large enough to provide enough
  719. * entropy to properly seed OpenSSL's PRNG.
  720. */
  721. #define RAND_LOAD_LENGTH 1024
  722. #ifdef HAVE_KEYLOG_CALLBACK
  723. static void ossl_keylog_callback(const SSL *ssl, const char *line)
  724. {
  725. (void)ssl;
  726. Curl_tls_keylog_write_line(line);
  727. }
  728. #else
  729. /*
  730. * ossl_log_tls12_secret is called by libcurl to make the CLIENT_RANDOMs if the
  731. * OpenSSL being used does not have native support for doing that.
  732. */
  733. static void
  734. ossl_log_tls12_secret(const SSL *ssl, bool *keylog_done)
  735. {
  736. const SSL_SESSION *session = SSL_get_session(ssl);
  737. unsigned char client_random[SSL3_RANDOM_SIZE];
  738. unsigned char master_key[SSL_MAX_MASTER_KEY_LENGTH];
  739. int master_key_length = 0;
  740. if(!session || *keylog_done)
  741. return;
  742. #if OPENSSL_VERSION_NUMBER >= 0x10100000L && \
  743. !(defined(LIBRESSL_VERSION_NUMBER) && \
  744. LIBRESSL_VERSION_NUMBER < 0x20700000L)
  745. /* ssl->s3 is not checked in OpenSSL 1.1.0-pre6, but let's assume that
  746. * we have a valid SSL context if we have a non-NULL session. */
  747. SSL_get_client_random(ssl, client_random, SSL3_RANDOM_SIZE);
  748. master_key_length = (int)
  749. SSL_SESSION_get_master_key(session, master_key, SSL_MAX_MASTER_KEY_LENGTH);
  750. #else
  751. if(ssl->s3 && session->master_key_length > 0) {
  752. master_key_length = session->master_key_length;
  753. memcpy(master_key, session->master_key, session->master_key_length);
  754. memcpy(client_random, ssl->s3->client_random, SSL3_RANDOM_SIZE);
  755. }
  756. #endif
  757. /* The handshake has not progressed sufficiently yet, or this is a TLS 1.3
  758. * session (when curl was built with older OpenSSL headers and running with
  759. * newer OpenSSL runtime libraries). */
  760. if(master_key_length <= 0)
  761. return;
  762. *keylog_done = true;
  763. Curl_tls_keylog_write("CLIENT_RANDOM", client_random,
  764. master_key, master_key_length);
  765. }
  766. #endif /* !HAVE_KEYLOG_CALLBACK */
  767. static const char *SSL_ERROR_to_str(int err)
  768. {
  769. switch(err) {
  770. case SSL_ERROR_NONE:
  771. return "SSL_ERROR_NONE";
  772. case SSL_ERROR_SSL:
  773. return "SSL_ERROR_SSL";
  774. case SSL_ERROR_WANT_READ:
  775. return "SSL_ERROR_WANT_READ";
  776. case SSL_ERROR_WANT_WRITE:
  777. return "SSL_ERROR_WANT_WRITE";
  778. case SSL_ERROR_WANT_X509_LOOKUP:
  779. return "SSL_ERROR_WANT_X509_LOOKUP";
  780. case SSL_ERROR_SYSCALL:
  781. return "SSL_ERROR_SYSCALL";
  782. case SSL_ERROR_ZERO_RETURN:
  783. return "SSL_ERROR_ZERO_RETURN";
  784. case SSL_ERROR_WANT_CONNECT:
  785. return "SSL_ERROR_WANT_CONNECT";
  786. case SSL_ERROR_WANT_ACCEPT:
  787. return "SSL_ERROR_WANT_ACCEPT";
  788. #if defined(SSL_ERROR_WANT_ASYNC)
  789. case SSL_ERROR_WANT_ASYNC:
  790. return "SSL_ERROR_WANT_ASYNC";
  791. #endif
  792. #if defined(SSL_ERROR_WANT_ASYNC_JOB)
  793. case SSL_ERROR_WANT_ASYNC_JOB:
  794. return "SSL_ERROR_WANT_ASYNC_JOB";
  795. #endif
  796. #if defined(SSL_ERROR_WANT_EARLY)
  797. case SSL_ERROR_WANT_EARLY:
  798. return "SSL_ERROR_WANT_EARLY";
  799. #endif
  800. default:
  801. return "SSL_ERROR unknown";
  802. }
  803. }
  804. static size_t ossl_version(char *buffer, size_t size);
  805. /* Return error string for last OpenSSL error
  806. */
  807. static char *ossl_strerror(unsigned long error, char *buf, size_t size)
  808. {
  809. size_t len;
  810. DEBUGASSERT(size);
  811. *buf = '\0';
  812. len = ossl_version(buf, size);
  813. DEBUGASSERT(len < (size - 2));
  814. if(len < (size - 2)) {
  815. buf += len;
  816. size -= (len + 2);
  817. *buf++ = ':';
  818. *buf++ = ' ';
  819. *buf = '\0';
  820. }
  821. #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
  822. ERR_error_string_n((uint32_t)error, buf, size);
  823. #else
  824. ERR_error_string_n(error, buf, size);
  825. #endif
  826. if(!*buf) {
  827. const char *msg = error ? "Unknown error" : "No error";
  828. if(strlen(msg) < size)
  829. strcpy(buf, msg);
  830. }
  831. return buf;
  832. }
  833. static int passwd_callback(char *buf, int num, int encrypting,
  834. void *global_passwd)
  835. {
  836. DEBUGASSERT(0 == encrypting);
  837. if(!encrypting && num >= 0) {
  838. int klen = curlx_uztosi(strlen((char *)global_passwd));
  839. if(num > klen) {
  840. memcpy(buf, global_passwd, klen + 1);
  841. return klen;
  842. }
  843. }
  844. return 0;
  845. }
  846. /*
  847. * rand_enough() returns TRUE if we have seeded the random engine properly.
  848. */
  849. static bool rand_enough(void)
  850. {
  851. return (0 != RAND_status()) ? TRUE : FALSE;
  852. }
  853. static CURLcode ossl_seed(struct Curl_easy *data)
  854. {
  855. /* This might get called before it has been added to a multi handle */
  856. if(data->multi && data->multi->ssl_seeded)
  857. return CURLE_OK;
  858. if(rand_enough()) {
  859. /* OpenSSL 1.1.0+ should return here */
  860. if(data->multi)
  861. data->multi->ssl_seeded = TRUE;
  862. return CURLE_OK;
  863. }
  864. #ifdef HAVE_RANDOM_INIT_BY_DEFAULT
  865. /* with OpenSSL 1.1.0+, a failed RAND_status is a showstopper */
  866. failf(data, "Insufficient randomness");
  867. return CURLE_SSL_CONNECT_ERROR;
  868. #else
  869. #ifdef RANDOM_FILE
  870. RAND_load_file(RANDOM_FILE, RAND_LOAD_LENGTH);
  871. if(rand_enough())
  872. return CURLE_OK;
  873. #endif
  874. /* fallback to a custom seeding of the PRNG using a hash based on a current
  875. time */
  876. do {
  877. unsigned char randb[64];
  878. size_t len = sizeof(randb);
  879. size_t i, i_max;
  880. for(i = 0, i_max = len / sizeof(struct curltime); i < i_max; ++i) {
  881. struct curltime tv = Curl_now();
  882. Curl_wait_ms(1);
  883. tv.tv_sec *= (time_t)i + 1;
  884. tv.tv_usec *= (int)i + 2;
  885. tv.tv_sec ^= ((Curl_now().tv_sec + (time_t)Curl_now().tv_usec) *
  886. (time_t)(i + 3)) << 8;
  887. tv.tv_usec ^= (int) ((Curl_now().tv_sec + (time_t)Curl_now().tv_usec) *
  888. (time_t)(i + 4)) << 16;
  889. memcpy(&randb[i * sizeof(struct curltime)], &tv,
  890. sizeof(struct curltime));
  891. }
  892. RAND_add(randb, (int)len, (double)len/2);
  893. } while(!rand_enough());
  894. {
  895. /* generates a default path for the random seed file */
  896. char fname[256];
  897. fname[0] = 0; /* blank it first */
  898. RAND_file_name(fname, sizeof(fname));
  899. if(fname[0]) {
  900. /* we got a filename to try */
  901. RAND_load_file(fname, RAND_LOAD_LENGTH);
  902. if(rand_enough())
  903. return CURLE_OK;
  904. }
  905. }
  906. infof(data, "libcurl is now using a weak random seed");
  907. return (rand_enough() ? CURLE_OK :
  908. CURLE_SSL_CONNECT_ERROR /* confusing error code */);
  909. #endif
  910. }
  911. #ifndef SSL_FILETYPE_ENGINE
  912. #define SSL_FILETYPE_ENGINE 42
  913. #endif
  914. #ifndef SSL_FILETYPE_PKCS12
  915. #define SSL_FILETYPE_PKCS12 43
  916. #endif
  917. static int do_file_type(const char *type)
  918. {
  919. if(!type || !type[0])
  920. return SSL_FILETYPE_PEM;
  921. if(strcasecompare(type, "PEM"))
  922. return SSL_FILETYPE_PEM;
  923. if(strcasecompare(type, "DER"))
  924. return SSL_FILETYPE_ASN1;
  925. if(strcasecompare(type, "ENG"))
  926. return SSL_FILETYPE_ENGINE;
  927. if(strcasecompare(type, "P12"))
  928. return SSL_FILETYPE_PKCS12;
  929. return -1;
  930. }
  931. #ifdef USE_OPENSSL_ENGINE
  932. /*
  933. * Supply default password to the engine user interface conversation.
  934. * The password is passed by OpenSSL engine from ENGINE_load_private_key()
  935. * last argument to the ui and can be obtained by UI_get0_user_data(ui) here.
  936. */
  937. static int ssl_ui_reader(UI *ui, UI_STRING *uis)
  938. {
  939. const char *password;
  940. switch(UI_get_string_type(uis)) {
  941. case UIT_PROMPT:
  942. case UIT_VERIFY:
  943. password = (const char *)UI_get0_user_data(ui);
  944. if(password && (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  945. UI_set_result(ui, uis, password);
  946. return 1;
  947. }
  948. FALLTHROUGH();
  949. default:
  950. break;
  951. }
  952. return (UI_method_get_reader(UI_OpenSSL()))(ui, uis);
  953. }
  954. /*
  955. * Suppress interactive request for a default password if available.
  956. */
  957. static int ssl_ui_writer(UI *ui, UI_STRING *uis)
  958. {
  959. switch(UI_get_string_type(uis)) {
  960. case UIT_PROMPT:
  961. case UIT_VERIFY:
  962. if(UI_get0_user_data(ui) &&
  963. (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD)) {
  964. return 1;
  965. }
  966. FALLTHROUGH();
  967. default:
  968. break;
  969. }
  970. return (UI_method_get_writer(UI_OpenSSL()))(ui, uis);
  971. }
  972. /*
  973. * Check if a given string is a PKCS#11 URI
  974. */
  975. static bool is_pkcs11_uri(const char *string)
  976. {
  977. return (string && strncasecompare(string, "pkcs11:", 7));
  978. }
  979. #endif
  980. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine);
  981. static int
  982. SSL_CTX_use_certificate_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  983. int type, const char *key_passwd)
  984. {
  985. int ret = 0;
  986. X509 *x = NULL;
  987. /* the typecast of blob->len is fine since it is guaranteed to never be
  988. larger than CURL_MAX_INPUT_LENGTH */
  989. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  990. if(!in)
  991. return CURLE_OUT_OF_MEMORY;
  992. if(type == SSL_FILETYPE_ASN1) {
  993. /* j = ERR_R_ASN1_LIB; */
  994. x = d2i_X509_bio(in, NULL);
  995. }
  996. else if(type == SSL_FILETYPE_PEM) {
  997. /* ERR_R_PEM_LIB; */
  998. x = PEM_read_bio_X509(in, NULL,
  999. passwd_callback, (void *)key_passwd);
  1000. }
  1001. else {
  1002. ret = 0;
  1003. goto end;
  1004. }
  1005. if(!x) {
  1006. ret = 0;
  1007. goto end;
  1008. }
  1009. ret = SSL_CTX_use_certificate(ctx, x);
  1010. end:
  1011. X509_free(x);
  1012. BIO_free(in);
  1013. return ret;
  1014. }
  1015. static int
  1016. SSL_CTX_use_PrivateKey_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  1017. int type, const char *key_passwd)
  1018. {
  1019. int ret = 0;
  1020. EVP_PKEY *pkey = NULL;
  1021. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  1022. if(!in)
  1023. return CURLE_OUT_OF_MEMORY;
  1024. if(type == SSL_FILETYPE_PEM)
  1025. pkey = PEM_read_bio_PrivateKey(in, NULL, passwd_callback,
  1026. (void *)key_passwd);
  1027. else if(type == SSL_FILETYPE_ASN1)
  1028. pkey = d2i_PrivateKey_bio(in, NULL);
  1029. else {
  1030. ret = 0;
  1031. goto end;
  1032. }
  1033. if(!pkey) {
  1034. ret = 0;
  1035. goto end;
  1036. }
  1037. ret = SSL_CTX_use_PrivateKey(ctx, pkey);
  1038. EVP_PKEY_free(pkey);
  1039. end:
  1040. BIO_free(in);
  1041. return ret;
  1042. }
  1043. static int
  1044. SSL_CTX_use_certificate_chain_blob(SSL_CTX *ctx, const struct curl_blob *blob,
  1045. const char *key_passwd)
  1046. {
  1047. /* SSL_CTX_add1_chain_cert introduced in OpenSSL 1.0.2 */
  1048. #if (OPENSSL_VERSION_NUMBER >= 0x1000200fL) && /* OpenSSL 1.0.2 or later */ \
  1049. !(defined(LIBRESSL_VERSION_NUMBER) && \
  1050. (LIBRESSL_VERSION_NUMBER < 0x2090100fL)) /* LibreSSL 2.9.1 or later */
  1051. int ret = 0;
  1052. X509 *x = NULL;
  1053. void *passwd_callback_userdata = (void *)key_passwd;
  1054. BIO *in = BIO_new_mem_buf(blob->data, (int)(blob->len));
  1055. if(!in)
  1056. return CURLE_OUT_OF_MEMORY;
  1057. ERR_clear_error();
  1058. x = PEM_read_bio_X509_AUX(in, NULL,
  1059. passwd_callback, (void *)key_passwd);
  1060. if(!x) {
  1061. ret = 0;
  1062. goto end;
  1063. }
  1064. ret = SSL_CTX_use_certificate(ctx, x);
  1065. if(ERR_peek_error() != 0)
  1066. ret = 0;
  1067. if(ret) {
  1068. X509 *ca;
  1069. sslerr_t err;
  1070. if(!SSL_CTX_clear_chain_certs(ctx)) {
  1071. ret = 0;
  1072. goto end;
  1073. }
  1074. while((ca = PEM_read_bio_X509(in, NULL, passwd_callback,
  1075. passwd_callback_userdata))
  1076. != NULL) {
  1077. if(!SSL_CTX_add0_chain_cert(ctx, ca)) {
  1078. X509_free(ca);
  1079. ret = 0;
  1080. goto end;
  1081. }
  1082. }
  1083. err = ERR_peek_last_error();
  1084. if((ERR_GET_LIB(err) == ERR_LIB_PEM) &&
  1085. (ERR_GET_REASON(err) == PEM_R_NO_START_LINE))
  1086. ERR_clear_error();
  1087. else
  1088. ret = 0;
  1089. }
  1090. end:
  1091. X509_free(x);
  1092. BIO_free(in);
  1093. return ret;
  1094. #else
  1095. (void)ctx; /* unused */
  1096. (void)blob; /* unused */
  1097. (void)key_passwd; /* unused */
  1098. return 0;
  1099. #endif
  1100. }
  1101. static
  1102. int cert_stuff(struct Curl_easy *data,
  1103. SSL_CTX* ctx,
  1104. char *cert_file,
  1105. const struct curl_blob *cert_blob,
  1106. const char *cert_type,
  1107. char *key_file,
  1108. const struct curl_blob *key_blob,
  1109. const char *key_type,
  1110. char *key_passwd)
  1111. {
  1112. char error_buffer[256];
  1113. bool check_privkey = TRUE;
  1114. int file_type = do_file_type(cert_type);
  1115. if(cert_file || cert_blob || (file_type == SSL_FILETYPE_ENGINE)) {
  1116. SSL *ssl;
  1117. X509 *x509;
  1118. int cert_done = 0;
  1119. int cert_use_result;
  1120. if(key_passwd) {
  1121. /* set the password in the callback userdata */
  1122. SSL_CTX_set_default_passwd_cb_userdata(ctx, key_passwd);
  1123. /* Set passwd callback: */
  1124. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  1125. }
  1126. switch(file_type) {
  1127. case SSL_FILETYPE_PEM:
  1128. /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
  1129. cert_use_result = cert_blob ?
  1130. SSL_CTX_use_certificate_chain_blob(ctx, cert_blob, key_passwd) :
  1131. SSL_CTX_use_certificate_chain_file(ctx, cert_file);
  1132. if(cert_use_result != 1) {
  1133. failf(data,
  1134. "could not load PEM client certificate from %s, " OSSL_PACKAGE
  1135. " error %s, "
  1136. "(no key found, wrong pass phrase, or wrong file format?)",
  1137. (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
  1138. ossl_strerror(ERR_get_error(), error_buffer,
  1139. sizeof(error_buffer)) );
  1140. return 0;
  1141. }
  1142. break;
  1143. case SSL_FILETYPE_ASN1:
  1144. /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
  1145. we use the case above for PEM so this can only be performed with
  1146. ASN1 files. */
  1147. cert_use_result = cert_blob ?
  1148. SSL_CTX_use_certificate_blob(ctx, cert_blob,
  1149. file_type, key_passwd) :
  1150. SSL_CTX_use_certificate_file(ctx, cert_file, file_type);
  1151. if(cert_use_result != 1) {
  1152. failf(data,
  1153. "could not load ASN1 client certificate from %s, " OSSL_PACKAGE
  1154. " error %s, "
  1155. "(no key found, wrong pass phrase, or wrong file format?)",
  1156. (cert_blob ? "CURLOPT_SSLCERT_BLOB" : cert_file),
  1157. ossl_strerror(ERR_get_error(), error_buffer,
  1158. sizeof(error_buffer)) );
  1159. return 0;
  1160. }
  1161. break;
  1162. case SSL_FILETYPE_ENGINE:
  1163. #if defined(USE_OPENSSL_ENGINE) && defined(ENGINE_CTRL_GET_CMD_FROM_NAME)
  1164. {
  1165. /* Implicitly use pkcs11 engine if none was provided and the
  1166. * cert_file is a PKCS#11 URI */
  1167. if(!data->state.engine) {
  1168. if(is_pkcs11_uri(cert_file)) {
  1169. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  1170. return 0;
  1171. }
  1172. }
  1173. }
  1174. if(data->state.engine) {
  1175. const char *cmd_name = "LOAD_CERT_CTRL";
  1176. struct {
  1177. const char *cert_id;
  1178. X509 *cert;
  1179. } params;
  1180. params.cert_id = cert_file;
  1181. params.cert = NULL;
  1182. /* Does the engine supports LOAD_CERT_CTRL ? */
  1183. if(!ENGINE_ctrl(data->state.engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
  1184. 0, (void *)cmd_name, NULL)) {
  1185. failf(data, "ssl engine does not support loading certificates");
  1186. return 0;
  1187. }
  1188. /* Load the certificate from the engine */
  1189. if(!ENGINE_ctrl_cmd(data->state.engine, cmd_name,
  1190. 0, &params, NULL, 1)) {
  1191. failf(data, "ssl engine cannot load client cert with id"
  1192. " '%s' [%s]", cert_file,
  1193. ossl_strerror(ERR_get_error(), error_buffer,
  1194. sizeof(error_buffer)));
  1195. return 0;
  1196. }
  1197. if(!params.cert) {
  1198. failf(data, "ssl engine did not initialized the certificate "
  1199. "properly.");
  1200. return 0;
  1201. }
  1202. if(SSL_CTX_use_certificate(ctx, params.cert) != 1) {
  1203. failf(data, "unable to set client certificate [%s]",
  1204. ossl_strerror(ERR_get_error(), error_buffer,
  1205. sizeof(error_buffer)));
  1206. return 0;
  1207. }
  1208. X509_free(params.cert); /* we do not need the handle any more... */
  1209. }
  1210. else {
  1211. failf(data, "crypto engine not set, cannot load certificate");
  1212. return 0;
  1213. }
  1214. }
  1215. break;
  1216. #else
  1217. failf(data, "file type ENG for certificate not implemented");
  1218. return 0;
  1219. #endif
  1220. case SSL_FILETYPE_PKCS12:
  1221. {
  1222. BIO *cert_bio = NULL;
  1223. PKCS12 *p12 = NULL;
  1224. EVP_PKEY *pri;
  1225. STACK_OF(X509) *ca = NULL;
  1226. if(cert_blob) {
  1227. cert_bio = BIO_new_mem_buf(cert_blob->data, (int)(cert_blob->len));
  1228. if(!cert_bio) {
  1229. failf(data,
  1230. "BIO_new_mem_buf NULL, " OSSL_PACKAGE
  1231. " error %s",
  1232. ossl_strerror(ERR_get_error(), error_buffer,
  1233. sizeof(error_buffer)) );
  1234. return 0;
  1235. }
  1236. }
  1237. else {
  1238. cert_bio = BIO_new(BIO_s_file());
  1239. if(!cert_bio) {
  1240. failf(data,
  1241. "BIO_new return NULL, " OSSL_PACKAGE
  1242. " error %s",
  1243. ossl_strerror(ERR_get_error(), error_buffer,
  1244. sizeof(error_buffer)) );
  1245. return 0;
  1246. }
  1247. if(BIO_read_filename(cert_bio, cert_file) <= 0) {
  1248. failf(data, "could not open PKCS12 file '%s'", cert_file);
  1249. BIO_free(cert_bio);
  1250. return 0;
  1251. }
  1252. }
  1253. p12 = d2i_PKCS12_bio(cert_bio, NULL);
  1254. BIO_free(cert_bio);
  1255. if(!p12) {
  1256. failf(data, "error reading PKCS12 file '%s'",
  1257. cert_blob ? "(memory blob)" : cert_file);
  1258. return 0;
  1259. }
  1260. PKCS12_PBE_add();
  1261. if(!PKCS12_parse(p12, key_passwd, &pri, &x509,
  1262. &ca)) {
  1263. failf(data,
  1264. "could not parse PKCS12 file, check password, " OSSL_PACKAGE
  1265. " error %s",
  1266. ossl_strerror(ERR_get_error(), error_buffer,
  1267. sizeof(error_buffer)) );
  1268. PKCS12_free(p12);
  1269. return 0;
  1270. }
  1271. PKCS12_free(p12);
  1272. if(SSL_CTX_use_certificate(ctx, x509) != 1) {
  1273. failf(data,
  1274. "could not load PKCS12 client certificate, " OSSL_PACKAGE
  1275. " error %s",
  1276. ossl_strerror(ERR_get_error(), error_buffer,
  1277. sizeof(error_buffer)) );
  1278. goto fail;
  1279. }
  1280. if(SSL_CTX_use_PrivateKey(ctx, pri) != 1) {
  1281. failf(data, "unable to use private key from PKCS12 file '%s'",
  1282. cert_file);
  1283. goto fail;
  1284. }
  1285. if(!SSL_CTX_check_private_key (ctx)) {
  1286. failf(data, "private key from PKCS12 file '%s' "
  1287. "does not match certificate in same file", cert_file);
  1288. goto fail;
  1289. }
  1290. /* Set Certificate Verification chain */
  1291. if(ca) {
  1292. while(sk_X509_num(ca)) {
  1293. /*
  1294. * Note that sk_X509_pop() is used below to make sure the cert is
  1295. * removed from the stack properly before getting passed to
  1296. * SSL_CTX_add_extra_chain_cert(), which takes ownership. Previously
  1297. * we used sk_X509_value() instead, but then we would clean it in the
  1298. * subsequent sk_X509_pop_free() call.
  1299. */
  1300. X509 *x = sk_X509_pop(ca);
  1301. if(!SSL_CTX_add_client_CA(ctx, x)) {
  1302. X509_free(x);
  1303. failf(data, "cannot add certificate to client CA list");
  1304. goto fail;
  1305. }
  1306. if(!SSL_CTX_add_extra_chain_cert(ctx, x)) {
  1307. X509_free(x);
  1308. failf(data, "cannot add certificate to certificate chain");
  1309. goto fail;
  1310. }
  1311. }
  1312. }
  1313. cert_done = 1;
  1314. fail:
  1315. EVP_PKEY_free(pri);
  1316. X509_free(x509);
  1317. sk_X509_pop_free(ca, X509_free);
  1318. if(!cert_done)
  1319. return 0; /* failure! */
  1320. break;
  1321. }
  1322. default:
  1323. failf(data, "not supported file type '%s' for certificate", cert_type);
  1324. return 0;
  1325. }
  1326. if((!key_file) && (!key_blob)) {
  1327. key_file = cert_file;
  1328. key_blob = cert_blob;
  1329. }
  1330. else
  1331. file_type = do_file_type(key_type);
  1332. switch(file_type) {
  1333. case SSL_FILETYPE_PEM:
  1334. if(cert_done)
  1335. break;
  1336. FALLTHROUGH();
  1337. case SSL_FILETYPE_ASN1:
  1338. cert_use_result = key_blob ?
  1339. SSL_CTX_use_PrivateKey_blob(ctx, key_blob, file_type, key_passwd) :
  1340. SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type);
  1341. if(cert_use_result != 1) {
  1342. failf(data, "unable to set private key file: '%s' type %s",
  1343. key_file?key_file:"(memory blob)", key_type?key_type:"PEM");
  1344. return 0;
  1345. }
  1346. break;
  1347. case SSL_FILETYPE_ENGINE:
  1348. #ifdef USE_OPENSSL_ENGINE
  1349. {
  1350. EVP_PKEY *priv_key = NULL;
  1351. /* Implicitly use pkcs11 engine if none was provided and the
  1352. * key_file is a PKCS#11 URI */
  1353. if(!data->state.engine) {
  1354. if(is_pkcs11_uri(key_file)) {
  1355. if(ossl_set_engine(data, "pkcs11") != CURLE_OK) {
  1356. return 0;
  1357. }
  1358. }
  1359. }
  1360. if(data->state.engine) {
  1361. UI_METHOD *ui_method =
  1362. UI_create_method((char *)"curl user interface");
  1363. if(!ui_method) {
  1364. failf(data, "unable do create " OSSL_PACKAGE
  1365. " user-interface method");
  1366. return 0;
  1367. }
  1368. UI_method_set_opener(ui_method, UI_method_get_opener(UI_OpenSSL()));
  1369. UI_method_set_closer(ui_method, UI_method_get_closer(UI_OpenSSL()));
  1370. UI_method_set_reader(ui_method, ssl_ui_reader);
  1371. UI_method_set_writer(ui_method, ssl_ui_writer);
  1372. priv_key = ENGINE_load_private_key(data->state.engine, key_file,
  1373. ui_method,
  1374. key_passwd);
  1375. UI_destroy_method(ui_method);
  1376. if(!priv_key) {
  1377. failf(data, "failed to load private key from crypto engine");
  1378. return 0;
  1379. }
  1380. if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
  1381. failf(data, "unable to set private key");
  1382. EVP_PKEY_free(priv_key);
  1383. return 0;
  1384. }
  1385. EVP_PKEY_free(priv_key); /* we do not need the handle any more... */
  1386. }
  1387. else {
  1388. failf(data, "crypto engine not set, cannot load private key");
  1389. return 0;
  1390. }
  1391. }
  1392. break;
  1393. #else
  1394. failf(data, "file type ENG for private key not supported");
  1395. return 0;
  1396. #endif
  1397. case SSL_FILETYPE_PKCS12:
  1398. if(!cert_done) {
  1399. failf(data, "file type P12 for private key not supported");
  1400. return 0;
  1401. }
  1402. break;
  1403. default:
  1404. failf(data, "not supported file type for private key");
  1405. return 0;
  1406. }
  1407. ssl = SSL_new(ctx);
  1408. if(!ssl) {
  1409. failf(data, "unable to create an SSL structure");
  1410. return 0;
  1411. }
  1412. x509 = SSL_get_certificate(ssl);
  1413. /* This version was provided by Evan Jordan and is supposed to not
  1414. leak memory as the previous version: */
  1415. if(x509) {
  1416. EVP_PKEY *pktmp = X509_get_pubkey(x509);
  1417. EVP_PKEY_copy_parameters(pktmp, SSL_get_privatekey(ssl));
  1418. EVP_PKEY_free(pktmp);
  1419. }
  1420. #if !defined(OPENSSL_NO_RSA) && !defined(OPENSSL_IS_BORINGSSL) && \
  1421. !defined(OPENSSL_NO_DEPRECATED_3_0)
  1422. {
  1423. /* If RSA is used, do not check the private key if its flags indicate
  1424. * it does not support it. */
  1425. EVP_PKEY *priv_key = SSL_get_privatekey(ssl);
  1426. int pktype;
  1427. #ifdef HAVE_OPAQUE_EVP_PKEY
  1428. pktype = EVP_PKEY_id(priv_key);
  1429. #else
  1430. pktype = priv_key->type;
  1431. #endif
  1432. if(pktype == EVP_PKEY_RSA) {
  1433. RSA *rsa = EVP_PKEY_get1_RSA(priv_key);
  1434. if(RSA_flags(rsa) & RSA_METHOD_FLAG_NO_CHECK)
  1435. check_privkey = FALSE;
  1436. RSA_free(rsa); /* Decrement reference count */
  1437. }
  1438. }
  1439. #endif
  1440. SSL_free(ssl);
  1441. /* If we are using DSA, we can copy the parameters from
  1442. * the private key */
  1443. if(check_privkey == TRUE) {
  1444. /* Now we know that a key and cert have been set against
  1445. * the SSL context */
  1446. if(!SSL_CTX_check_private_key(ctx)) {
  1447. failf(data, "Private key does not match the certificate public key");
  1448. return 0;
  1449. }
  1450. }
  1451. }
  1452. return 1;
  1453. }
  1454. CURLcode Curl_ossl_set_client_cert(struct Curl_easy *data, SSL_CTX *ctx,
  1455. char *cert_file,
  1456. const struct curl_blob *cert_blob,
  1457. const char *cert_type, char *key_file,
  1458. const struct curl_blob *key_blob,
  1459. const char *key_type, char *key_passwd)
  1460. {
  1461. int rv = cert_stuff(data, ctx, cert_file, cert_blob, cert_type, key_file,
  1462. key_blob, key_type, key_passwd);
  1463. if(rv != 1) {
  1464. return CURLE_SSL_CERTPROBLEM;
  1465. }
  1466. return CURLE_OK;
  1467. }
  1468. /* returns non-zero on failure */
  1469. static int x509_name_oneline(X509_NAME *a, char *buf, size_t size)
  1470. {
  1471. BIO *bio_out = BIO_new(BIO_s_mem());
  1472. BUF_MEM *biomem;
  1473. int rc;
  1474. if(!bio_out)
  1475. return 1; /* alloc failed! */
  1476. rc = X509_NAME_print_ex(bio_out, a, 0, XN_FLAG_SEP_SPLUS_SPC);
  1477. BIO_get_mem_ptr(bio_out, &biomem);
  1478. if((size_t)biomem->length < size)
  1479. size = biomem->length;
  1480. else
  1481. size--; /* do not overwrite the buffer end */
  1482. memcpy(buf, biomem->data, size);
  1483. buf[size] = 0;
  1484. BIO_free(bio_out);
  1485. return !rc;
  1486. }
  1487. /**
  1488. * Global SSL init
  1489. *
  1490. * @retval 0 error initializing SSL
  1491. * @retval 1 SSL initialized successfully
  1492. */
  1493. static int ossl_init(void)
  1494. {
  1495. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  1496. (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
  1497. const uint64_t flags =
  1498. #ifdef OPENSSL_INIT_ENGINE_ALL_BUILTIN
  1499. /* not present in BoringSSL */
  1500. OPENSSL_INIT_ENGINE_ALL_BUILTIN |
  1501. #endif
  1502. #ifdef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1503. OPENSSL_INIT_NO_LOAD_CONFIG |
  1504. #else
  1505. OPENSSL_INIT_LOAD_CONFIG |
  1506. #endif
  1507. 0;
  1508. OPENSSL_init_ssl(flags, NULL);
  1509. #else
  1510. OPENSSL_load_builtin_modules();
  1511. #ifdef USE_OPENSSL_ENGINE
  1512. ENGINE_load_builtin_engines();
  1513. #endif
  1514. /* CONF_MFLAGS_DEFAULT_SECTION was introduced some time between 0.9.8b and
  1515. 0.9.8e */
  1516. #ifndef CONF_MFLAGS_DEFAULT_SECTION
  1517. #define CONF_MFLAGS_DEFAULT_SECTION 0x0
  1518. #endif
  1519. #ifndef CURL_DISABLE_OPENSSL_AUTO_LOAD_CONFIG
  1520. CONF_modules_load_file(NULL, NULL,
  1521. CONF_MFLAGS_DEFAULT_SECTION|
  1522. CONF_MFLAGS_IGNORE_MISSING_FILE);
  1523. #endif
  1524. /* Let's get nice error messages */
  1525. SSL_load_error_strings();
  1526. /* Init the global ciphers and digests */
  1527. if(!SSLeay_add_ssl_algorithms())
  1528. return 0;
  1529. OpenSSL_add_all_algorithms();
  1530. #endif
  1531. Curl_tls_keylog_open();
  1532. return 1;
  1533. }
  1534. /* Global cleanup */
  1535. static void ossl_cleanup(void)
  1536. {
  1537. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  1538. (!defined(LIBRESSL_VERSION_NUMBER) || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)
  1539. /* OpenSSL 1.1 deprecates all these cleanup functions and
  1540. turns them into no-ops in OpenSSL 1.0 compatibility mode */
  1541. #else
  1542. /* Free ciphers and digests lists */
  1543. EVP_cleanup();
  1544. #ifdef USE_OPENSSL_ENGINE
  1545. /* Free engine list */
  1546. ENGINE_cleanup();
  1547. #endif
  1548. /* Free OpenSSL error strings */
  1549. ERR_free_strings();
  1550. /* Free thread local error state, destroying hash upon zero refcount */
  1551. #ifdef HAVE_ERR_REMOVE_THREAD_STATE
  1552. ERR_remove_thread_state(NULL);
  1553. #else
  1554. ERR_remove_state(0);
  1555. #endif
  1556. /* Free all memory allocated by all configuration modules */
  1557. CONF_modules_free();
  1558. #ifdef HAVE_SSL_COMP_FREE_COMPRESSION_METHODS
  1559. SSL_COMP_free_compression_methods();
  1560. #endif
  1561. #endif
  1562. Curl_tls_keylog_close();
  1563. }
  1564. /* Selects an OpenSSL crypto engine
  1565. */
  1566. static CURLcode ossl_set_engine(struct Curl_easy *data, const char *engine)
  1567. {
  1568. #ifdef USE_OPENSSL_ENGINE
  1569. ENGINE *e;
  1570. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  1571. e = ENGINE_by_id(engine);
  1572. #else
  1573. /* avoid memory leak */
  1574. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  1575. const char *e_id = ENGINE_get_id(e);
  1576. if(!strcmp(engine, e_id))
  1577. break;
  1578. }
  1579. #endif
  1580. if(!e) {
  1581. failf(data, "SSL Engine '%s' not found", engine);
  1582. return CURLE_SSL_ENGINE_NOTFOUND;
  1583. }
  1584. if(data->state.engine) {
  1585. ENGINE_finish(data->state.engine);
  1586. ENGINE_free(data->state.engine);
  1587. data->state.engine = NULL;
  1588. }
  1589. if(!ENGINE_init(e)) {
  1590. char buf[256];
  1591. ENGINE_free(e);
  1592. failf(data, "Failed to initialise SSL Engine '%s': %s",
  1593. engine, ossl_strerror(ERR_get_error(), buf, sizeof(buf)));
  1594. return CURLE_SSL_ENGINE_INITFAILED;
  1595. }
  1596. data->state.engine = e;
  1597. return CURLE_OK;
  1598. #else
  1599. (void)engine;
  1600. failf(data, "SSL Engine not supported");
  1601. return CURLE_SSL_ENGINE_NOTFOUND;
  1602. #endif
  1603. }
  1604. /* Sets engine as default for all SSL operations
  1605. */
  1606. static CURLcode ossl_set_engine_default(struct Curl_easy *data)
  1607. {
  1608. #ifdef USE_OPENSSL_ENGINE
  1609. if(data->state.engine) {
  1610. if(ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
  1611. infof(data, "set default crypto engine '%s'",
  1612. ENGINE_get_id(data->state.engine));
  1613. }
  1614. else {
  1615. failf(data, "set default crypto engine '%s' failed",
  1616. ENGINE_get_id(data->state.engine));
  1617. return CURLE_SSL_ENGINE_SETFAILED;
  1618. }
  1619. }
  1620. #else
  1621. (void) data;
  1622. #endif
  1623. return CURLE_OK;
  1624. }
  1625. /* Return list of OpenSSL crypto engine names.
  1626. */
  1627. static struct curl_slist *ossl_engines_list(struct Curl_easy *data)
  1628. {
  1629. struct curl_slist *list = NULL;
  1630. #ifdef USE_OPENSSL_ENGINE
  1631. struct curl_slist *beg;
  1632. ENGINE *e;
  1633. for(e = ENGINE_get_first(); e; e = ENGINE_get_next(e)) {
  1634. beg = curl_slist_append(list, ENGINE_get_id(e));
  1635. if(!beg) {
  1636. curl_slist_free_all(list);
  1637. return NULL;
  1638. }
  1639. list = beg;
  1640. }
  1641. #endif
  1642. (void) data;
  1643. return list;
  1644. }
  1645. static CURLcode ossl_shutdown(struct Curl_cfilter *cf,
  1646. struct Curl_easy *data,
  1647. bool send_shutdown, bool *done)
  1648. {
  1649. struct ssl_connect_data *connssl = cf->ctx;
  1650. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  1651. CURLcode result = CURLE_OK;
  1652. char buf[1024];
  1653. int nread, err;
  1654. unsigned long sslerr;
  1655. size_t i;
  1656. DEBUGASSERT(octx);
  1657. if(!octx->ssl || cf->shutdown) {
  1658. *done = TRUE;
  1659. goto out;
  1660. }
  1661. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1662. *done = FALSE;
  1663. if(!(SSL_get_shutdown(octx->ssl) & SSL_SENT_SHUTDOWN)) {
  1664. /* We have not started the shutdown from our side yet. Check
  1665. * if the server already sent us one. */
  1666. ERR_clear_error();
  1667. for(i = 0; i < 10; ++i) {
  1668. nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
  1669. CURL_TRC_CF(data, cf, "SSL shutdown not sent, read -> %d", nread);
  1670. if(nread <= 0)
  1671. break;
  1672. }
  1673. err = SSL_get_error(octx->ssl, nread);
  1674. if(!nread && err == SSL_ERROR_ZERO_RETURN) {
  1675. bool input_pending;
  1676. /* Yes, it did. */
  1677. if(!send_shutdown) {
  1678. CURL_TRC_CF(data, cf, "SSL shutdown received, not sending");
  1679. *done = TRUE;
  1680. goto out;
  1681. }
  1682. else if(!cf->next->cft->is_alive(cf->next, data, &input_pending)) {
  1683. /* Server closed the connection after its closy notify. It
  1684. * seems not interested to see our close notify, so do not
  1685. * send it. We are done. */
  1686. connssl->peer_closed = TRUE;
  1687. CURL_TRC_CF(data, cf, "peer closed connection");
  1688. *done = TRUE;
  1689. goto out;
  1690. }
  1691. }
  1692. if(send_shutdown && SSL_shutdown(octx->ssl) == 1) {
  1693. CURL_TRC_CF(data, cf, "SSL shutdown finished");
  1694. *done = TRUE;
  1695. goto out;
  1696. }
  1697. }
  1698. /* SSL should now have started the shutdown from our side. Since it
  1699. * was not complete, we are lacking the close notify from the server. */
  1700. for(i = 0; i < 10; ++i) {
  1701. ERR_clear_error();
  1702. nread = SSL_read(octx->ssl, buf, (int)sizeof(buf));
  1703. CURL_TRC_CF(data, cf, "SSL shutdown read -> %d", nread);
  1704. if(nread <= 0)
  1705. break;
  1706. }
  1707. if(SSL_get_shutdown(octx->ssl) & SSL_RECEIVED_SHUTDOWN) {
  1708. CURL_TRC_CF(data, cf, "SSL shutdown received, finished");
  1709. *done = TRUE;
  1710. goto out;
  1711. }
  1712. err = SSL_get_error(octx->ssl, nread);
  1713. switch(err) {
  1714. case SSL_ERROR_ZERO_RETURN: /* no more data */
  1715. CURL_TRC_CF(data, cf, "SSL shutdown not received, but closed");
  1716. *done = TRUE;
  1717. break;
  1718. case SSL_ERROR_NONE: /* just did not get anything */
  1719. case SSL_ERROR_WANT_READ:
  1720. /* SSL has send its notify and now wants to read the reply
  1721. * from the server. We are not really interested in that. */
  1722. CURL_TRC_CF(data, cf, "SSL shutdown sent, want receive");
  1723. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  1724. break;
  1725. case SSL_ERROR_WANT_WRITE:
  1726. CURL_TRC_CF(data, cf, "SSL shutdown send blocked");
  1727. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  1728. break;
  1729. default:
  1730. /* Server seems to have closed the connection without sending us
  1731. * a close notify. */
  1732. sslerr = ERR_get_error();
  1733. CURL_TRC_CF(data, cf, "SSL shutdown, ignore recv error: '%s', errno %d",
  1734. (sslerr ?
  1735. ossl_strerror(sslerr, buf, sizeof(buf)) :
  1736. SSL_ERROR_to_str(err)),
  1737. SOCKERRNO);
  1738. *done = TRUE;
  1739. result = CURLE_OK;
  1740. break;
  1741. }
  1742. out:
  1743. cf->shutdown = (result || *done);
  1744. return result;
  1745. }
  1746. static void ossl_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  1747. {
  1748. struct ssl_connect_data *connssl = cf->ctx;
  1749. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  1750. (void)data;
  1751. DEBUGASSERT(octx);
  1752. if(octx->ssl) {
  1753. SSL_free(octx->ssl);
  1754. octx->ssl = NULL;
  1755. }
  1756. if(octx->ssl_ctx) {
  1757. SSL_CTX_free(octx->ssl_ctx);
  1758. octx->ssl_ctx = NULL;
  1759. octx->x509_store_setup = FALSE;
  1760. }
  1761. if(octx->bio_method) {
  1762. ossl_bio_cf_method_free(octx->bio_method);
  1763. octx->bio_method = NULL;
  1764. }
  1765. }
  1766. static void ossl_session_free(void *sessionid, size_t idsize)
  1767. {
  1768. /* free the ID */
  1769. (void)idsize;
  1770. SSL_SESSION_free(sessionid);
  1771. }
  1772. /*
  1773. * This function is called when the 'data' struct is going away. Close
  1774. * down everything and free all resources!
  1775. */
  1776. static void ossl_close_all(struct Curl_easy *data)
  1777. {
  1778. #ifdef USE_OPENSSL_ENGINE
  1779. if(data->state.engine) {
  1780. ENGINE_finish(data->state.engine);
  1781. ENGINE_free(data->state.engine);
  1782. data->state.engine = NULL;
  1783. }
  1784. #else
  1785. (void)data;
  1786. #endif
  1787. #if !defined(HAVE_ERR_REMOVE_THREAD_STATE_DEPRECATED) && \
  1788. defined(HAVE_ERR_REMOVE_THREAD_STATE)
  1789. /* OpenSSL 1.0.1 and 1.0.2 build an error queue that is stored per-thread
  1790. so we need to clean it here in case the thread will be killed. All OpenSSL
  1791. code should extract the error in association with the error so clearing
  1792. this queue here should be harmless at worst. */
  1793. ERR_remove_thread_state(NULL);
  1794. #endif
  1795. }
  1796. /* ====================================================== */
  1797. /*
  1798. * Match subjectAltName against the hostname.
  1799. */
  1800. static bool subj_alt_hostcheck(struct Curl_easy *data,
  1801. const char *match_pattern,
  1802. size_t matchlen,
  1803. const char *hostname,
  1804. size_t hostlen,
  1805. const char *dispname)
  1806. {
  1807. #ifdef CURL_DISABLE_VERBOSE_STRINGS
  1808. (void)dispname;
  1809. (void)data;
  1810. #endif
  1811. if(Curl_cert_hostcheck(match_pattern, matchlen, hostname, hostlen)) {
  1812. infof(data, " subjectAltName: host \"%s\" matched cert's \"%s\"",
  1813. dispname, match_pattern);
  1814. return TRUE;
  1815. }
  1816. return FALSE;
  1817. }
  1818. /* Quote from RFC2818 section 3.1 "Server Identity"
  1819. If a subjectAltName extension of type dNSName is present, that MUST
  1820. be used as the identity. Otherwise, the (most specific) Common Name
  1821. field in the Subject field of the certificate MUST be used. Although
  1822. the use of the Common Name is existing practice, it is deprecated and
  1823. Certification Authorities are encouraged to use the dNSName instead.
  1824. Matching is performed using the matching rules specified by
  1825. [RFC2459]. If more than one identity of a given type is present in
  1826. the certificate (e.g., more than one dNSName name, a match in any one
  1827. of the set is considered acceptable.) Names may contain the wildcard
  1828. character * which is considered to match any single domain name
  1829. component or component fragment. E.g., *.a.com matches foo.a.com but
  1830. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  1831. In some cases, the URI is specified as an IP address rather than a
  1832. hostname. In this case, the iPAddress subjectAltName must be present
  1833. in the certificate and must exactly match the IP in the URI.
  1834. This function is now used from ngtcp2 (QUIC) as well.
  1835. */
  1836. CURLcode Curl_ossl_verifyhost(struct Curl_easy *data, struct connectdata *conn,
  1837. struct ssl_peer *peer, X509 *server_cert)
  1838. {
  1839. bool matched = FALSE;
  1840. int target; /* target type, GEN_DNS or GEN_IPADD */
  1841. size_t addrlen = 0;
  1842. STACK_OF(GENERAL_NAME) *altnames;
  1843. #ifdef USE_IPV6
  1844. struct in6_addr addr;
  1845. #else
  1846. struct in_addr addr;
  1847. #endif
  1848. CURLcode result = CURLE_OK;
  1849. bool dNSName = FALSE; /* if a dNSName field exists in the cert */
  1850. bool iPAddress = FALSE; /* if an iPAddress field exists in the cert */
  1851. size_t hostlen;
  1852. (void)conn;
  1853. hostlen = strlen(peer->hostname);
  1854. switch(peer->type) {
  1855. case CURL_SSL_PEER_IPV4:
  1856. if(!Curl_inet_pton(AF_INET, peer->hostname, &addr))
  1857. return CURLE_PEER_FAILED_VERIFICATION;
  1858. target = GEN_IPADD;
  1859. addrlen = sizeof(struct in_addr);
  1860. break;
  1861. #ifdef USE_IPV6
  1862. case CURL_SSL_PEER_IPV6:
  1863. if(!Curl_inet_pton(AF_INET6, peer->hostname, &addr))
  1864. return CURLE_PEER_FAILED_VERIFICATION;
  1865. target = GEN_IPADD;
  1866. addrlen = sizeof(struct in6_addr);
  1867. break;
  1868. #endif
  1869. case CURL_SSL_PEER_DNS:
  1870. target = GEN_DNS;
  1871. break;
  1872. default:
  1873. DEBUGASSERT(0);
  1874. failf(data, "unexpected ssl peer type: %d", peer->type);
  1875. return CURLE_PEER_FAILED_VERIFICATION;
  1876. }
  1877. /* get a "list" of alternative names */
  1878. altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);
  1879. if(altnames) {
  1880. #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
  1881. size_t numalts;
  1882. size_t i;
  1883. #else
  1884. int numalts;
  1885. int i;
  1886. #endif
  1887. bool dnsmatched = FALSE;
  1888. bool ipmatched = FALSE;
  1889. /* get amount of alternatives, RFC2459 claims there MUST be at least
  1890. one, but we do not depend on it... */
  1891. numalts = sk_GENERAL_NAME_num(altnames);
  1892. /* loop through all alternatives - until a dnsmatch */
  1893. for(i = 0; (i < numalts) && !dnsmatched; i++) {
  1894. /* get a handle to alternative name number i */
  1895. const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
  1896. if(check->type == GEN_DNS)
  1897. dNSName = TRUE;
  1898. else if(check->type == GEN_IPADD)
  1899. iPAddress = TRUE;
  1900. /* only check alternatives of the same type the target is */
  1901. if(check->type == target) {
  1902. /* get data and length */
  1903. const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);
  1904. size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);
  1905. switch(target) {
  1906. case GEN_DNS: /* name/pattern comparison */
  1907. /* The OpenSSL manpage explicitly says: "In general it cannot be
  1908. assumed that the data returned by ASN1_STRING_data() is null
  1909. terminated or does not contain embedded nulls." But also that
  1910. "The actual format of the data will depend on the actual string
  1911. type itself: for example for an IA5String the data will be ASCII"
  1912. It has been however verified that in 0.9.6 and 0.9.7, IA5String
  1913. is always null-terminated.
  1914. */
  1915. if((altlen == strlen(altptr)) &&
  1916. /* if this is not true, there was an embedded zero in the name
  1917. string and we cannot match it. */
  1918. subj_alt_hostcheck(data, altptr, altlen,
  1919. peer->hostname, hostlen,
  1920. peer->dispname)) {
  1921. dnsmatched = TRUE;
  1922. }
  1923. break;
  1924. case GEN_IPADD: /* IP address comparison */
  1925. /* compare alternative IP address if the data chunk is the same size
  1926. our server IP address is */
  1927. if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {
  1928. ipmatched = TRUE;
  1929. infof(data,
  1930. " subjectAltName: host \"%s\" matched cert's IP address!",
  1931. peer->dispname);
  1932. }
  1933. break;
  1934. }
  1935. }
  1936. }
  1937. GENERAL_NAMES_free(altnames);
  1938. if(dnsmatched || ipmatched)
  1939. matched = TRUE;
  1940. }
  1941. if(matched)
  1942. /* an alternative name matched */
  1943. ;
  1944. else if(dNSName || iPAddress) {
  1945. const char *tname = (peer->type == CURL_SSL_PEER_DNS) ? "hostname" :
  1946. (peer->type == CURL_SSL_PEER_IPV4) ?
  1947. "ipv4 address" : "ipv6 address";
  1948. infof(data, " subjectAltName does not match %s %s", tname, peer->dispname);
  1949. failf(data, "SSL: no alternative certificate subject name matches "
  1950. "target %s '%s'", tname, peer->dispname);
  1951. result = CURLE_PEER_FAILED_VERIFICATION;
  1952. }
  1953. else {
  1954. /* we have to look to the last occurrence of a commonName in the
  1955. distinguished one to get the most significant one. */
  1956. int i = -1;
  1957. unsigned char *peer_CN = NULL;
  1958. int peerlen = 0;
  1959. /* The following is done because of a bug in 0.9.6b */
  1960. X509_NAME *name = X509_get_subject_name(server_cert);
  1961. if(name) {
  1962. int j;
  1963. while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)
  1964. i = j;
  1965. }
  1966. /* we have the name entry and we will now convert this to a string
  1967. that we can use for comparison. Doing this we support BMPstring,
  1968. UTF8, etc. */
  1969. if(i >= 0) {
  1970. ASN1_STRING *tmp =
  1971. X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
  1972. /* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input
  1973. is already UTF-8 encoded. We check for this case and copy the raw
  1974. string manually to avoid the problem. This code can be made
  1975. conditional in the future when OpenSSL has been fixed. */
  1976. if(tmp) {
  1977. if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {
  1978. peerlen = ASN1_STRING_length(tmp);
  1979. if(peerlen >= 0) {
  1980. peer_CN = OPENSSL_malloc(peerlen + 1);
  1981. if(peer_CN) {
  1982. memcpy(peer_CN, ASN1_STRING_get0_data(tmp), peerlen);
  1983. peer_CN[peerlen] = '\0';
  1984. }
  1985. else
  1986. result = CURLE_OUT_OF_MEMORY;
  1987. }
  1988. }
  1989. else /* not a UTF8 name */
  1990. peerlen = ASN1_STRING_to_UTF8(&peer_CN, tmp);
  1991. if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != peerlen)) {
  1992. /* there was a terminating zero before the end of string, this
  1993. cannot match and we return failure! */
  1994. failf(data, "SSL: illegal cert name field");
  1995. result = CURLE_PEER_FAILED_VERIFICATION;
  1996. }
  1997. }
  1998. }
  1999. if(result)
  2000. /* error already detected, pass through */
  2001. ;
  2002. else if(!peer_CN) {
  2003. failf(data,
  2004. "SSL: unable to obtain common name from peer certificate");
  2005. result = CURLE_PEER_FAILED_VERIFICATION;
  2006. }
  2007. else if(!Curl_cert_hostcheck((const char *)peer_CN,
  2008. peerlen, peer->hostname, hostlen)) {
  2009. failf(data, "SSL: certificate subject name '%s' does not match "
  2010. "target hostname '%s'", peer_CN, peer->dispname);
  2011. result = CURLE_PEER_FAILED_VERIFICATION;
  2012. }
  2013. else {
  2014. infof(data, " common name: %s (matched)", peer_CN);
  2015. }
  2016. if(peer_CN)
  2017. OPENSSL_free(peer_CN);
  2018. }
  2019. return result;
  2020. }
  2021. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  2022. !defined(OPENSSL_NO_OCSP)
  2023. static CURLcode verifystatus(struct Curl_cfilter *cf,
  2024. struct Curl_easy *data,
  2025. struct ossl_ctx *octx)
  2026. {
  2027. int i, ocsp_status;
  2028. #if defined(OPENSSL_IS_AWSLC)
  2029. const uint8_t *status;
  2030. #else
  2031. unsigned char *status;
  2032. #endif
  2033. const unsigned char *p;
  2034. CURLcode result = CURLE_OK;
  2035. OCSP_RESPONSE *rsp = NULL;
  2036. OCSP_BASICRESP *br = NULL;
  2037. X509_STORE *st = NULL;
  2038. STACK_OF(X509) *ch = NULL;
  2039. X509 *cert;
  2040. OCSP_CERTID *id = NULL;
  2041. int cert_status, crl_reason;
  2042. ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd;
  2043. int ret;
  2044. long len;
  2045. (void)cf;
  2046. DEBUGASSERT(octx);
  2047. len = (long)SSL_get_tlsext_status_ocsp_resp(octx->ssl, &status);
  2048. if(!status) {
  2049. failf(data, "No OCSP response received");
  2050. result = CURLE_SSL_INVALIDCERTSTATUS;
  2051. goto end;
  2052. }
  2053. p = status;
  2054. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  2055. if(!rsp) {
  2056. failf(data, "Invalid OCSP response");
  2057. result = CURLE_SSL_INVALIDCERTSTATUS;
  2058. goto end;
  2059. }
  2060. ocsp_status = OCSP_response_status(rsp);
  2061. if(ocsp_status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  2062. failf(data, "Invalid OCSP response status: %s (%d)",
  2063. OCSP_response_status_str(ocsp_status), ocsp_status);
  2064. result = CURLE_SSL_INVALIDCERTSTATUS;
  2065. goto end;
  2066. }
  2067. br = OCSP_response_get1_basic(rsp);
  2068. if(!br) {
  2069. failf(data, "Invalid OCSP response");
  2070. result = CURLE_SSL_INVALIDCERTSTATUS;
  2071. goto end;
  2072. }
  2073. ch = SSL_get_peer_cert_chain(octx->ssl);
  2074. if(!ch) {
  2075. failf(data, "Could not get peer certificate chain");
  2076. result = CURLE_SSL_INVALIDCERTSTATUS;
  2077. goto end;
  2078. }
  2079. st = SSL_CTX_get_cert_store(octx->ssl_ctx);
  2080. #if ((OPENSSL_VERSION_NUMBER <= 0x1000201fL) /* Fixed after 1.0.2a */ || \
  2081. (defined(LIBRESSL_VERSION_NUMBER) && \
  2082. LIBRESSL_VERSION_NUMBER <= 0x2040200fL))
  2083. /* The authorized responder cert in the OCSP response MUST be signed by the
  2084. peer cert's issuer (see RFC6960 section 4.2.2.2). If that is a root cert,
  2085. no problem, but if it is an intermediate cert OpenSSL has a bug where it
  2086. expects this issuer to be present in the chain embedded in the OCSP
  2087. response. So we add it if necessary. */
  2088. /* First make sure the peer cert chain includes both a peer and an issuer,
  2089. and the OCSP response contains a responder cert. */
  2090. if(sk_X509_num(ch) >= 2 && sk_X509_num(br->certs) >= 1) {
  2091. X509 *responder = sk_X509_value(br->certs, sk_X509_num(br->certs) - 1);
  2092. /* Find issuer of responder cert and add it to the OCSP response chain */
  2093. for(i = 0; i < sk_X509_num(ch); i++) {
  2094. X509 *issuer = sk_X509_value(ch, i);
  2095. if(X509_check_issued(issuer, responder) == X509_V_OK) {
  2096. if(!OCSP_basic_add1_cert(br, issuer)) {
  2097. failf(data, "Could not add issuer cert to OCSP response");
  2098. result = CURLE_SSL_INVALIDCERTSTATUS;
  2099. goto end;
  2100. }
  2101. }
  2102. }
  2103. }
  2104. #endif
  2105. if(OCSP_basic_verify(br, ch, st, 0) <= 0) {
  2106. failf(data, "OCSP response verification failed");
  2107. result = CURLE_SSL_INVALIDCERTSTATUS;
  2108. goto end;
  2109. }
  2110. /* Compute the certificate's ID */
  2111. cert = SSL_get1_peer_certificate(octx->ssl);
  2112. if(!cert) {
  2113. failf(data, "Error getting peer certificate");
  2114. result = CURLE_SSL_INVALIDCERTSTATUS;
  2115. goto end;
  2116. }
  2117. for(i = 0; i < (int)sk_X509_num(ch); i++) {
  2118. X509 *issuer = sk_X509_value(ch, (ossl_valsize_t)i);
  2119. if(X509_check_issued(issuer, cert) == X509_V_OK) {
  2120. id = OCSP_cert_to_id(EVP_sha1(), cert, issuer);
  2121. break;
  2122. }
  2123. }
  2124. X509_free(cert);
  2125. if(!id) {
  2126. failf(data, "Error computing OCSP ID");
  2127. result = CURLE_SSL_INVALIDCERTSTATUS;
  2128. goto end;
  2129. }
  2130. /* Find the single OCSP response corresponding to the certificate ID */
  2131. ret = OCSP_resp_find_status(br, id, &cert_status, &crl_reason, &rev,
  2132. &thisupd, &nextupd);
  2133. OCSP_CERTID_free(id);
  2134. if(ret != 1) {
  2135. failf(data, "Could not find certificate ID in OCSP response");
  2136. result = CURLE_SSL_INVALIDCERTSTATUS;
  2137. goto end;
  2138. }
  2139. /* Validate the corresponding single OCSP response */
  2140. if(!OCSP_check_validity(thisupd, nextupd, 300L, -1L)) {
  2141. failf(data, "OCSP response has expired");
  2142. result = CURLE_SSL_INVALIDCERTSTATUS;
  2143. goto end;
  2144. }
  2145. infof(data, "SSL certificate status: %s (%d)",
  2146. OCSP_cert_status_str(cert_status), cert_status);
  2147. switch(cert_status) {
  2148. case V_OCSP_CERTSTATUS_GOOD:
  2149. break;
  2150. case V_OCSP_CERTSTATUS_REVOKED:
  2151. result = CURLE_SSL_INVALIDCERTSTATUS;
  2152. failf(data, "SSL certificate revocation reason: %s (%d)",
  2153. OCSP_crl_reason_str(crl_reason), crl_reason);
  2154. goto end;
  2155. case V_OCSP_CERTSTATUS_UNKNOWN:
  2156. default:
  2157. result = CURLE_SSL_INVALIDCERTSTATUS;
  2158. goto end;
  2159. }
  2160. end:
  2161. if(br)
  2162. OCSP_BASICRESP_free(br);
  2163. OCSP_RESPONSE_free(rsp);
  2164. return result;
  2165. }
  2166. #endif
  2167. #endif /* USE_OPENSSL */
  2168. /* The SSL_CTRL_SET_MSG_CALLBACK does not exist in ancient OpenSSL versions
  2169. and thus this cannot be done there. */
  2170. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  2171. static const char *ssl_msg_type(int ssl_ver, int msg)
  2172. {
  2173. #ifdef SSL2_VERSION_MAJOR
  2174. if(ssl_ver == SSL2_VERSION_MAJOR) {
  2175. switch(msg) {
  2176. case SSL2_MT_ERROR:
  2177. return "Error";
  2178. case SSL2_MT_CLIENT_HELLO:
  2179. return "Client hello";
  2180. case SSL2_MT_CLIENT_MASTER_KEY:
  2181. return "Client key";
  2182. case SSL2_MT_CLIENT_FINISHED:
  2183. return "Client finished";
  2184. case SSL2_MT_SERVER_HELLO:
  2185. return "Server hello";
  2186. case SSL2_MT_SERVER_VERIFY:
  2187. return "Server verify";
  2188. case SSL2_MT_SERVER_FINISHED:
  2189. return "Server finished";
  2190. case SSL2_MT_REQUEST_CERTIFICATE:
  2191. return "Request CERT";
  2192. case SSL2_MT_CLIENT_CERTIFICATE:
  2193. return "Client CERT";
  2194. }
  2195. }
  2196. else
  2197. #endif
  2198. if(ssl_ver == SSL3_VERSION_MAJOR) {
  2199. switch(msg) {
  2200. case SSL3_MT_HELLO_REQUEST:
  2201. return "Hello request";
  2202. case SSL3_MT_CLIENT_HELLO:
  2203. return "Client hello";
  2204. case SSL3_MT_SERVER_HELLO:
  2205. return "Server hello";
  2206. #ifdef SSL3_MT_NEWSESSION_TICKET
  2207. case SSL3_MT_NEWSESSION_TICKET:
  2208. return "Newsession Ticket";
  2209. #endif
  2210. case SSL3_MT_CERTIFICATE:
  2211. return "Certificate";
  2212. case SSL3_MT_SERVER_KEY_EXCHANGE:
  2213. return "Server key exchange";
  2214. case SSL3_MT_CLIENT_KEY_EXCHANGE:
  2215. return "Client key exchange";
  2216. case SSL3_MT_CERTIFICATE_REQUEST:
  2217. return "Request CERT";
  2218. case SSL3_MT_SERVER_DONE:
  2219. return "Server finished";
  2220. case SSL3_MT_CERTIFICATE_VERIFY:
  2221. return "CERT verify";
  2222. case SSL3_MT_FINISHED:
  2223. return "Finished";
  2224. #ifdef SSL3_MT_CERTIFICATE_STATUS
  2225. case SSL3_MT_CERTIFICATE_STATUS:
  2226. return "Certificate Status";
  2227. #endif
  2228. #ifdef SSL3_MT_ENCRYPTED_EXTENSIONS
  2229. case SSL3_MT_ENCRYPTED_EXTENSIONS:
  2230. return "Encrypted Extensions";
  2231. #endif
  2232. #ifdef SSL3_MT_SUPPLEMENTAL_DATA
  2233. case SSL3_MT_SUPPLEMENTAL_DATA:
  2234. return "Supplemental data";
  2235. #endif
  2236. #ifdef SSL3_MT_END_OF_EARLY_DATA
  2237. case SSL3_MT_END_OF_EARLY_DATA:
  2238. return "End of early data";
  2239. #endif
  2240. #ifdef SSL3_MT_KEY_UPDATE
  2241. case SSL3_MT_KEY_UPDATE:
  2242. return "Key update";
  2243. #endif
  2244. #ifdef SSL3_MT_NEXT_PROTO
  2245. case SSL3_MT_NEXT_PROTO:
  2246. return "Next protocol";
  2247. #endif
  2248. #ifdef SSL3_MT_MESSAGE_HASH
  2249. case SSL3_MT_MESSAGE_HASH:
  2250. return "Message hash";
  2251. #endif
  2252. }
  2253. }
  2254. return "Unknown";
  2255. }
  2256. static const char *tls_rt_type(int type)
  2257. {
  2258. switch(type) {
  2259. #ifdef SSL3_RT_HEADER
  2260. case SSL3_RT_HEADER:
  2261. return "TLS header";
  2262. #endif
  2263. case SSL3_RT_CHANGE_CIPHER_SPEC:
  2264. return "TLS change cipher";
  2265. case SSL3_RT_ALERT:
  2266. return "TLS alert";
  2267. case SSL3_RT_HANDSHAKE:
  2268. return "TLS handshake";
  2269. case SSL3_RT_APPLICATION_DATA:
  2270. return "TLS app data";
  2271. default:
  2272. return "TLS Unknown";
  2273. }
  2274. }
  2275. /*
  2276. * Our callback from the SSL/TLS layers.
  2277. */
  2278. static void ossl_trace(int direction, int ssl_ver, int content_type,
  2279. const void *buf, size_t len, SSL *ssl,
  2280. void *userp)
  2281. {
  2282. const char *verstr = "???";
  2283. struct Curl_cfilter *cf = userp;
  2284. struct Curl_easy *data = NULL;
  2285. char unknown[32];
  2286. if(!cf)
  2287. return;
  2288. data = CF_DATA_CURRENT(cf);
  2289. if(!data || !data->set.fdebug || (direction && direction != 1))
  2290. return;
  2291. switch(ssl_ver) {
  2292. #ifdef SSL2_VERSION /* removed in recent versions */
  2293. case SSL2_VERSION:
  2294. verstr = "SSLv2";
  2295. break;
  2296. #endif
  2297. #ifdef SSL3_VERSION
  2298. case SSL3_VERSION:
  2299. verstr = "SSLv3";
  2300. break;
  2301. #endif
  2302. case TLS1_VERSION:
  2303. verstr = "TLSv1.0";
  2304. break;
  2305. #ifdef TLS1_1_VERSION
  2306. case TLS1_1_VERSION:
  2307. verstr = "TLSv1.1";
  2308. break;
  2309. #endif
  2310. #ifdef TLS1_2_VERSION
  2311. case TLS1_2_VERSION:
  2312. verstr = "TLSv1.2";
  2313. break;
  2314. #endif
  2315. #ifdef TLS1_3_VERSION
  2316. case TLS1_3_VERSION:
  2317. verstr = "TLSv1.3";
  2318. break;
  2319. #endif
  2320. case 0:
  2321. break;
  2322. default:
  2323. msnprintf(unknown, sizeof(unknown), "(%x)", ssl_ver);
  2324. verstr = unknown;
  2325. break;
  2326. }
  2327. /* Log progress for interesting records only (like Handshake or Alert), skip
  2328. * all raw record headers (content_type == SSL3_RT_HEADER or ssl_ver == 0).
  2329. * For TLS 1.3, skip notification of the decrypted inner Content-Type.
  2330. */
  2331. if(ssl_ver
  2332. #ifdef SSL3_RT_HEADER
  2333. && content_type != SSL3_RT_HEADER
  2334. #endif
  2335. #ifdef SSL3_RT_INNER_CONTENT_TYPE
  2336. && content_type != SSL3_RT_INNER_CONTENT_TYPE
  2337. #endif
  2338. ) {
  2339. const char *msg_name, *tls_rt_name;
  2340. char ssl_buf[1024];
  2341. int msg_type, txt_len;
  2342. /* the info given when the version is zero is not that useful for us */
  2343. ssl_ver >>= 8; /* check the upper 8 bits only below */
  2344. /* SSLv2 does not seem to have TLS record-type headers, so OpenSSL
  2345. * always pass-up content-type as 0. But the interesting message-type
  2346. * is at 'buf[0]'.
  2347. */
  2348. if(ssl_ver == SSL3_VERSION_MAJOR && content_type)
  2349. tls_rt_name = tls_rt_type(content_type);
  2350. else
  2351. tls_rt_name = "";
  2352. if(content_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  2353. msg_type = *(char *)buf;
  2354. msg_name = "Change cipher spec";
  2355. }
  2356. else if(content_type == SSL3_RT_ALERT) {
  2357. msg_type = (((char *)buf)[0] << 8) + ((char *)buf)[1];
  2358. msg_name = SSL_alert_desc_string_long(msg_type);
  2359. }
  2360. else {
  2361. msg_type = *(char *)buf;
  2362. msg_name = ssl_msg_type(ssl_ver, msg_type);
  2363. }
  2364. txt_len = msnprintf(ssl_buf, sizeof(ssl_buf),
  2365. "%s (%s), %s, %s (%d):\n",
  2366. verstr, direction?"OUT":"IN",
  2367. tls_rt_name, msg_name, msg_type);
  2368. if(0 <= txt_len && (unsigned)txt_len < sizeof(ssl_buf)) {
  2369. Curl_debug(data, CURLINFO_TEXT, ssl_buf, (size_t)txt_len);
  2370. }
  2371. }
  2372. Curl_debug(data, (direction == 1) ? CURLINFO_SSL_DATA_OUT :
  2373. CURLINFO_SSL_DATA_IN, (char *)buf, len);
  2374. (void) ssl;
  2375. }
  2376. #endif
  2377. #ifdef USE_OPENSSL
  2378. /* ====================================================== */
  2379. /* Check for OpenSSL 1.0.2 which has ALPN support. */
  2380. #undef HAS_ALPN
  2381. #if OPENSSL_VERSION_NUMBER >= 0x10002000L \
  2382. && !defined(OPENSSL_NO_TLSEXT)
  2383. # define HAS_ALPN 1
  2384. #endif
  2385. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
  2386. static CURLcode
  2387. ossl_set_ssl_version_min_max(struct Curl_cfilter *cf, SSL_CTX *ctx)
  2388. {
  2389. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2390. /* first, TLS min version... */
  2391. long curl_ssl_version_min = conn_config->version;
  2392. long curl_ssl_version_max;
  2393. /* convert curl min SSL version option to OpenSSL constant */
  2394. #if (defined(OPENSSL_IS_BORINGSSL) || \
  2395. defined(OPENSSL_IS_AWSLC) || \
  2396. defined(LIBRESSL_VERSION_NUMBER))
  2397. uint16_t ossl_ssl_version_min = 0;
  2398. uint16_t ossl_ssl_version_max = 0;
  2399. #else
  2400. long ossl_ssl_version_min = 0;
  2401. long ossl_ssl_version_max = 0;
  2402. #endif
  2403. switch(curl_ssl_version_min) {
  2404. case CURL_SSLVERSION_TLSv1: /* TLS 1.x */
  2405. case CURL_SSLVERSION_TLSv1_0:
  2406. ossl_ssl_version_min = TLS1_VERSION;
  2407. break;
  2408. case CURL_SSLVERSION_TLSv1_1:
  2409. ossl_ssl_version_min = TLS1_1_VERSION;
  2410. break;
  2411. case CURL_SSLVERSION_TLSv1_2:
  2412. ossl_ssl_version_min = TLS1_2_VERSION;
  2413. break;
  2414. case CURL_SSLVERSION_TLSv1_3:
  2415. #ifdef TLS1_3_VERSION
  2416. ossl_ssl_version_min = TLS1_3_VERSION;
  2417. break;
  2418. #else
  2419. return CURLE_NOT_BUILT_IN;
  2420. #endif
  2421. }
  2422. /* CURL_SSLVERSION_DEFAULT means that no option was selected.
  2423. We do not want to pass 0 to SSL_CTX_set_min_proto_version as
  2424. it would enable all versions down to the lowest supported by
  2425. the library.
  2426. So we skip this, and stay with the library default
  2427. */
  2428. if(curl_ssl_version_min != CURL_SSLVERSION_DEFAULT) {
  2429. if(!SSL_CTX_set_min_proto_version(ctx, ossl_ssl_version_min)) {
  2430. return CURLE_SSL_CONNECT_ERROR;
  2431. }
  2432. }
  2433. /* ... then, TLS max version */
  2434. curl_ssl_version_max = (long)conn_config->version_max;
  2435. /* convert curl max SSL version option to OpenSSL constant */
  2436. switch(curl_ssl_version_max) {
  2437. case CURL_SSLVERSION_MAX_TLSv1_0:
  2438. ossl_ssl_version_max = TLS1_VERSION;
  2439. break;
  2440. case CURL_SSLVERSION_MAX_TLSv1_1:
  2441. ossl_ssl_version_max = TLS1_1_VERSION;
  2442. break;
  2443. case CURL_SSLVERSION_MAX_TLSv1_2:
  2444. ossl_ssl_version_max = TLS1_2_VERSION;
  2445. break;
  2446. #ifdef TLS1_3_VERSION
  2447. case CURL_SSLVERSION_MAX_TLSv1_3:
  2448. ossl_ssl_version_max = TLS1_3_VERSION;
  2449. break;
  2450. #endif
  2451. case CURL_SSLVERSION_MAX_NONE: /* none selected */
  2452. case CURL_SSLVERSION_MAX_DEFAULT: /* max selected */
  2453. default:
  2454. /* SSL_CTX_set_max_proto_version states that:
  2455. setting the maximum to 0 will enable
  2456. protocol versions up to the highest version
  2457. supported by the library */
  2458. ossl_ssl_version_max = 0;
  2459. break;
  2460. }
  2461. if(!SSL_CTX_set_max_proto_version(ctx, ossl_ssl_version_max)) {
  2462. return CURLE_SSL_CONNECT_ERROR;
  2463. }
  2464. return CURLE_OK;
  2465. }
  2466. #endif
  2467. #if defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)
  2468. typedef uint32_t ctx_option_t;
  2469. #elif OPENSSL_VERSION_NUMBER >= 0x30000000L
  2470. typedef uint64_t ctx_option_t;
  2471. #elif OPENSSL_VERSION_NUMBER >= 0x10100000L && \
  2472. !defined(LIBRESSL_VERSION_NUMBER)
  2473. typedef unsigned long ctx_option_t;
  2474. #else
  2475. typedef long ctx_option_t;
  2476. #endif
  2477. #if (OPENSSL_VERSION_NUMBER < 0x10100000L) /* 1.1.0 */
  2478. static CURLcode
  2479. ossl_set_ssl_version_min_max_legacy(ctx_option_t *ctx_options,
  2480. struct Curl_cfilter *cf,
  2481. struct Curl_easy *data)
  2482. {
  2483. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2484. long ssl_version = conn_config->version;
  2485. long ssl_version_max = conn_config->version_max;
  2486. (void) data; /* In case it is unused. */
  2487. switch(ssl_version) {
  2488. case CURL_SSLVERSION_TLSv1_3:
  2489. #ifdef TLS1_3_VERSION
  2490. {
  2491. struct ssl_connect_data *connssl = cf->ctx;
  2492. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  2493. DEBUGASSERT(octx);
  2494. SSL_CTX_set_max_proto_version(octx->ssl_ctx, TLS1_3_VERSION);
  2495. *ctx_options |= SSL_OP_NO_TLSv1_2;
  2496. }
  2497. #else
  2498. (void)ctx_options;
  2499. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  2500. return CURLE_NOT_BUILT_IN;
  2501. #endif
  2502. FALLTHROUGH();
  2503. case CURL_SSLVERSION_TLSv1_2:
  2504. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2505. *ctx_options |= SSL_OP_NO_TLSv1_1;
  2506. #else
  2507. failf(data, OSSL_PACKAGE " was built without TLS 1.2 support");
  2508. return CURLE_NOT_BUILT_IN;
  2509. #endif
  2510. FALLTHROUGH();
  2511. case CURL_SSLVERSION_TLSv1_1:
  2512. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2513. *ctx_options |= SSL_OP_NO_TLSv1;
  2514. #else
  2515. failf(data, OSSL_PACKAGE " was built without TLS 1.1 support");
  2516. return CURLE_NOT_BUILT_IN;
  2517. #endif
  2518. FALLTHROUGH();
  2519. case CURL_SSLVERSION_TLSv1_0:
  2520. case CURL_SSLVERSION_TLSv1:
  2521. break;
  2522. }
  2523. switch(ssl_version_max) {
  2524. case CURL_SSLVERSION_MAX_TLSv1_0:
  2525. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2526. *ctx_options |= SSL_OP_NO_TLSv1_1;
  2527. #endif
  2528. FALLTHROUGH();
  2529. case CURL_SSLVERSION_MAX_TLSv1_1:
  2530. #if OPENSSL_VERSION_NUMBER >= 0x1000100FL
  2531. *ctx_options |= SSL_OP_NO_TLSv1_2;
  2532. #endif
  2533. FALLTHROUGH();
  2534. case CURL_SSLVERSION_MAX_TLSv1_2:
  2535. #ifdef TLS1_3_VERSION
  2536. *ctx_options |= SSL_OP_NO_TLSv1_3;
  2537. #endif
  2538. break;
  2539. case CURL_SSLVERSION_MAX_TLSv1_3:
  2540. #ifdef TLS1_3_VERSION
  2541. break;
  2542. #else
  2543. failf(data, OSSL_PACKAGE " was built without TLS 1.3 support");
  2544. return CURLE_NOT_BUILT_IN;
  2545. #endif
  2546. }
  2547. return CURLE_OK;
  2548. }
  2549. #endif
  2550. CURLcode Curl_ossl_add_session(struct Curl_cfilter *cf,
  2551. struct Curl_easy *data,
  2552. const struct ssl_peer *peer,
  2553. SSL_SESSION *session)
  2554. {
  2555. const struct ssl_config_data *config;
  2556. CURLcode result = CURLE_OK;
  2557. if(!cf || !data)
  2558. goto out;
  2559. config = Curl_ssl_cf_get_config(cf, data);
  2560. if(config->primary.cache_session) {
  2561. Curl_ssl_sessionid_lock(data);
  2562. result = Curl_ssl_set_sessionid(cf, data, peer, session, 0,
  2563. ossl_session_free);
  2564. session = NULL; /* call has taken ownership */
  2565. Curl_ssl_sessionid_unlock(data);
  2566. }
  2567. out:
  2568. if(session)
  2569. ossl_session_free(session, 0);
  2570. return result;
  2571. }
  2572. /* The "new session" callback must return zero if the session can be removed
  2573. * or non-zero if the session has been put into the session cache.
  2574. */
  2575. static int ossl_new_session_cb(SSL *ssl, SSL_SESSION *ssl_sessionid)
  2576. {
  2577. struct Curl_cfilter *cf;
  2578. struct Curl_easy *data;
  2579. struct ssl_connect_data *connssl;
  2580. cf = (struct Curl_cfilter*) SSL_get_app_data(ssl);
  2581. connssl = cf? cf->ctx : NULL;
  2582. data = connssl? CF_DATA_CURRENT(cf) : NULL;
  2583. Curl_ossl_add_session(cf, data, &connssl->peer, ssl_sessionid);
  2584. return 1;
  2585. }
  2586. static CURLcode load_cacert_from_memory(X509_STORE *store,
  2587. const struct curl_blob *ca_info_blob)
  2588. {
  2589. /* these need to be freed at the end */
  2590. BIO *cbio = NULL;
  2591. STACK_OF(X509_INFO) *inf = NULL;
  2592. /* everything else is just a reference */
  2593. int i, count = 0;
  2594. X509_INFO *itmp = NULL;
  2595. if(ca_info_blob->len > (size_t)INT_MAX)
  2596. return CURLE_SSL_CACERT_BADFILE;
  2597. cbio = BIO_new_mem_buf(ca_info_blob->data, (int)ca_info_blob->len);
  2598. if(!cbio)
  2599. return CURLE_OUT_OF_MEMORY;
  2600. inf = PEM_X509_INFO_read_bio(cbio, NULL, NULL, NULL);
  2601. if(!inf) {
  2602. BIO_free(cbio);
  2603. return CURLE_SSL_CACERT_BADFILE;
  2604. }
  2605. /* add each entry from PEM file to x509_store */
  2606. for(i = 0; i < (int)sk_X509_INFO_num(inf); ++i) {
  2607. itmp = sk_X509_INFO_value(inf, (ossl_valsize_t)i);
  2608. if(itmp->x509) {
  2609. if(X509_STORE_add_cert(store, itmp->x509)) {
  2610. ++count;
  2611. }
  2612. else {
  2613. /* set count to 0 to return an error */
  2614. count = 0;
  2615. break;
  2616. }
  2617. }
  2618. if(itmp->crl) {
  2619. if(X509_STORE_add_crl(store, itmp->crl)) {
  2620. ++count;
  2621. }
  2622. else {
  2623. /* set count to 0 to return an error */
  2624. count = 0;
  2625. break;
  2626. }
  2627. }
  2628. }
  2629. sk_X509_INFO_pop_free(inf, X509_INFO_free);
  2630. BIO_free(cbio);
  2631. /* if we did not end up importing anything, treat that as an error */
  2632. return (count > 0) ? CURLE_OK : CURLE_SSL_CACERT_BADFILE;
  2633. }
  2634. #if defined(USE_WIN32_CRYPTO)
  2635. static CURLcode import_windows_cert_store(struct Curl_easy *data,
  2636. const char *name,
  2637. X509_STORE *store,
  2638. bool *imported)
  2639. {
  2640. CURLcode result = CURLE_OK;
  2641. HCERTSTORE hStore;
  2642. *imported = false;
  2643. hStore = CertOpenSystemStoreA(0, name);
  2644. if(hStore) {
  2645. PCCERT_CONTEXT pContext = NULL;
  2646. /* The array of enhanced key usage OIDs will vary per certificate and
  2647. is declared outside of the loop so that rather than malloc/free each
  2648. iteration we can grow it with realloc, when necessary. */
  2649. CERT_ENHKEY_USAGE *enhkey_usage = NULL;
  2650. DWORD enhkey_usage_size = 0;
  2651. /* This loop makes a best effort to import all valid certificates from
  2652. the MS root store. If a certificate cannot be imported it is
  2653. skipped. 'result' is used to store only hard-fail conditions (such
  2654. as out of memory) that cause an early break. */
  2655. result = CURLE_OK;
  2656. for(;;) {
  2657. X509 *x509;
  2658. FILETIME now;
  2659. BYTE key_usage[2];
  2660. DWORD req_size;
  2661. const unsigned char *encoded_cert;
  2662. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2663. char cert_name[256];
  2664. #endif
  2665. pContext = CertEnumCertificatesInStore(hStore, pContext);
  2666. if(!pContext)
  2667. break;
  2668. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2669. if(!CertGetNameStringA(pContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0,
  2670. NULL, cert_name, sizeof(cert_name))) {
  2671. strcpy(cert_name, "Unknown");
  2672. }
  2673. infof(data, "SSL: Checking cert \"%s\"", cert_name);
  2674. #endif
  2675. encoded_cert = (const unsigned char *)pContext->pbCertEncoded;
  2676. if(!encoded_cert)
  2677. continue;
  2678. GetSystemTimeAsFileTime(&now);
  2679. if(CompareFileTime(&pContext->pCertInfo->NotBefore, &now) > 0 ||
  2680. CompareFileTime(&now, &pContext->pCertInfo->NotAfter) > 0)
  2681. continue;
  2682. /* If key usage exists check for signing attribute */
  2683. if(CertGetIntendedKeyUsage(pContext->dwCertEncodingType,
  2684. pContext->pCertInfo,
  2685. key_usage, sizeof(key_usage))) {
  2686. if(!(key_usage[0] & CERT_KEY_CERT_SIGN_KEY_USAGE))
  2687. continue;
  2688. }
  2689. else if(GetLastError())
  2690. continue;
  2691. /* If enhanced key usage exists check for server auth attribute.
  2692. *
  2693. * Note "In a Microsoft environment, a certificate might also have
  2694. * EKU extended properties that specify valid uses for the
  2695. * certificate." The call below checks both, and behavior varies
  2696. * depending on what is found. For more details see
  2697. * CertGetEnhancedKeyUsage doc.
  2698. */
  2699. if(CertGetEnhancedKeyUsage(pContext, 0, NULL, &req_size)) {
  2700. if(req_size && req_size > enhkey_usage_size) {
  2701. void *tmp = realloc(enhkey_usage, req_size);
  2702. if(!tmp) {
  2703. failf(data, "SSL: Out of memory allocating for OID list");
  2704. result = CURLE_OUT_OF_MEMORY;
  2705. break;
  2706. }
  2707. enhkey_usage = (CERT_ENHKEY_USAGE *)tmp;
  2708. enhkey_usage_size = req_size;
  2709. }
  2710. if(CertGetEnhancedKeyUsage(pContext, 0, enhkey_usage, &req_size)) {
  2711. if(!enhkey_usage->cUsageIdentifier) {
  2712. /* "If GetLastError returns CRYPT_E_NOT_FOUND, the certificate
  2713. is good for all uses. If it returns zero, the certificate
  2714. has no valid uses." */
  2715. if((HRESULT)GetLastError() != CRYPT_E_NOT_FOUND)
  2716. continue;
  2717. }
  2718. else {
  2719. DWORD i;
  2720. bool found = false;
  2721. for(i = 0; i < enhkey_usage->cUsageIdentifier; ++i) {
  2722. if(!strcmp("1.3.6.1.5.5.7.3.1" /* OID server auth */,
  2723. enhkey_usage->rgpszUsageIdentifier[i])) {
  2724. found = true;
  2725. break;
  2726. }
  2727. }
  2728. if(!found)
  2729. continue;
  2730. }
  2731. }
  2732. else
  2733. continue;
  2734. }
  2735. else
  2736. continue;
  2737. x509 = d2i_X509(NULL, &encoded_cert, (long)pContext->cbCertEncoded);
  2738. if(!x509)
  2739. continue;
  2740. /* Try to import the certificate. This may fail for legitimate
  2741. reasons such as duplicate certificate, which is allowed by MS but
  2742. not OpenSSL. */
  2743. if(X509_STORE_add_cert(store, x509) == 1) {
  2744. #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS)
  2745. infof(data, "SSL: Imported cert \"%s\"", cert_name);
  2746. #endif
  2747. *imported = true;
  2748. }
  2749. X509_free(x509);
  2750. }
  2751. free(enhkey_usage);
  2752. CertFreeCertificateContext(pContext);
  2753. CertCloseStore(hStore, 0);
  2754. if(result)
  2755. return result;
  2756. }
  2757. return result;
  2758. }
  2759. #endif
  2760. static CURLcode populate_x509_store(struct Curl_cfilter *cf,
  2761. struct Curl_easy *data,
  2762. X509_STORE *store)
  2763. {
  2764. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2765. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  2766. CURLcode result = CURLE_OK;
  2767. X509_LOOKUP *lookup = NULL;
  2768. const struct curl_blob *ca_info_blob = conn_config->ca_info_blob;
  2769. const char * const ssl_cafile =
  2770. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  2771. (ca_info_blob ? NULL : conn_config->CAfile);
  2772. const char * const ssl_capath = conn_config->CApath;
  2773. const char * const ssl_crlfile = ssl_config->primary.CRLfile;
  2774. const bool verifypeer = conn_config->verifypeer;
  2775. bool imported_native_ca = false;
  2776. bool imported_ca_info_blob = false;
  2777. CURL_TRC_CF(data, cf, "populate_x509_store, path=%s, blob=%d",
  2778. ssl_cafile? ssl_cafile : "none", !!ca_info_blob);
  2779. if(!store)
  2780. return CURLE_OUT_OF_MEMORY;
  2781. if(verifypeer) {
  2782. #if defined(USE_WIN32_CRYPTO)
  2783. /* Import certificates from the Windows root certificate store if
  2784. requested.
  2785. https://stackoverflow.com/questions/9507184/
  2786. https://github.com/d3x0r/SACK/blob/master/src/netlib/ssl_layer.c#L1037
  2787. https://datatracker.ietf.org/doc/html/rfc5280 */
  2788. if(ssl_config->native_ca_store) {
  2789. const char *storeNames[] = {
  2790. "ROOT", /* Trusted Root Certification Authorities */
  2791. "CA" /* Intermediate Certification Authorities */
  2792. };
  2793. size_t i;
  2794. for(i = 0; i < ARRAYSIZE(storeNames); ++i) {
  2795. bool imported = false;
  2796. result = import_windows_cert_store(data, storeNames[i], store,
  2797. &imported);
  2798. if(result)
  2799. return result;
  2800. if(imported) {
  2801. infof(data, "successfully imported Windows %s store", storeNames[i]);
  2802. imported_native_ca = true;
  2803. }
  2804. else
  2805. infof(data, "error importing Windows %s store, continuing anyway",
  2806. storeNames[i]);
  2807. }
  2808. }
  2809. #endif
  2810. if(ca_info_blob) {
  2811. result = load_cacert_from_memory(store, ca_info_blob);
  2812. if(result) {
  2813. failf(data, "error importing CA certificate blob");
  2814. return result;
  2815. }
  2816. else {
  2817. imported_ca_info_blob = true;
  2818. infof(data, "successfully imported CA certificate blob");
  2819. }
  2820. }
  2821. if(ssl_cafile || ssl_capath) {
  2822. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  2823. /* OpenSSL 3.0.0 has deprecated SSL_CTX_load_verify_locations */
  2824. if(ssl_cafile && !X509_STORE_load_file(store, ssl_cafile)) {
  2825. if(!imported_native_ca && !imported_ca_info_blob) {
  2826. /* Fail if we insist on successfully verifying the server. */
  2827. failf(data, "error setting certificate file: %s", ssl_cafile);
  2828. return CURLE_SSL_CACERT_BADFILE;
  2829. }
  2830. else
  2831. infof(data, "error setting certificate file, continuing anyway");
  2832. }
  2833. if(ssl_capath && !X509_STORE_load_path(store, ssl_capath)) {
  2834. if(!imported_native_ca && !imported_ca_info_blob) {
  2835. /* Fail if we insist on successfully verifying the server. */
  2836. failf(data, "error setting certificate path: %s", ssl_capath);
  2837. return CURLE_SSL_CACERT_BADFILE;
  2838. }
  2839. else
  2840. infof(data, "error setting certificate path, continuing anyway");
  2841. }
  2842. #else
  2843. /* tell OpenSSL where to find CA certificates that are used to verify the
  2844. server's certificate. */
  2845. if(!X509_STORE_load_locations(store, ssl_cafile, ssl_capath)) {
  2846. if(!imported_native_ca && !imported_ca_info_blob) {
  2847. /* Fail if we insist on successfully verifying the server. */
  2848. failf(data, "error setting certificate verify locations:"
  2849. " CAfile: %s CApath: %s",
  2850. ssl_cafile ? ssl_cafile : "none",
  2851. ssl_capath ? ssl_capath : "none");
  2852. return CURLE_SSL_CACERT_BADFILE;
  2853. }
  2854. else {
  2855. infof(data, "error setting certificate verify locations,"
  2856. " continuing anyway");
  2857. }
  2858. }
  2859. #endif
  2860. infof(data, " CAfile: %s", ssl_cafile ? ssl_cafile : "none");
  2861. infof(data, " CApath: %s", ssl_capath ? ssl_capath : "none");
  2862. }
  2863. #ifdef CURL_CA_FALLBACK
  2864. if(!ssl_cafile && !ssl_capath &&
  2865. !imported_native_ca && !imported_ca_info_blob) {
  2866. /* verifying the peer without any CA certificates will not
  2867. work so use OpenSSL's built-in default as fallback */
  2868. X509_STORE_set_default_paths(store);
  2869. }
  2870. #endif
  2871. }
  2872. if(ssl_crlfile) {
  2873. /* tell OpenSSL where to find CRL file that is used to check certificate
  2874. * revocation */
  2875. lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  2876. if(!lookup ||
  2877. (!X509_load_crl_file(lookup, ssl_crlfile, X509_FILETYPE_PEM)) ) {
  2878. failf(data, "error loading CRL file: %s", ssl_crlfile);
  2879. return CURLE_SSL_CRL_BADFILE;
  2880. }
  2881. /* Everything is fine. */
  2882. infof(data, "successfully loaded CRL file:");
  2883. X509_STORE_set_flags(store,
  2884. X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
  2885. infof(data, " CRLfile: %s", ssl_crlfile);
  2886. }
  2887. if(verifypeer) {
  2888. /* Try building a chain using issuers in the trusted store first to avoid
  2889. problems with server-sent legacy intermediates. Newer versions of
  2890. OpenSSL do alternate chain checking by default but we do not know how to
  2891. determine that in a reliable manner.
  2892. https://web.archive.org/web/20190422050538/
  2893. rt.openssl.org/Ticket/Display.html?id=3621
  2894. */
  2895. #if defined(X509_V_FLAG_TRUSTED_FIRST)
  2896. X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
  2897. #endif
  2898. #ifdef X509_V_FLAG_PARTIAL_CHAIN
  2899. if(!ssl_config->no_partialchain && !ssl_crlfile) {
  2900. /* Have intermediate certificates in the trust store be treated as
  2901. trust-anchors, in the same way as self-signed root CA certificates
  2902. are. This allows users to verify servers using the intermediate cert
  2903. only, instead of needing the whole chain.
  2904. Due to OpenSSL bug https://github.com/openssl/openssl/issues/5081 we
  2905. cannot do partial chains with a CRL check.
  2906. */
  2907. X509_STORE_set_flags(store, X509_V_FLAG_PARTIAL_CHAIN);
  2908. }
  2909. #endif
  2910. }
  2911. return result;
  2912. }
  2913. #if defined(HAVE_SSL_X509_STORE_SHARE)
  2914. /* key to use at `multi->proto_hash` */
  2915. #define MPROTO_OSSL_X509_KEY "tls:ossl:x509:share"
  2916. struct ossl_x509_share {
  2917. char *CAfile; /* CAfile path used to generate X509 store */
  2918. X509_STORE *store; /* cached X509 store or NULL if none */
  2919. struct curltime time; /* when the cached store was created */
  2920. };
  2921. static void oss_x509_share_free(void *key, size_t key_len, void *p)
  2922. {
  2923. struct ossl_x509_share *share = p;
  2924. DEBUGASSERT(key_len == (sizeof(MPROTO_OSSL_X509_KEY)-1));
  2925. DEBUGASSERT(!memcmp(MPROTO_OSSL_X509_KEY, key, key_len));
  2926. (void)key;
  2927. (void)key_len;
  2928. if(share->store) {
  2929. X509_STORE_free(share->store);
  2930. }
  2931. free(share->CAfile);
  2932. free(share);
  2933. }
  2934. static bool
  2935. cached_x509_store_expired(const struct Curl_easy *data,
  2936. const struct ossl_x509_share *mb)
  2937. {
  2938. const struct ssl_general_config *cfg = &data->set.general_ssl;
  2939. if(cfg->ca_cache_timeout < 0)
  2940. return FALSE;
  2941. else {
  2942. struct curltime now = Curl_now();
  2943. timediff_t elapsed_ms = Curl_timediff(now, mb->time);
  2944. timediff_t timeout_ms = cfg->ca_cache_timeout * (timediff_t)1000;
  2945. return elapsed_ms >= timeout_ms;
  2946. }
  2947. }
  2948. static bool
  2949. cached_x509_store_different(struct Curl_cfilter *cf,
  2950. const struct ossl_x509_share *mb)
  2951. {
  2952. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2953. if(!mb->CAfile || !conn_config->CAfile)
  2954. return mb->CAfile != conn_config->CAfile;
  2955. return strcmp(mb->CAfile, conn_config->CAfile);
  2956. }
  2957. static X509_STORE *get_cached_x509_store(struct Curl_cfilter *cf,
  2958. const struct Curl_easy *data)
  2959. {
  2960. struct Curl_multi *multi = data->multi;
  2961. struct ossl_x509_share *share;
  2962. X509_STORE *store = NULL;
  2963. DEBUGASSERT(multi);
  2964. share = multi? Curl_hash_pick(&multi->proto_hash,
  2965. (void *)MPROTO_OSSL_X509_KEY,
  2966. sizeof(MPROTO_OSSL_X509_KEY)-1) : NULL;
  2967. if(share && share->store &&
  2968. !cached_x509_store_expired(data, share) &&
  2969. !cached_x509_store_different(cf, share)) {
  2970. store = share->store;
  2971. }
  2972. return store;
  2973. }
  2974. static void set_cached_x509_store(struct Curl_cfilter *cf,
  2975. const struct Curl_easy *data,
  2976. X509_STORE *store)
  2977. {
  2978. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2979. struct Curl_multi *multi = data->multi;
  2980. struct ossl_x509_share *share;
  2981. DEBUGASSERT(multi);
  2982. if(!multi)
  2983. return;
  2984. share = Curl_hash_pick(&multi->proto_hash,
  2985. (void *)MPROTO_OSSL_X509_KEY,
  2986. sizeof(MPROTO_OSSL_X509_KEY)-1);
  2987. if(!share) {
  2988. share = calloc(1, sizeof(*share));
  2989. if(!share)
  2990. return;
  2991. if(!Curl_hash_add2(&multi->proto_hash,
  2992. (void *)MPROTO_OSSL_X509_KEY,
  2993. sizeof(MPROTO_OSSL_X509_KEY)-1,
  2994. share, oss_x509_share_free)) {
  2995. free(share);
  2996. return;
  2997. }
  2998. }
  2999. if(X509_STORE_up_ref(store)) {
  3000. char *CAfile = NULL;
  3001. if(conn_config->CAfile) {
  3002. CAfile = strdup(conn_config->CAfile);
  3003. if(!CAfile) {
  3004. X509_STORE_free(store);
  3005. return;
  3006. }
  3007. }
  3008. if(share->store) {
  3009. X509_STORE_free(share->store);
  3010. free(share->CAfile);
  3011. }
  3012. share->time = Curl_now();
  3013. share->store = store;
  3014. share->CAfile = CAfile;
  3015. }
  3016. }
  3017. CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
  3018. struct Curl_easy *data,
  3019. SSL_CTX *ssl_ctx)
  3020. {
  3021. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3022. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3023. CURLcode result = CURLE_OK;
  3024. X509_STORE *cached_store;
  3025. bool cache_criteria_met;
  3026. /* Consider the X509 store cacheable if it comes exclusively from a CAfile,
  3027. or no source is provided and we are falling back to OpenSSL's built-in
  3028. default. */
  3029. cache_criteria_met = (data->set.general_ssl.ca_cache_timeout != 0) &&
  3030. conn_config->verifypeer &&
  3031. !conn_config->CApath &&
  3032. !conn_config->ca_info_blob &&
  3033. !ssl_config->primary.CRLfile &&
  3034. !ssl_config->native_ca_store;
  3035. cached_store = get_cached_x509_store(cf, data);
  3036. if(cached_store && cache_criteria_met && X509_STORE_up_ref(cached_store)) {
  3037. SSL_CTX_set_cert_store(ssl_ctx, cached_store);
  3038. }
  3039. else {
  3040. X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
  3041. result = populate_x509_store(cf, data, store);
  3042. if(result == CURLE_OK && cache_criteria_met) {
  3043. set_cached_x509_store(cf, data, store);
  3044. }
  3045. }
  3046. return result;
  3047. }
  3048. #else /* HAVE_SSL_X509_STORE_SHARE */
  3049. CURLcode Curl_ssl_setup_x509_store(struct Curl_cfilter *cf,
  3050. struct Curl_easy *data,
  3051. SSL_CTX *ssl_ctx)
  3052. {
  3053. X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx);
  3054. return populate_x509_store(cf, data, store);
  3055. }
  3056. #endif /* HAVE_SSL_X509_STORE_SHARE */
  3057. CURLcode Curl_ossl_ctx_init(struct ossl_ctx *octx,
  3058. struct Curl_cfilter *cf,
  3059. struct Curl_easy *data,
  3060. struct ssl_peer *peer,
  3061. int transport, /* TCP or QUIC */
  3062. const unsigned char *alpn, size_t alpn_len,
  3063. Curl_ossl_ctx_setup_cb *cb_setup,
  3064. void *cb_user_data,
  3065. Curl_ossl_new_session_cb *cb_new_session,
  3066. void *ssl_user_data)
  3067. {
  3068. CURLcode result = CURLE_OK;
  3069. const char *ciphers;
  3070. SSL_METHOD_QUAL SSL_METHOD *req_method = NULL;
  3071. ctx_option_t ctx_options = 0;
  3072. void *ssl_sessionid = NULL;
  3073. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3074. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3075. const long int ssl_version_min = conn_config->version;
  3076. char * const ssl_cert = ssl_config->primary.clientcert;
  3077. const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
  3078. const char * const ssl_cert_type = ssl_config->cert_type;
  3079. const bool verifypeer = conn_config->verifypeer;
  3080. char error_buffer[256];
  3081. /* Make funny stuff to get random input */
  3082. result = ossl_seed(data);
  3083. if(result)
  3084. return result;
  3085. ssl_config->certverifyresult = !X509_V_OK;
  3086. switch(transport) {
  3087. case TRNSPRT_TCP:
  3088. /* check to see if we have been told to use an explicit SSL/TLS version */
  3089. switch(ssl_version_min) {
  3090. case CURL_SSLVERSION_DEFAULT:
  3091. case CURL_SSLVERSION_TLSv1:
  3092. case CURL_SSLVERSION_TLSv1_0:
  3093. case CURL_SSLVERSION_TLSv1_1:
  3094. case CURL_SSLVERSION_TLSv1_2:
  3095. case CURL_SSLVERSION_TLSv1_3:
  3096. /* it will be handled later with the context options */
  3097. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  3098. req_method = TLS_client_method();
  3099. #else
  3100. req_method = SSLv23_client_method();
  3101. #endif
  3102. break;
  3103. case CURL_SSLVERSION_SSLv2:
  3104. failf(data, "No SSLv2 support");
  3105. return CURLE_NOT_BUILT_IN;
  3106. case CURL_SSLVERSION_SSLv3:
  3107. failf(data, "No SSLv3 support");
  3108. return CURLE_NOT_BUILT_IN;
  3109. default:
  3110. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  3111. return CURLE_SSL_CONNECT_ERROR;
  3112. }
  3113. break;
  3114. case TRNSPRT_QUIC:
  3115. if(conn_config->version_max &&
  3116. (conn_config->version_max != CURL_SSLVERSION_MAX_TLSv1_3)) {
  3117. failf(data, "QUIC needs at least TLS version 1.3");
  3118. return CURLE_SSL_CONNECT_ERROR;
  3119. }
  3120. #ifdef USE_OPENSSL_QUIC
  3121. req_method = OSSL_QUIC_client_method();
  3122. #elif (OPENSSL_VERSION_NUMBER >= 0x10100000L)
  3123. req_method = TLS_method();
  3124. #else
  3125. req_method = SSLv23_client_method();
  3126. #endif
  3127. break;
  3128. default:
  3129. failf(data, "unsupported transport %d in SSL init", transport);
  3130. return CURLE_SSL_CONNECT_ERROR;
  3131. }
  3132. DEBUGASSERT(!octx->ssl_ctx);
  3133. octx->ssl_ctx = SSL_CTX_new(req_method);
  3134. if(!octx->ssl_ctx) {
  3135. failf(data, "SSL: could not create a context: %s",
  3136. ossl_strerror(ERR_peek_error(), error_buffer, sizeof(error_buffer)));
  3137. return CURLE_OUT_OF_MEMORY;
  3138. }
  3139. if(cb_setup) {
  3140. result = cb_setup(cf, data, cb_user_data);
  3141. if(result)
  3142. return result;
  3143. }
  3144. #ifdef SSL_CTRL_SET_MSG_CALLBACK
  3145. if(data->set.fdebug && data->set.verbose) {
  3146. /* the SSL trace callback is only used for verbose logging */
  3147. SSL_CTX_set_msg_callback(octx->ssl_ctx, ossl_trace);
  3148. SSL_CTX_set_msg_callback_arg(octx->ssl_ctx, cf);
  3149. }
  3150. #endif
  3151. /* OpenSSL contains code to work around lots of bugs and flaws in various
  3152. SSL-implementations. SSL_CTX_set_options() is used to enabled those
  3153. work-arounds. The manpage for this option states that SSL_OP_ALL enables
  3154. all the work-arounds and that "It is usually safe to use SSL_OP_ALL to
  3155. enable the bug workaround options if compatibility with somewhat broken
  3156. implementations is desired."
  3157. The "-no_ticket" option was introduced in OpenSSL 0.9.8j. it is a flag to
  3158. disable "rfc4507bis session ticket support". rfc4507bis was later turned
  3159. into the proper RFC5077: https://datatracker.ietf.org/doc/html/rfc5077
  3160. The enabled extension concerns the session management. I wonder how often
  3161. libcurl stops a connection and then resumes a TLS session. Also, sending
  3162. the session data is some overhead. I suggest that you just use your
  3163. proposed patch (which explicitly disables TICKET).
  3164. If someone writes an application with libcurl and OpenSSL who wants to
  3165. enable the feature, one can do this in the SSL callback.
  3166. SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG option enabling allowed proper
  3167. interoperability with web server Netscape Enterprise Server 2.0.1 which
  3168. was released back in 1996.
  3169. Due to CVE-2010-4180, option SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG has
  3170. become ineffective as of OpenSSL 0.9.8q and 1.0.0c. In order to mitigate
  3171. CVE-2010-4180 when using previous OpenSSL versions we no longer enable
  3172. this option regardless of OpenSSL version and SSL_OP_ALL definition.
  3173. OpenSSL added a work-around for a SSL 3.0/TLS 1.0 CBC vulnerability:
  3174. https://web.archive.org/web/20240114184648/openssl.org/~bodo/tls-cbc.txt.
  3175. In 0.9.6e they added a bit to SSL_OP_ALL that _disables_ that work-around
  3176. despite the fact that SSL_OP_ALL is documented to do "rather harmless"
  3177. workarounds. In order to keep the secure work-around, the
  3178. SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS bit must not be set.
  3179. */
  3180. ctx_options = SSL_OP_ALL;
  3181. #ifdef SSL_OP_NO_TICKET
  3182. ctx_options |= SSL_OP_NO_TICKET;
  3183. #endif
  3184. #ifdef SSL_OP_NO_COMPRESSION
  3185. ctx_options |= SSL_OP_NO_COMPRESSION;
  3186. #endif
  3187. #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
  3188. /* mitigate CVE-2010-4180 */
  3189. ctx_options &= ~(ctx_option_t)SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG;
  3190. #endif
  3191. #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
  3192. /* unless the user explicitly asks to allow the protocol vulnerability we
  3193. use the work-around */
  3194. if(!ssl_config->enable_beast)
  3195. ctx_options &= ~(ctx_option_t)SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
  3196. #endif
  3197. switch(ssl_version_min) {
  3198. case CURL_SSLVERSION_SSLv2:
  3199. case CURL_SSLVERSION_SSLv3:
  3200. return CURLE_NOT_BUILT_IN;
  3201. /* "--tlsv<x.y>" options mean TLS >= version <x.y> */
  3202. case CURL_SSLVERSION_DEFAULT:
  3203. case CURL_SSLVERSION_TLSv1: /* TLS >= version 1.0 */
  3204. case CURL_SSLVERSION_TLSv1_0: /* TLS >= version 1.0 */
  3205. case CURL_SSLVERSION_TLSv1_1: /* TLS >= version 1.1 */
  3206. case CURL_SSLVERSION_TLSv1_2: /* TLS >= version 1.2 */
  3207. case CURL_SSLVERSION_TLSv1_3: /* TLS >= version 1.3 */
  3208. /* asking for any TLS version as the minimum, means no SSL versions
  3209. allowed */
  3210. ctx_options |= SSL_OP_NO_SSLv2;
  3211. ctx_options |= SSL_OP_NO_SSLv3;
  3212. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) /* 1.1.0 */
  3213. result = ossl_set_ssl_version_min_max(cf, octx->ssl_ctx);
  3214. #else
  3215. result = ossl_set_ssl_version_min_max_legacy(&ctx_options, cf, data);
  3216. #endif
  3217. if(result != CURLE_OK)
  3218. return result;
  3219. break;
  3220. default:
  3221. failf(data, "Unrecognized parameter passed via CURLOPT_SSLVERSION");
  3222. return CURLE_SSL_CONNECT_ERROR;
  3223. }
  3224. SSL_CTX_set_options(octx->ssl_ctx, ctx_options);
  3225. #ifdef HAS_ALPN
  3226. if(alpn && alpn_len) {
  3227. if(SSL_CTX_set_alpn_protos(octx->ssl_ctx, alpn, (int)alpn_len)) {
  3228. failf(data, "Error setting ALPN");
  3229. return CURLE_SSL_CONNECT_ERROR;
  3230. }
  3231. }
  3232. #endif
  3233. if(ssl_cert || ssl_cert_blob || ssl_cert_type) {
  3234. if(!result &&
  3235. !cert_stuff(data, octx->ssl_ctx,
  3236. ssl_cert, ssl_cert_blob, ssl_cert_type,
  3237. ssl_config->key, ssl_config->key_blob,
  3238. ssl_config->key_type, ssl_config->key_passwd))
  3239. result = CURLE_SSL_CERTPROBLEM;
  3240. if(result)
  3241. /* failf() is already done in cert_stuff() */
  3242. return result;
  3243. }
  3244. ciphers = conn_config->cipher_list;
  3245. if(!ciphers && (peer->transport != TRNSPRT_QUIC))
  3246. ciphers = DEFAULT_CIPHER_SELECTION;
  3247. if(ciphers) {
  3248. if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, ciphers)) {
  3249. failf(data, "failed setting cipher list: %s", ciphers);
  3250. return CURLE_SSL_CIPHER;
  3251. }
  3252. infof(data, "Cipher selection: %s", ciphers);
  3253. }
  3254. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  3255. {
  3256. const char *ciphers13 = conn_config->cipher_list13;
  3257. if(ciphers13) {
  3258. if(!SSL_CTX_set_ciphersuites(octx->ssl_ctx, ciphers13)) {
  3259. failf(data, "failed setting TLS 1.3 cipher suite: %s", ciphers13);
  3260. return CURLE_SSL_CIPHER;
  3261. }
  3262. infof(data, "TLS 1.3 cipher selection: %s", ciphers13);
  3263. }
  3264. }
  3265. #endif
  3266. #ifdef HAVE_SSL_CTX_SET_POST_HANDSHAKE_AUTH
  3267. /* OpenSSL 1.1.1 requires clients to opt-in for PHA */
  3268. SSL_CTX_set_post_handshake_auth(octx->ssl_ctx, 1);
  3269. #endif
  3270. #ifdef HAVE_SSL_CTX_SET_EC_CURVES
  3271. {
  3272. const char *curves = conn_config->curves;
  3273. if(curves) {
  3274. if(!SSL_CTX_set1_curves_list(octx->ssl_ctx, curves)) {
  3275. failf(data, "failed setting curves list: '%s'", curves);
  3276. return CURLE_SSL_CIPHER;
  3277. }
  3278. }
  3279. }
  3280. #endif
  3281. #ifdef USE_OPENSSL_SRP
  3282. if(ssl_config->primary.username && Curl_auth_allowed_to_host(data)) {
  3283. char * const ssl_username = ssl_config->primary.username;
  3284. char * const ssl_password = ssl_config->primary.password;
  3285. infof(data, "Using TLS-SRP username: %s", ssl_username);
  3286. if(!SSL_CTX_set_srp_username(octx->ssl_ctx, ssl_username)) {
  3287. failf(data, "Unable to set SRP username");
  3288. return CURLE_BAD_FUNCTION_ARGUMENT;
  3289. }
  3290. if(!SSL_CTX_set_srp_password(octx->ssl_ctx, ssl_password)) {
  3291. failf(data, "failed setting SRP password");
  3292. return CURLE_BAD_FUNCTION_ARGUMENT;
  3293. }
  3294. if(!conn_config->cipher_list) {
  3295. infof(data, "Setting cipher list SRP");
  3296. if(!SSL_CTX_set_cipher_list(octx->ssl_ctx, "SRP")) {
  3297. failf(data, "failed setting SRP cipher list");
  3298. return CURLE_SSL_CIPHER;
  3299. }
  3300. }
  3301. }
  3302. #endif
  3303. /* OpenSSL always tries to verify the peer, this only says whether it should
  3304. * fail to connect if the verification fails, or if it should continue
  3305. * anyway. In the latter case the result of the verification is checked with
  3306. * SSL_get_verify_result() below. */
  3307. SSL_CTX_set_verify(octx->ssl_ctx,
  3308. verifypeer ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
  3309. /* Enable logging of secrets to the file specified in env SSLKEYLOGFILE. */
  3310. #ifdef HAVE_KEYLOG_CALLBACK
  3311. if(Curl_tls_keylog_enabled()) {
  3312. SSL_CTX_set_keylog_callback(octx->ssl_ctx, ossl_keylog_callback);
  3313. }
  3314. #endif
  3315. if(cb_new_session) {
  3316. /* Enable the session cache because it is a prerequisite for the
  3317. * "new session" callback. Use the "external storage" mode to prevent
  3318. * OpenSSL from creating an internal session cache.
  3319. */
  3320. SSL_CTX_set_session_cache_mode(octx->ssl_ctx,
  3321. SSL_SESS_CACHE_CLIENT |
  3322. SSL_SESS_CACHE_NO_INTERNAL);
  3323. SSL_CTX_sess_set_new_cb(octx->ssl_ctx, cb_new_session);
  3324. }
  3325. /* give application a chance to interfere with SSL set up. */
  3326. if(data->set.ssl.fsslctx) {
  3327. /* When a user callback is installed to modify the SSL_CTX,
  3328. * we need to do the full initialization before calling it.
  3329. * See: #11800 */
  3330. if(!octx->x509_store_setup) {
  3331. result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx);
  3332. if(result)
  3333. return result;
  3334. octx->x509_store_setup = TRUE;
  3335. }
  3336. Curl_set_in_callback(data, true);
  3337. result = (*data->set.ssl.fsslctx)(data, octx->ssl_ctx,
  3338. data->set.ssl.fsslctxp);
  3339. Curl_set_in_callback(data, false);
  3340. if(result) {
  3341. failf(data, "error signaled by ssl ctx callback");
  3342. return result;
  3343. }
  3344. }
  3345. /* Let's make an SSL structure */
  3346. if(octx->ssl)
  3347. SSL_free(octx->ssl);
  3348. octx->ssl = SSL_new(octx->ssl_ctx);
  3349. if(!octx->ssl) {
  3350. failf(data, "SSL: could not create a context (handle)");
  3351. return CURLE_OUT_OF_MEMORY;
  3352. }
  3353. SSL_set_app_data(octx->ssl, ssl_user_data);
  3354. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  3355. !defined(OPENSSL_NO_OCSP)
  3356. if(conn_config->verifystatus)
  3357. SSL_set_tlsext_status_type(octx->ssl, TLSEXT_STATUSTYPE_ocsp);
  3358. #endif
  3359. #if (defined(OPENSSL_IS_BORINGSSL) || defined(OPENSSL_IS_AWSLC)) && \
  3360. defined(ALLOW_RENEG)
  3361. SSL_set_renegotiate_mode(octx->ssl, ssl_renegotiate_freely);
  3362. #endif
  3363. SSL_set_connect_state(octx->ssl);
  3364. octx->server_cert = 0x0;
  3365. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  3366. if(peer->sni) {
  3367. if(!SSL_set_tlsext_host_name(octx->ssl, peer->sni)) {
  3368. failf(data, "Failed set SNI");
  3369. return CURLE_SSL_CONNECT_ERROR;
  3370. }
  3371. }
  3372. #ifdef USE_ECH
  3373. if(ECH_ENABLED(data)) {
  3374. unsigned char *ech_config = NULL;
  3375. size_t ech_config_len = 0;
  3376. char *outername = data->set.str[STRING_ECH_PUBLIC];
  3377. int trying_ech_now = 0;
  3378. if(data->set.tls_ech & CURLECH_GREASE) {
  3379. infof(data, "ECH: will GREASE ClientHello");
  3380. # ifdef OPENSSL_IS_BORINGSSL
  3381. SSL_set_enable_ech_grease(octx->ssl, 1);
  3382. # else
  3383. SSL_set_options(octx->ssl, SSL_OP_ECH_GREASE);
  3384. # endif
  3385. }
  3386. else if(data->set.tls_ech & CURLECH_CLA_CFG) {
  3387. # ifdef OPENSSL_IS_BORINGSSL
  3388. /* have to do base64 decode here for boring */
  3389. const char *b64 = data->set.str[STRING_ECH_CONFIG];
  3390. if(!b64) {
  3391. infof(data, "ECH: ECHConfig from command line empty");
  3392. return CURLE_SSL_CONNECT_ERROR;
  3393. }
  3394. ech_config_len = 2 * strlen(b64);
  3395. result = Curl_base64_decode(b64, &ech_config, &ech_config_len);
  3396. if(result || !ech_config) {
  3397. infof(data, "ECH: cannot base64 decode ECHConfig from command line");
  3398. if(data->set.tls_ech & CURLECH_HARD)
  3399. return result;
  3400. }
  3401. if(SSL_set1_ech_config_list(octx->ssl, ech_config,
  3402. ech_config_len) != 1) {
  3403. infof(data, "ECH: SSL_ECH_set1_echconfig failed");
  3404. if(data->set.tls_ech & CURLECH_HARD) {
  3405. free(ech_config);
  3406. return CURLE_SSL_CONNECT_ERROR;
  3407. }
  3408. }
  3409. free(ech_config);
  3410. trying_ech_now = 1;
  3411. # else
  3412. ech_config = (unsigned char *) data->set.str[STRING_ECH_CONFIG];
  3413. if(!ech_config) {
  3414. infof(data, "ECH: ECHConfig from command line empty");
  3415. return CURLE_SSL_CONNECT_ERROR;
  3416. }
  3417. ech_config_len = strlen(data->set.str[STRING_ECH_CONFIG]);
  3418. if(SSL_ech_set1_echconfig(octx->ssl, ech_config, ech_config_len) != 1) {
  3419. infof(data, "ECH: SSL_ECH_set1_echconfig failed");
  3420. if(data->set.tls_ech & CURLECH_HARD)
  3421. return CURLE_SSL_CONNECT_ERROR;
  3422. }
  3423. else
  3424. trying_ech_now = 1;
  3425. # endif
  3426. infof(data, "ECH: ECHConfig from command line");
  3427. }
  3428. else {
  3429. struct Curl_dns_entry *dns = NULL;
  3430. if(peer->hostname)
  3431. dns = Curl_fetch_addr(data, peer->hostname, peer->port);
  3432. if(!dns) {
  3433. infof(data, "ECH: requested but no DNS info available");
  3434. if(data->set.tls_ech & CURLECH_HARD)
  3435. return CURLE_SSL_CONNECT_ERROR;
  3436. }
  3437. else {
  3438. struct Curl_https_rrinfo *rinfo = NULL;
  3439. rinfo = dns->hinfo;
  3440. if(rinfo && rinfo->echconfiglist) {
  3441. unsigned char *ecl = rinfo->echconfiglist;
  3442. size_t elen = rinfo->echconfiglist_len;
  3443. infof(data, "ECH: ECHConfig from DoH HTTPS RR");
  3444. # ifndef OPENSSL_IS_BORINGSSL
  3445. if(SSL_ech_set1_echconfig(octx->ssl, ecl, elen) != 1) {
  3446. infof(data, "ECH: SSL_ECH_set1_echconfig failed");
  3447. if(data->set.tls_ech & CURLECH_HARD)
  3448. return CURLE_SSL_CONNECT_ERROR;
  3449. }
  3450. # else
  3451. if(SSL_set1_ech_config_list(octx->ssl, ecl, elen) != 1) {
  3452. infof(data, "ECH: SSL_set1_ech_config_list failed (boring)");
  3453. if(data->set.tls_ech & CURLECH_HARD)
  3454. return CURLE_SSL_CONNECT_ERROR;
  3455. }
  3456. # endif
  3457. else {
  3458. trying_ech_now = 1;
  3459. infof(data, "ECH: imported ECHConfigList of length %zu", elen);
  3460. }
  3461. }
  3462. else {
  3463. infof(data, "ECH: requested but no ECHConfig available");
  3464. if(data->set.tls_ech & CURLECH_HARD)
  3465. return CURLE_SSL_CONNECT_ERROR;
  3466. }
  3467. Curl_resolv_unlock(data, dns);
  3468. }
  3469. }
  3470. # ifdef OPENSSL_IS_BORINGSSL
  3471. if(trying_ech_now && outername) {
  3472. infof(data, "ECH: setting public_name not supported with BoringSSL");
  3473. return CURLE_SSL_CONNECT_ERROR;
  3474. }
  3475. # else
  3476. if(trying_ech_now && outername) {
  3477. infof(data, "ECH: inner: '%s', outer: '%s'",
  3478. peer->hostname ? peer->hostname : "NULL", outername);
  3479. result = SSL_ech_set_server_names(octx->ssl,
  3480. peer->hostname, outername,
  3481. 0 /* do send outer */);
  3482. if(result != 1) {
  3483. infof(data, "ECH: rv failed to set server name(s) %d [ERROR]", result);
  3484. return CURLE_SSL_CONNECT_ERROR;
  3485. }
  3486. }
  3487. # endif /* not BORING */
  3488. if(trying_ech_now
  3489. && SSL_set_min_proto_version(octx->ssl, TLS1_3_VERSION) != 1) {
  3490. infof(data, "ECH: cannot force TLSv1.3 [ERROR]");
  3491. return CURLE_SSL_CONNECT_ERROR;
  3492. }
  3493. }
  3494. #endif /* USE_ECH */
  3495. #endif
  3496. octx->reused_session = FALSE;
  3497. if(ssl_config->primary.cache_session && transport == TRNSPRT_TCP) {
  3498. Curl_ssl_sessionid_lock(data);
  3499. if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, NULL)) {
  3500. /* we got a session id, use it! */
  3501. if(!SSL_set_session(octx->ssl, ssl_sessionid)) {
  3502. Curl_ssl_sessionid_unlock(data);
  3503. failf(data, "SSL: SSL_set_session failed: %s",
  3504. ossl_strerror(ERR_get_error(), error_buffer,
  3505. sizeof(error_buffer)));
  3506. return CURLE_SSL_CONNECT_ERROR;
  3507. }
  3508. /* Informational message */
  3509. infof(data, "SSL reusing session ID");
  3510. octx->reused_session = TRUE;
  3511. }
  3512. Curl_ssl_sessionid_unlock(data);
  3513. }
  3514. return CURLE_OK;
  3515. }
  3516. static CURLcode ossl_connect_step1(struct Curl_cfilter *cf,
  3517. struct Curl_easy *data)
  3518. {
  3519. struct ssl_connect_data *connssl = cf->ctx;
  3520. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  3521. struct alpn_proto_buf proto;
  3522. BIO *bio;
  3523. CURLcode result;
  3524. DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);
  3525. DEBUGASSERT(octx);
  3526. memset(&proto, 0, sizeof(proto));
  3527. #ifdef HAS_ALPN
  3528. if(connssl->alpn) {
  3529. result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);
  3530. if(result) {
  3531. failf(data, "Error determining ALPN");
  3532. return CURLE_SSL_CONNECT_ERROR;
  3533. }
  3534. }
  3535. #endif
  3536. result = Curl_ossl_ctx_init(octx, cf, data, &connssl->peer, TRNSPRT_TCP,
  3537. proto.data, proto.len, NULL, NULL,
  3538. ossl_new_session_cb, cf);
  3539. if(result)
  3540. return result;
  3541. octx->bio_method = ossl_bio_cf_method_create();
  3542. if(!octx->bio_method)
  3543. return CURLE_OUT_OF_MEMORY;
  3544. bio = BIO_new(octx->bio_method);
  3545. if(!bio)
  3546. return CURLE_OUT_OF_MEMORY;
  3547. BIO_set_data(bio, cf);
  3548. #ifdef HAVE_SSL_SET0_WBIO
  3549. /* with OpenSSL v1.1.1 we get an alternative to SSL_set_bio() that works
  3550. * without backward compat quirks. Every call takes one reference, so we
  3551. * up it and pass. SSL* then owns it and will free.
  3552. * We check on the function in configure, since LibreSSL and friends
  3553. * each have their own versions to add support for this. */
  3554. BIO_up_ref(bio);
  3555. SSL_set0_rbio(octx->ssl, bio);
  3556. SSL_set0_wbio(octx->ssl, bio);
  3557. #else
  3558. SSL_set_bio(octx->ssl, bio, bio);
  3559. #endif
  3560. #ifdef HAS_ALPN
  3561. if(connssl->alpn) {
  3562. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  3563. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  3564. }
  3565. #endif
  3566. connssl->connecting_state = ssl_connect_2;
  3567. return CURLE_OK;
  3568. }
  3569. #ifdef USE_ECH
  3570. /* If we have retry configs, then trace those out */
  3571. static void ossl_trace_ech_retry_configs(struct Curl_easy *data, SSL* ssl,
  3572. int reason)
  3573. {
  3574. CURLcode result = CURLE_OK;
  3575. size_t rcl = 0;
  3576. int rv = 1;
  3577. # ifndef OPENSSL_IS_BORINGSSL
  3578. char *inner = NULL;
  3579. unsigned char *rcs = NULL;
  3580. char *outer = NULL;
  3581. # else
  3582. const char *inner = NULL;
  3583. const uint8_t *rcs = NULL;
  3584. const char *outer = NULL;
  3585. size_t out_name_len = 0;
  3586. int servername_type = 0;
  3587. # endif
  3588. /* nothing to trace if not doing ECH */
  3589. if(!ECH_ENABLED(data))
  3590. return;
  3591. # ifndef OPENSSL_IS_BORINGSSL
  3592. rv = SSL_ech_get_retry_config(ssl, &rcs, &rcl);
  3593. # else
  3594. SSL_get0_ech_retry_configs(ssl, &rcs, &rcl);
  3595. rv = (int)rcl;
  3596. # endif
  3597. if(rv && rcs) {
  3598. # define HEXSTR_MAX 800
  3599. char *b64str = NULL;
  3600. size_t blen = 0;
  3601. result = Curl_base64_encode((const char *)rcs, rcl,
  3602. &b64str, &blen);
  3603. if(!result && b64str)
  3604. infof(data, "ECH: retry_configs %s", b64str);
  3605. free(b64str);
  3606. # ifndef OPENSSL_IS_BORINGSSL
  3607. rv = SSL_ech_get_status(ssl, &inner, &outer);
  3608. infof(data, "ECH: retry_configs for %s from %s, %d %d",
  3609. inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
  3610. #else
  3611. rv = SSL_ech_accepted(ssl);
  3612. servername_type = SSL_get_servername_type(ssl);
  3613. inner = SSL_get_servername(ssl, servername_type);
  3614. SSL_get0_ech_name_override(ssl, &outer, &out_name_len);
  3615. /* TODO: get the inner from boring */
  3616. infof(data, "ECH: retry_configs for %s from %s, %d %d",
  3617. inner ? inner : "NULL", outer ? outer : "NULL", reason, rv);
  3618. #endif
  3619. }
  3620. else
  3621. infof(data, "ECH: no retry_configs (rv = %d)", rv);
  3622. # ifndef OPENSSL_IS_BORINGSSL
  3623. OPENSSL_free((void *)rcs);
  3624. # endif
  3625. return;
  3626. }
  3627. #endif
  3628. static CURLcode ossl_connect_step2(struct Curl_cfilter *cf,
  3629. struct Curl_easy *data)
  3630. {
  3631. int err;
  3632. struct ssl_connect_data *connssl = cf->ctx;
  3633. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  3634. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3635. DEBUGASSERT(ssl_connect_2 == connssl->connecting_state);
  3636. DEBUGASSERT(octx);
  3637. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  3638. ERR_clear_error();
  3639. err = SSL_connect(octx->ssl);
  3640. if(!octx->x509_store_setup) {
  3641. /* After having send off the ClientHello, we prepare the x509
  3642. * store to verify the coming certificate from the server */
  3643. CURLcode result = Curl_ssl_setup_x509_store(cf, data, octx->ssl_ctx);
  3644. if(result)
  3645. return result;
  3646. octx->x509_store_setup = TRUE;
  3647. }
  3648. #ifndef HAVE_KEYLOG_CALLBACK
  3649. /* If key logging is enabled, wait for the handshake to complete and then
  3650. * proceed with logging secrets (for TLS 1.2 or older).
  3651. */
  3652. if(Curl_tls_keylog_enabled() && !octx->keylog_done)
  3653. ossl_log_tls12_secret(octx->ssl, &octx->keylog_done);
  3654. #endif
  3655. /* 1 is fine
  3656. 0 is "not successful but was shut down controlled"
  3657. <0 is "handshake was not successful, because a fatal error occurred" */
  3658. if(1 != err) {
  3659. int detail = SSL_get_error(octx->ssl, err);
  3660. if(SSL_ERROR_WANT_READ == detail) {
  3661. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  3662. return CURLE_OK;
  3663. }
  3664. if(SSL_ERROR_WANT_WRITE == detail) {
  3665. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  3666. return CURLE_OK;
  3667. }
  3668. #ifdef SSL_ERROR_WANT_ASYNC
  3669. if(SSL_ERROR_WANT_ASYNC == detail) {
  3670. connssl->connecting_state = ssl_connect_2;
  3671. return CURLE_OK;
  3672. }
  3673. #endif
  3674. #ifdef SSL_ERROR_WANT_RETRY_VERIFY
  3675. if(SSL_ERROR_WANT_RETRY_VERIFY == detail) {
  3676. connssl->connecting_state = ssl_connect_2;
  3677. return CURLE_OK;
  3678. }
  3679. #endif
  3680. if(octx->io_result == CURLE_AGAIN) {
  3681. return CURLE_OK;
  3682. }
  3683. else {
  3684. /* untreated error */
  3685. sslerr_t errdetail;
  3686. char error_buffer[256]="";
  3687. CURLcode result;
  3688. long lerr;
  3689. int lib;
  3690. int reason;
  3691. /* the connection failed, we are not waiting for anything else. */
  3692. connssl->connecting_state = ssl_connect_2;
  3693. /* Get the earliest error code from the thread's error queue and remove
  3694. the entry. */
  3695. errdetail = ERR_get_error();
  3696. /* Extract which lib and reason */
  3697. lib = ERR_GET_LIB(errdetail);
  3698. reason = ERR_GET_REASON(errdetail);
  3699. if((lib == ERR_LIB_SSL) &&
  3700. ((reason == SSL_R_CERTIFICATE_VERIFY_FAILED) ||
  3701. (reason == SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED))) {
  3702. result = CURLE_PEER_FAILED_VERIFICATION;
  3703. lerr = SSL_get_verify_result(octx->ssl);
  3704. if(lerr != X509_V_OK) {
  3705. ssl_config->certverifyresult = lerr;
  3706. msnprintf(error_buffer, sizeof(error_buffer),
  3707. "SSL certificate problem: %s",
  3708. X509_verify_cert_error_string(lerr));
  3709. }
  3710. else
  3711. /* strcpy() is fine here as long as the string fits within
  3712. error_buffer */
  3713. strcpy(error_buffer, "SSL certificate verification failed");
  3714. }
  3715. #if defined(SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)
  3716. /* SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED is only available on
  3717. OpenSSL version above v1.1.1, not LibreSSL, BoringSSL, or AWS-LC */
  3718. else if((lib == ERR_LIB_SSL) &&
  3719. (reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED)) {
  3720. /* If client certificate is required, communicate the
  3721. error to client */
  3722. result = CURLE_SSL_CLIENTCERT;
  3723. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
  3724. }
  3725. #endif
  3726. #ifdef USE_ECH
  3727. else if((lib == ERR_LIB_SSL) &&
  3728. # ifndef OPENSSL_IS_BORINGSSL
  3729. (reason == SSL_R_ECH_REQUIRED)) {
  3730. # else
  3731. (reason == SSL_R_ECH_REJECTED)) {
  3732. # endif
  3733. /* trace retry_configs if we got some */
  3734. ossl_trace_ech_retry_configs(data, octx->ssl, reason);
  3735. result = CURLE_ECH_REQUIRED;
  3736. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
  3737. }
  3738. #endif
  3739. else {
  3740. result = CURLE_SSL_CONNECT_ERROR;
  3741. ossl_strerror(errdetail, error_buffer, sizeof(error_buffer));
  3742. }
  3743. /* detail is already set to the SSL error above */
  3744. /* If we e.g. use SSLv2 request-method and the server does not like us
  3745. * (RST connection, etc.), OpenSSL gives no explanation whatsoever and
  3746. * the SO_ERROR is also lost.
  3747. */
  3748. if(CURLE_SSL_CONNECT_ERROR == result && errdetail == 0) {
  3749. char extramsg[80]="";
  3750. int sockerr = SOCKERRNO;
  3751. if(sockerr && detail == SSL_ERROR_SYSCALL)
  3752. Curl_strerror(sockerr, extramsg, sizeof(extramsg));
  3753. failf(data, OSSL_PACKAGE " SSL_connect: %s in connection to %s:%d ",
  3754. extramsg[0] ? extramsg : SSL_ERROR_to_str(detail),
  3755. connssl->peer.hostname, connssl->peer.port);
  3756. return result;
  3757. }
  3758. /* Could be a CERT problem */
  3759. failf(data, "%s", error_buffer);
  3760. return result;
  3761. }
  3762. }
  3763. else {
  3764. int psigtype_nid = NID_undef;
  3765. const char *negotiated_group_name = NULL;
  3766. /* we connected fine, we are not waiting for anything else. */
  3767. connssl->connecting_state = ssl_connect_3;
  3768. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  3769. SSL_get_peer_signature_type_nid(octx->ssl, &psigtype_nid);
  3770. #if (OPENSSL_VERSION_NUMBER >= 0x30200000L)
  3771. negotiated_group_name = SSL_get0_group_name(octx->ssl);
  3772. #else
  3773. negotiated_group_name =
  3774. OBJ_nid2sn(SSL_get_negotiated_group(octx->ssl) & 0x0000FFFF);
  3775. #endif
  3776. #endif
  3777. /* Informational message */
  3778. infof(data, "SSL connection using %s / %s / %s / %s",
  3779. SSL_get_version(octx->ssl),
  3780. SSL_get_cipher(octx->ssl),
  3781. negotiated_group_name? negotiated_group_name : "[blank]",
  3782. OBJ_nid2sn(psigtype_nid));
  3783. #ifdef USE_ECH
  3784. # ifndef OPENSSL_IS_BORINGSSL
  3785. if(ECH_ENABLED(data)) {
  3786. char *inner = NULL, *outer = NULL;
  3787. const char *status = NULL;
  3788. int rv;
  3789. rv = SSL_ech_get_status(octx->ssl, &inner, &outer);
  3790. switch(rv) {
  3791. case SSL_ECH_STATUS_SUCCESS:
  3792. status = "succeeded";
  3793. break;
  3794. case SSL_ECH_STATUS_GREASE_ECH:
  3795. status = "sent GREASE, got retry-configs";
  3796. break;
  3797. case SSL_ECH_STATUS_GREASE:
  3798. status = "sent GREASE";
  3799. break;
  3800. case SSL_ECH_STATUS_NOT_TRIED:
  3801. status = "not attempted";
  3802. break;
  3803. case SSL_ECH_STATUS_NOT_CONFIGURED:
  3804. status = "not configured";
  3805. break;
  3806. case SSL_ECH_STATUS_BACKEND:
  3807. status = "backend (unexpected)";
  3808. break;
  3809. case SSL_ECH_STATUS_FAILED:
  3810. status = "failed";
  3811. break;
  3812. case SSL_ECH_STATUS_BAD_CALL:
  3813. status = "bad call (unexpected)";
  3814. break;
  3815. case SSL_ECH_STATUS_BAD_NAME:
  3816. status = "bad name (unexpected)";
  3817. break;
  3818. default:
  3819. status = "unexpected status";
  3820. infof(data, "ECH: unexpected status %d",rv);
  3821. }
  3822. infof(data, "ECH: result: status is %s, inner is %s, outer is %s",
  3823. (status?status:"NULL"),
  3824. (inner?inner:"NULL"),
  3825. (outer?outer:"NULL"));
  3826. OPENSSL_free(inner);
  3827. OPENSSL_free(outer);
  3828. if(rv == SSL_ECH_STATUS_GREASE_ECH) {
  3829. /* trace retry_configs if we got some */
  3830. ossl_trace_ech_retry_configs(data, octx->ssl, 0);
  3831. }
  3832. if(rv != SSL_ECH_STATUS_SUCCESS
  3833. && data->set.tls_ech & CURLECH_HARD) {
  3834. infof(data, "ECH: ech-hard failed");
  3835. return CURLE_SSL_CONNECT_ERROR;
  3836. }
  3837. }
  3838. else {
  3839. infof(data, "ECH: result: status is not attempted");
  3840. }
  3841. # endif /* BORING */
  3842. #endif /* USE_ECH */
  3843. #ifdef HAS_ALPN
  3844. /* Sets data and len to negotiated protocol, len is 0 if no protocol was
  3845. * negotiated
  3846. */
  3847. if(connssl->alpn) {
  3848. const unsigned char *neg_protocol;
  3849. unsigned int len;
  3850. SSL_get0_alpn_selected(octx->ssl, &neg_protocol, &len);
  3851. return Curl_alpn_set_negotiated(cf, data, neg_protocol, len);
  3852. }
  3853. #endif
  3854. return CURLE_OK;
  3855. }
  3856. }
  3857. /*
  3858. * Heavily modified from:
  3859. * https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#OpenSSL
  3860. */
  3861. static CURLcode ossl_pkp_pin_peer_pubkey(struct Curl_easy *data, X509* cert,
  3862. const char *pinnedpubkey)
  3863. {
  3864. /* Scratch */
  3865. int len1 = 0, len2 = 0;
  3866. unsigned char *buff1 = NULL, *temp = NULL;
  3867. /* Result is returned to caller */
  3868. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  3869. /* if a path was not specified, do not pin */
  3870. if(!pinnedpubkey)
  3871. return CURLE_OK;
  3872. if(!cert)
  3873. return result;
  3874. do {
  3875. /* Begin Gyrations to get the subjectPublicKeyInfo */
  3876. /* Thanks to Viktor Dukhovni on the OpenSSL mailing list */
  3877. /* https://groups.google.com/group/mailing.openssl.users/browse_thread
  3878. /thread/d61858dae102c6c7 */
  3879. len1 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), NULL);
  3880. if(len1 < 1)
  3881. break; /* failed */
  3882. buff1 = temp = malloc(len1);
  3883. if(!buff1)
  3884. break; /* failed */
  3885. /* https://docs.openssl.org/master/man3/d2i_X509/ */
  3886. len2 = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp);
  3887. /*
  3888. * These checks are verifying we got back the same values as when we
  3889. * sized the buffer. it is pretty weak since they should always be the
  3890. * same. But it gives us something to test.
  3891. */
  3892. if((len1 != len2) || !temp || ((temp - buff1) != len1))
  3893. break; /* failed */
  3894. /* End Gyrations */
  3895. /* The one good exit point */
  3896. result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);
  3897. } while(0);
  3898. if(buff1)
  3899. free(buff1);
  3900. return result;
  3901. }
  3902. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && \
  3903. !(defined(LIBRESSL_VERSION_NUMBER) && \
  3904. LIBRESSL_VERSION_NUMBER < 0x3060000fL) && \
  3905. !defined(OPENSSL_IS_BORINGSSL) && \
  3906. !defined(OPENSSL_IS_AWSLC) && \
  3907. !defined(CURL_DISABLE_VERBOSE_STRINGS)
  3908. static void infof_certstack(struct Curl_easy *data, const SSL *ssl)
  3909. {
  3910. STACK_OF(X509) *certstack;
  3911. long verify_result;
  3912. int num_cert_levels;
  3913. int cert_level;
  3914. verify_result = SSL_get_verify_result(ssl);
  3915. if(verify_result != X509_V_OK)
  3916. certstack = SSL_get_peer_cert_chain(ssl);
  3917. else
  3918. certstack = SSL_get0_verified_chain(ssl);
  3919. num_cert_levels = sk_X509_num(certstack);
  3920. for(cert_level = 0; cert_level < num_cert_levels; cert_level++) {
  3921. char cert_algorithm[80] = "";
  3922. char group_name_final[80] = "";
  3923. const X509_ALGOR *palg_cert = NULL;
  3924. const ASN1_OBJECT *paobj_cert = NULL;
  3925. X509 *current_cert;
  3926. EVP_PKEY *current_pkey;
  3927. int key_bits;
  3928. int key_sec_bits;
  3929. int get_group_name;
  3930. const char *type_name;
  3931. current_cert = sk_X509_value(certstack, cert_level);
  3932. X509_get0_signature(NULL, &palg_cert, current_cert);
  3933. X509_ALGOR_get0(&paobj_cert, NULL, NULL, palg_cert);
  3934. OBJ_obj2txt(cert_algorithm, sizeof(cert_algorithm), paobj_cert, 0);
  3935. current_pkey = X509_get0_pubkey(current_cert);
  3936. key_bits = EVP_PKEY_bits(current_pkey);
  3937. #if (OPENSSL_VERSION_NUMBER < 0x30000000L)
  3938. #define EVP_PKEY_get_security_bits EVP_PKEY_security_bits
  3939. #endif
  3940. key_sec_bits = EVP_PKEY_get_security_bits(current_pkey);
  3941. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  3942. {
  3943. char group_name[80] = "";
  3944. get_group_name = EVP_PKEY_get_group_name(current_pkey, group_name,
  3945. sizeof(group_name), NULL);
  3946. msnprintf(group_name_final, sizeof(group_name_final), "/%s", group_name);
  3947. }
  3948. type_name = EVP_PKEY_get0_type_name(current_pkey);
  3949. #else
  3950. get_group_name = 0;
  3951. type_name = NULL;
  3952. #endif
  3953. infof(data,
  3954. " Certificate level %d: "
  3955. "Public key type %s%s (%d/%d Bits/secBits), signed using %s",
  3956. cert_level, type_name ? type_name : "?",
  3957. get_group_name == 0 ? "" : group_name_final,
  3958. key_bits, key_sec_bits, cert_algorithm);
  3959. }
  3960. }
  3961. #else
  3962. #define infof_certstack(data, ssl)
  3963. #endif
  3964. CURLcode Curl_oss_check_peer_cert(struct Curl_cfilter *cf,
  3965. struct Curl_easy *data,
  3966. struct ossl_ctx *octx,
  3967. struct ssl_peer *peer)
  3968. {
  3969. struct connectdata *conn = cf->conn;
  3970. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  3971. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  3972. CURLcode result = CURLE_OK;
  3973. int rc;
  3974. long lerr;
  3975. X509 *issuer;
  3976. BIO *fp = NULL;
  3977. char error_buffer[256]="";
  3978. char buffer[2048];
  3979. const char *ptr;
  3980. BIO *mem = BIO_new(BIO_s_mem());
  3981. bool strict = (conn_config->verifypeer || conn_config->verifyhost);
  3982. DEBUGASSERT(octx);
  3983. if(!mem) {
  3984. failf(data,
  3985. "BIO_new return NULL, " OSSL_PACKAGE
  3986. " error %s",
  3987. ossl_strerror(ERR_get_error(), error_buffer,
  3988. sizeof(error_buffer)) );
  3989. return CURLE_OUT_OF_MEMORY;
  3990. }
  3991. if(data->set.ssl.certinfo)
  3992. /* asked to gather certificate info */
  3993. (void)Curl_ossl_certchain(data, octx->ssl);
  3994. octx->server_cert = SSL_get1_peer_certificate(octx->ssl);
  3995. if(!octx->server_cert) {
  3996. BIO_free(mem);
  3997. if(!strict)
  3998. return CURLE_OK;
  3999. failf(data, "SSL: could not get peer certificate");
  4000. return CURLE_PEER_FAILED_VERIFICATION;
  4001. }
  4002. infof(data, "%s certificate:",
  4003. Curl_ssl_cf_is_proxy(cf)? "Proxy" : "Server");
  4004. rc = x509_name_oneline(X509_get_subject_name(octx->server_cert),
  4005. buffer, sizeof(buffer));
  4006. infof(data, " subject: %s", rc?"[NONE]":buffer);
  4007. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  4008. {
  4009. long len;
  4010. ASN1_TIME_print(mem, X509_get0_notBefore(octx->server_cert));
  4011. len = BIO_get_mem_data(mem, (char **) &ptr);
  4012. infof(data, " start date: %.*s", (int)len, ptr);
  4013. (void)BIO_reset(mem);
  4014. ASN1_TIME_print(mem, X509_get0_notAfter(octx->server_cert));
  4015. len = BIO_get_mem_data(mem, (char **) &ptr);
  4016. infof(data, " expire date: %.*s", (int)len, ptr);
  4017. (void)BIO_reset(mem);
  4018. }
  4019. #endif
  4020. BIO_free(mem);
  4021. if(conn_config->verifyhost) {
  4022. result = Curl_ossl_verifyhost(data, conn, peer, octx->server_cert);
  4023. if(result) {
  4024. X509_free(octx->server_cert);
  4025. octx->server_cert = NULL;
  4026. return result;
  4027. }
  4028. }
  4029. rc = x509_name_oneline(X509_get_issuer_name(octx->server_cert),
  4030. buffer, sizeof(buffer));
  4031. if(rc) {
  4032. if(strict)
  4033. failf(data, "SSL: could not get X509-issuer name");
  4034. result = CURLE_PEER_FAILED_VERIFICATION;
  4035. }
  4036. else {
  4037. infof(data, " issuer: %s", buffer);
  4038. /* We could do all sorts of certificate verification stuff here before
  4039. deallocating the certificate. */
  4040. /* e.g. match issuer name with provided issuer certificate */
  4041. if(conn_config->issuercert || conn_config->issuercert_blob) {
  4042. if(conn_config->issuercert_blob) {
  4043. fp = BIO_new_mem_buf(conn_config->issuercert_blob->data,
  4044. (int)conn_config->issuercert_blob->len);
  4045. if(!fp) {
  4046. failf(data,
  4047. "BIO_new_mem_buf NULL, " OSSL_PACKAGE
  4048. " error %s",
  4049. ossl_strerror(ERR_get_error(), error_buffer,
  4050. sizeof(error_buffer)) );
  4051. X509_free(octx->server_cert);
  4052. octx->server_cert = NULL;
  4053. return CURLE_OUT_OF_MEMORY;
  4054. }
  4055. }
  4056. else {
  4057. fp = BIO_new(BIO_s_file());
  4058. if(!fp) {
  4059. failf(data,
  4060. "BIO_new return NULL, " OSSL_PACKAGE
  4061. " error %s",
  4062. ossl_strerror(ERR_get_error(), error_buffer,
  4063. sizeof(error_buffer)) );
  4064. X509_free(octx->server_cert);
  4065. octx->server_cert = NULL;
  4066. return CURLE_OUT_OF_MEMORY;
  4067. }
  4068. if(BIO_read_filename(fp, conn_config->issuercert) <= 0) {
  4069. if(strict)
  4070. failf(data, "SSL: Unable to open issuer cert (%s)",
  4071. conn_config->issuercert);
  4072. BIO_free(fp);
  4073. X509_free(octx->server_cert);
  4074. octx->server_cert = NULL;
  4075. return CURLE_SSL_ISSUER_ERROR;
  4076. }
  4077. }
  4078. issuer = PEM_read_bio_X509(fp, NULL, ZERO_NULL, NULL);
  4079. if(!issuer) {
  4080. if(strict)
  4081. failf(data, "SSL: Unable to read issuer cert (%s)",
  4082. conn_config->issuercert);
  4083. BIO_free(fp);
  4084. X509_free(issuer);
  4085. X509_free(octx->server_cert);
  4086. octx->server_cert = NULL;
  4087. return CURLE_SSL_ISSUER_ERROR;
  4088. }
  4089. if(X509_check_issued(issuer, octx->server_cert) != X509_V_OK) {
  4090. if(strict)
  4091. failf(data, "SSL: Certificate issuer check failed (%s)",
  4092. conn_config->issuercert);
  4093. BIO_free(fp);
  4094. X509_free(issuer);
  4095. X509_free(octx->server_cert);
  4096. octx->server_cert = NULL;
  4097. return CURLE_SSL_ISSUER_ERROR;
  4098. }
  4099. infof(data, " SSL certificate issuer check ok (%s)",
  4100. conn_config->issuercert);
  4101. BIO_free(fp);
  4102. X509_free(issuer);
  4103. }
  4104. lerr = SSL_get_verify_result(octx->ssl);
  4105. ssl_config->certverifyresult = lerr;
  4106. if(lerr != X509_V_OK) {
  4107. if(conn_config->verifypeer) {
  4108. /* We probably never reach this, because SSL_connect() will fail
  4109. and we return earlier if verifypeer is set? */
  4110. if(strict)
  4111. failf(data, "SSL certificate verify result: %s (%ld)",
  4112. X509_verify_cert_error_string(lerr), lerr);
  4113. result = CURLE_PEER_FAILED_VERIFICATION;
  4114. }
  4115. else
  4116. infof(data, " SSL certificate verify result: %s (%ld),"
  4117. " continuing anyway.",
  4118. X509_verify_cert_error_string(lerr), lerr);
  4119. }
  4120. else
  4121. infof(data, " SSL certificate verify ok.");
  4122. }
  4123. infof_certstack(data, octx->ssl);
  4124. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  4125. !defined(OPENSSL_NO_OCSP)
  4126. if(conn_config->verifystatus && !octx->reused_session) {
  4127. /* do not do this after Session ID reuse */
  4128. result = verifystatus(cf, data, octx);
  4129. if(result) {
  4130. /* when verifystatus failed, remove the session id from the cache again
  4131. if present */
  4132. if(!Curl_ssl_cf_is_proxy(cf)) {
  4133. void *old_ssl_sessionid = NULL;
  4134. bool incache;
  4135. Curl_ssl_sessionid_lock(data);
  4136. incache = !(Curl_ssl_getsessionid(cf, data, peer,
  4137. &old_ssl_sessionid, NULL));
  4138. if(incache) {
  4139. infof(data, "Remove session ID again from cache");
  4140. Curl_ssl_delsessionid(data, old_ssl_sessionid);
  4141. }
  4142. Curl_ssl_sessionid_unlock(data);
  4143. }
  4144. X509_free(octx->server_cert);
  4145. octx->server_cert = NULL;
  4146. return result;
  4147. }
  4148. }
  4149. #endif
  4150. if(!strict)
  4151. /* when not strict, we do not bother about the verify cert problems */
  4152. result = CURLE_OK;
  4153. #ifndef CURL_DISABLE_PROXY
  4154. ptr = Curl_ssl_cf_is_proxy(cf)?
  4155. data->set.str[STRING_SSL_PINNEDPUBLICKEY_PROXY]:
  4156. data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  4157. #else
  4158. ptr = data->set.str[STRING_SSL_PINNEDPUBLICKEY];
  4159. #endif
  4160. if(!result && ptr) {
  4161. result = ossl_pkp_pin_peer_pubkey(data, octx->server_cert, ptr);
  4162. if(result)
  4163. failf(data, "SSL: public key does not match pinned public key");
  4164. }
  4165. X509_free(octx->server_cert);
  4166. octx->server_cert = NULL;
  4167. return result;
  4168. }
  4169. static CURLcode ossl_connect_step3(struct Curl_cfilter *cf,
  4170. struct Curl_easy *data)
  4171. {
  4172. CURLcode result = CURLE_OK;
  4173. struct ssl_connect_data *connssl = cf->ctx;
  4174. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4175. DEBUGASSERT(ssl_connect_3 == connssl->connecting_state);
  4176. /*
  4177. * We check certificates to authenticate the server; otherwise we risk
  4178. * man-in-the-middle attack; NEVERTHELESS, if we are told explicitly not to
  4179. * verify the peer, ignore faults and failures from the server cert
  4180. * operations.
  4181. */
  4182. result = Curl_oss_check_peer_cert(cf, data, octx, &connssl->peer);
  4183. if(!result)
  4184. connssl->connecting_state = ssl_connect_done;
  4185. return result;
  4186. }
  4187. static CURLcode ossl_connect_common(struct Curl_cfilter *cf,
  4188. struct Curl_easy *data,
  4189. bool nonblocking,
  4190. bool *done)
  4191. {
  4192. CURLcode result = CURLE_OK;
  4193. struct ssl_connect_data *connssl = cf->ctx;
  4194. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  4195. int what;
  4196. /* check if the connection has already been established */
  4197. if(ssl_connection_complete == connssl->state) {
  4198. *done = TRUE;
  4199. return CURLE_OK;
  4200. }
  4201. if(ssl_connect_1 == connssl->connecting_state) {
  4202. /* Find out how much more time we are allowed */
  4203. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  4204. if(timeout_ms < 0) {
  4205. /* no need to continue if time is already up */
  4206. failf(data, "SSL connection timeout");
  4207. return CURLE_OPERATION_TIMEDOUT;
  4208. }
  4209. result = ossl_connect_step1(cf, data);
  4210. if(result)
  4211. goto out;
  4212. }
  4213. while(ssl_connect_2 == connssl->connecting_state) {
  4214. /* check allowed time left */
  4215. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  4216. if(timeout_ms < 0) {
  4217. /* no need to continue if time already is up */
  4218. failf(data, "SSL connection timeout");
  4219. result = CURLE_OPERATION_TIMEDOUT;
  4220. goto out;
  4221. }
  4222. /* if ssl is expecting something, check if it is available. */
  4223. if(!nonblocking && connssl->io_need) {
  4224. curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND)?
  4225. sockfd:CURL_SOCKET_BAD;
  4226. curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV)?
  4227. sockfd:CURL_SOCKET_BAD;
  4228. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  4229. timeout_ms);
  4230. if(what < 0) {
  4231. /* fatal error */
  4232. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  4233. result = CURLE_SSL_CONNECT_ERROR;
  4234. goto out;
  4235. }
  4236. if(0 == what) {
  4237. /* timeout */
  4238. failf(data, "SSL connection timeout");
  4239. result = CURLE_OPERATION_TIMEDOUT;
  4240. goto out;
  4241. }
  4242. /* socket is readable or writable */
  4243. }
  4244. /* Run transaction, and return to the caller if it failed or if this
  4245. * connection is done nonblocking and this loop would execute again. This
  4246. * permits the owner of a multi handle to abort a connection attempt
  4247. * before step2 has completed while ensuring that a client using select()
  4248. * or epoll() will always have a valid fdset to wait on.
  4249. */
  4250. result = ossl_connect_step2(cf, data);
  4251. if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
  4252. goto out;
  4253. } /* repeat step2 until all transactions are done. */
  4254. if(ssl_connect_3 == connssl->connecting_state) {
  4255. result = ossl_connect_step3(cf, data);
  4256. if(result)
  4257. goto out;
  4258. }
  4259. if(ssl_connect_done == connssl->connecting_state) {
  4260. connssl->state = ssl_connection_complete;
  4261. *done = TRUE;
  4262. }
  4263. else
  4264. *done = FALSE;
  4265. /* Reset our connect state machine */
  4266. connssl->connecting_state = ssl_connect_1;
  4267. out:
  4268. return result;
  4269. }
  4270. static CURLcode ossl_connect_nonblocking(struct Curl_cfilter *cf,
  4271. struct Curl_easy *data,
  4272. bool *done)
  4273. {
  4274. return ossl_connect_common(cf, data, TRUE, done);
  4275. }
  4276. static CURLcode ossl_connect(struct Curl_cfilter *cf,
  4277. struct Curl_easy *data)
  4278. {
  4279. CURLcode result;
  4280. bool done = FALSE;
  4281. result = ossl_connect_common(cf, data, FALSE, &done);
  4282. if(result)
  4283. return result;
  4284. DEBUGASSERT(done);
  4285. return CURLE_OK;
  4286. }
  4287. static bool ossl_data_pending(struct Curl_cfilter *cf,
  4288. const struct Curl_easy *data)
  4289. {
  4290. struct ssl_connect_data *connssl = cf->ctx;
  4291. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4292. (void)data;
  4293. DEBUGASSERT(connssl && octx);
  4294. if(octx->ssl && SSL_pending(octx->ssl))
  4295. return TRUE;
  4296. return FALSE;
  4297. }
  4298. static ssize_t ossl_send(struct Curl_cfilter *cf,
  4299. struct Curl_easy *data,
  4300. const void *mem,
  4301. size_t len,
  4302. CURLcode *curlcode)
  4303. {
  4304. /* SSL_write() is said to return 'int' while write() and send() returns
  4305. 'size_t' */
  4306. int err;
  4307. char error_buffer[256];
  4308. sslerr_t sslerror;
  4309. int memlen;
  4310. int rc;
  4311. struct ssl_connect_data *connssl = cf->ctx;
  4312. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4313. (void)data;
  4314. DEBUGASSERT(octx);
  4315. ERR_clear_error();
  4316. memlen = (len > (size_t)INT_MAX) ? INT_MAX : (int)len;
  4317. rc = SSL_write(octx->ssl, mem, memlen);
  4318. if(rc <= 0) {
  4319. err = SSL_get_error(octx->ssl, rc);
  4320. switch(err) {
  4321. case SSL_ERROR_WANT_READ:
  4322. case SSL_ERROR_WANT_WRITE:
  4323. /* The operation did not complete; the same TLS/SSL I/O function
  4324. should be called again later. This is basically an EWOULDBLOCK
  4325. equivalent. */
  4326. *curlcode = CURLE_AGAIN;
  4327. rc = -1;
  4328. goto out;
  4329. case SSL_ERROR_SYSCALL:
  4330. {
  4331. int sockerr = SOCKERRNO;
  4332. if(octx->io_result == CURLE_AGAIN) {
  4333. *curlcode = CURLE_AGAIN;
  4334. rc = -1;
  4335. goto out;
  4336. }
  4337. sslerror = ERR_get_error();
  4338. if(sslerror)
  4339. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4340. else if(sockerr)
  4341. Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4342. else
  4343. msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4344. SSL_ERROR_to_str(err));
  4345. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  4346. error_buffer, sockerr);
  4347. *curlcode = CURLE_SEND_ERROR;
  4348. rc = -1;
  4349. goto out;
  4350. }
  4351. case SSL_ERROR_SSL: {
  4352. /* A failure in the SSL library occurred, usually a protocol error.
  4353. The OpenSSL error queue contains more information on the error. */
  4354. sslerror = ERR_get_error();
  4355. failf(data, "SSL_write() error: %s",
  4356. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer)));
  4357. *curlcode = CURLE_SEND_ERROR;
  4358. rc = -1;
  4359. goto out;
  4360. }
  4361. default:
  4362. /* a true error */
  4363. failf(data, OSSL_PACKAGE " SSL_write: %s, errno %d",
  4364. SSL_ERROR_to_str(err), SOCKERRNO);
  4365. *curlcode = CURLE_SEND_ERROR;
  4366. rc = -1;
  4367. goto out;
  4368. }
  4369. }
  4370. *curlcode = CURLE_OK;
  4371. out:
  4372. return (ssize_t)rc; /* number of bytes */
  4373. }
  4374. static ssize_t ossl_recv(struct Curl_cfilter *cf,
  4375. struct Curl_easy *data, /* transfer */
  4376. char *buf, /* store read data here */
  4377. size_t buffersize, /* max amount to read */
  4378. CURLcode *curlcode)
  4379. {
  4380. char error_buffer[256];
  4381. unsigned long sslerror;
  4382. ssize_t nread;
  4383. int buffsize;
  4384. struct connectdata *conn = cf->conn;
  4385. struct ssl_connect_data *connssl = cf->ctx;
  4386. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4387. (void)data;
  4388. DEBUGASSERT(octx);
  4389. ERR_clear_error();
  4390. buffsize = (buffersize > (size_t)INT_MAX) ? INT_MAX : (int)buffersize;
  4391. nread = (ssize_t)SSL_read(octx->ssl, buf, buffsize);
  4392. if(nread <= 0) {
  4393. /* failed SSL_read */
  4394. int err = SSL_get_error(octx->ssl, (int)nread);
  4395. switch(err) {
  4396. case SSL_ERROR_NONE: /* this is not an error */
  4397. break;
  4398. case SSL_ERROR_ZERO_RETURN: /* no more data */
  4399. /* close_notify alert */
  4400. if(cf->sockindex == FIRSTSOCKET)
  4401. /* mark the connection for close if it is indeed the control
  4402. connection */
  4403. connclose(conn, "TLS close_notify");
  4404. break;
  4405. case SSL_ERROR_WANT_READ:
  4406. case SSL_ERROR_WANT_WRITE:
  4407. /* there is data pending, re-invoke SSL_read() */
  4408. *curlcode = CURLE_AGAIN;
  4409. nread = -1;
  4410. goto out;
  4411. default:
  4412. /* openssl/ssl.h for SSL_ERROR_SYSCALL says "look at error stack/return
  4413. value/errno" */
  4414. /* https://docs.openssl.org/master/man3/ERR_get_error/ */
  4415. if(octx->io_result == CURLE_AGAIN) {
  4416. *curlcode = CURLE_AGAIN;
  4417. nread = -1;
  4418. goto out;
  4419. }
  4420. sslerror = ERR_get_error();
  4421. if((nread < 0) || sslerror) {
  4422. /* If the return code was negative or there actually is an error in the
  4423. queue */
  4424. int sockerr = SOCKERRNO;
  4425. if(sslerror)
  4426. ossl_strerror(sslerror, error_buffer, sizeof(error_buffer));
  4427. else if(sockerr && err == SSL_ERROR_SYSCALL)
  4428. Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4429. else
  4430. msnprintf(error_buffer, sizeof(error_buffer), "%s",
  4431. SSL_ERROR_to_str(err));
  4432. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d",
  4433. error_buffer, sockerr);
  4434. *curlcode = CURLE_RECV_ERROR;
  4435. nread = -1;
  4436. goto out;
  4437. }
  4438. /* For debug builds be a little stricter and error on any
  4439. SSL_ERROR_SYSCALL. For example a server may have closed the connection
  4440. abruptly without a close_notify alert. For compatibility with older
  4441. peers we do not do this by default. #4624
  4442. We can use this to gauge how many users may be affected, and
  4443. if it goes ok eventually transition to allow in dev and release with
  4444. the newest OpenSSL: #if (OPENSSL_VERSION_NUMBER >= 0x10101000L) */
  4445. #ifdef DEBUGBUILD
  4446. if(err == SSL_ERROR_SYSCALL) {
  4447. int sockerr = SOCKERRNO;
  4448. if(sockerr)
  4449. Curl_strerror(sockerr, error_buffer, sizeof(error_buffer));
  4450. else {
  4451. msnprintf(error_buffer, sizeof(error_buffer),
  4452. "Connection closed abruptly");
  4453. }
  4454. failf(data, OSSL_PACKAGE " SSL_read: %s, errno %d"
  4455. " (Fatal because this is a curl debug build)",
  4456. error_buffer, sockerr);
  4457. *curlcode = CURLE_RECV_ERROR;
  4458. nread = -1;
  4459. goto out;
  4460. }
  4461. #endif
  4462. }
  4463. }
  4464. out:
  4465. return nread;
  4466. }
  4467. static size_t ossl_version(char *buffer, size_t size)
  4468. {
  4469. #ifdef LIBRESSL_VERSION_NUMBER
  4470. #ifdef HAVE_OPENSSL_VERSION
  4471. char *p;
  4472. size_t count;
  4473. const char *ver = OpenSSL_version(OPENSSL_VERSION);
  4474. const char expected[] = OSSL_PACKAGE " "; /* ie "LibreSSL " */
  4475. if(strncasecompare(ver, expected, sizeof(expected) - 1)) {
  4476. ver += sizeof(expected) - 1;
  4477. }
  4478. count = msnprintf(buffer, size, "%s/%s", OSSL_PACKAGE, ver);
  4479. for(p = buffer; *p; ++p) {
  4480. if(ISBLANK(*p))
  4481. *p = '_';
  4482. }
  4483. return count;
  4484. #else
  4485. return msnprintf(buffer, size, "%s/%lx.%lx.%lx",
  4486. OSSL_PACKAGE,
  4487. (LIBRESSL_VERSION_NUMBER>>28)&0xf,
  4488. (LIBRESSL_VERSION_NUMBER>>20)&0xff,
  4489. (LIBRESSL_VERSION_NUMBER>>12)&0xff);
  4490. #endif
  4491. #elif defined(OPENSSL_IS_BORINGSSL)
  4492. #ifdef CURL_BORINGSSL_VERSION
  4493. return msnprintf(buffer, size, "%s/%s",
  4494. OSSL_PACKAGE,
  4495. CURL_BORINGSSL_VERSION);
  4496. #else
  4497. return msnprintf(buffer, size, OSSL_PACKAGE);
  4498. #endif
  4499. #elif defined(OPENSSL_IS_AWSLC)
  4500. return msnprintf(buffer, size, "%s/%s",
  4501. OSSL_PACKAGE,
  4502. AWSLC_VERSION_NUMBER_STRING);
  4503. #elif defined(HAVE_OPENSSL_VERSION) && defined(OPENSSL_VERSION_STRING)
  4504. return msnprintf(buffer, size, "%s/%s",
  4505. OSSL_PACKAGE, OpenSSL_version(OPENSSL_VERSION_STRING));
  4506. #else
  4507. /* not LibreSSL, BoringSSL and not using OpenSSL_version */
  4508. char sub[3];
  4509. unsigned long ssleay_value;
  4510. sub[2]='\0';
  4511. sub[1]='\0';
  4512. ssleay_value = OpenSSL_version_num();
  4513. if(ssleay_value < 0x906000) {
  4514. ssleay_value = SSLEAY_VERSION_NUMBER;
  4515. sub[0]='\0';
  4516. }
  4517. else {
  4518. if(ssleay_value&0xff0) {
  4519. int minor_ver = (ssleay_value >> 4) & 0xff;
  4520. if(minor_ver > 26) {
  4521. /* handle extended version introduced for 0.9.8za */
  4522. sub[1] = (char) ((minor_ver - 1) % 26 + 'a' + 1);
  4523. sub[0] = 'z';
  4524. }
  4525. else {
  4526. sub[0] = (char) (minor_ver + 'a' - 1);
  4527. }
  4528. }
  4529. else
  4530. sub[0]='\0';
  4531. }
  4532. return msnprintf(buffer, size, "%s/%lx.%lx.%lx%s"
  4533. #ifdef OPENSSL_FIPS
  4534. "-fips"
  4535. #endif
  4536. ,
  4537. OSSL_PACKAGE,
  4538. (ssleay_value>>28)&0xf,
  4539. (ssleay_value>>20)&0xff,
  4540. (ssleay_value>>12)&0xff,
  4541. sub);
  4542. #endif /* OPENSSL_IS_BORINGSSL */
  4543. }
  4544. /* can be called with data == NULL */
  4545. static CURLcode ossl_random(struct Curl_easy *data,
  4546. unsigned char *entropy, size_t length)
  4547. {
  4548. int rc;
  4549. if(data) {
  4550. if(ossl_seed(data)) /* Initiate the seed if not already done */
  4551. return CURLE_FAILED_INIT; /* could not seed for some reason */
  4552. }
  4553. else {
  4554. if(!rand_enough())
  4555. return CURLE_FAILED_INIT;
  4556. }
  4557. /* RAND_bytes() returns 1 on success, 0 otherwise. */
  4558. rc = RAND_bytes(entropy, (ossl_valsize_t)curlx_uztosi(length));
  4559. return (rc == 1 ? CURLE_OK : CURLE_FAILED_INIT);
  4560. }
  4561. #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
  4562. static CURLcode ossl_sha256sum(const unsigned char *tmp, /* input */
  4563. size_t tmplen,
  4564. unsigned char *sha256sum /* output */,
  4565. size_t unused)
  4566. {
  4567. EVP_MD_CTX *mdctx;
  4568. unsigned int len = 0;
  4569. (void) unused;
  4570. mdctx = EVP_MD_CTX_create();
  4571. if(!mdctx)
  4572. return CURLE_OUT_OF_MEMORY;
  4573. if(!EVP_DigestInit(mdctx, EVP_sha256())) {
  4574. EVP_MD_CTX_destroy(mdctx);
  4575. return CURLE_FAILED_INIT;
  4576. }
  4577. EVP_DigestUpdate(mdctx, tmp, tmplen);
  4578. EVP_DigestFinal_ex(mdctx, sha256sum, &len);
  4579. EVP_MD_CTX_destroy(mdctx);
  4580. return CURLE_OK;
  4581. }
  4582. #endif
  4583. static bool ossl_cert_status_request(void)
  4584. {
  4585. #if (OPENSSL_VERSION_NUMBER >= 0x0090808fL) && !defined(OPENSSL_NO_TLSEXT) && \
  4586. !defined(OPENSSL_NO_OCSP)
  4587. return TRUE;
  4588. #else
  4589. return FALSE;
  4590. #endif
  4591. }
  4592. static void *ossl_get_internals(struct ssl_connect_data *connssl,
  4593. CURLINFO info)
  4594. {
  4595. /* Legacy: CURLINFO_TLS_SESSION must return an SSL_CTX pointer. */
  4596. struct ossl_ctx *octx = (struct ossl_ctx *)connssl->backend;
  4597. DEBUGASSERT(octx);
  4598. return info == CURLINFO_TLS_SESSION ?
  4599. (void *)octx->ssl_ctx : (void *)octx->ssl;
  4600. }
  4601. const struct Curl_ssl Curl_ssl_openssl = {
  4602. { CURLSSLBACKEND_OPENSSL, "openssl" }, /* info */
  4603. SSLSUPP_CA_PATH |
  4604. SSLSUPP_CAINFO_BLOB |
  4605. SSLSUPP_CERTINFO |
  4606. SSLSUPP_PINNEDPUBKEY |
  4607. SSLSUPP_SSL_CTX |
  4608. #ifdef HAVE_SSL_CTX_SET_CIPHERSUITES
  4609. SSLSUPP_TLS13_CIPHERSUITES |
  4610. #endif
  4611. #ifdef USE_ECH
  4612. SSLSUPP_ECH |
  4613. #endif
  4614. SSLSUPP_CA_CACHE |
  4615. SSLSUPP_HTTPS_PROXY,
  4616. sizeof(struct ossl_ctx),
  4617. ossl_init, /* init */
  4618. ossl_cleanup, /* cleanup */
  4619. ossl_version, /* version */
  4620. Curl_none_check_cxn, /* check_cxn */
  4621. ossl_shutdown, /* shutdown */
  4622. ossl_data_pending, /* data_pending */
  4623. ossl_random, /* random */
  4624. ossl_cert_status_request, /* cert_status_request */
  4625. ossl_connect, /* connect */
  4626. ossl_connect_nonblocking, /* connect_nonblocking */
  4627. Curl_ssl_adjust_pollset, /* adjust_pollset */
  4628. ossl_get_internals, /* get_internals */
  4629. ossl_close, /* close_one */
  4630. ossl_close_all, /* close_all */
  4631. ossl_set_engine, /* set_engine */
  4632. ossl_set_engine_default, /* set_engine_default */
  4633. ossl_engines_list, /* engines_list */
  4634. Curl_none_false_start, /* false_start */
  4635. #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL) && !defined(OPENSSL_NO_SHA256)
  4636. ossl_sha256sum, /* sha256sum */
  4637. #else
  4638. NULL, /* sha256sum */
  4639. #endif
  4640. NULL, /* use of data in this connection */
  4641. NULL, /* remote of data from this connection */
  4642. ossl_recv, /* recv decrypted data */
  4643. ossl_send, /* send data to encrypt */
  4644. };
  4645. #endif /* USE_OPENSSL */