_ssl.c 186 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308
  1. /* SSL socket module
  2. SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
  3. Re-worked a bit by Bill Janssen to add server-side support and
  4. certificate decoding. Chris Stawarz contributed some non-blocking
  5. patches.
  6. This module is imported by ssl.py. It should *not* be used
  7. directly.
  8. XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
  9. XXX integrate several "shutdown modes" as suggested in
  10. http://bugs.python.org/issue8108#msg102867 ?
  11. */
  12. /* Don't warn about deprecated functions, */
  13. #ifndef OPENSSL_API_COMPAT
  14. // 0x10101000L == 1.1.1, 30000 == 3.0.0
  15. #define OPENSSL_API_COMPAT 0x10101000L
  16. #endif
  17. #define OPENSSL_NO_DEPRECATED 1
  18. #define PY_SSIZE_T_CLEAN
  19. #include "Python.h"
  20. /* Include symbols from _socket module */
  21. #include "socketmodule.h"
  22. #ifdef MS_WINDOWS
  23. # include <wincrypt.h>
  24. #endif
  25. #include "_ssl.h"
  26. /* Redefined below for Windows debug builds after important #includes */
  27. #define _PySSL_FIX_ERRNO
  28. #define PySSL_BEGIN_ALLOW_THREADS_S(save) \
  29. do { (save) = PyEval_SaveThread(); } while(0)
  30. #define PySSL_END_ALLOW_THREADS_S(save) \
  31. do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
  32. #define PySSL_BEGIN_ALLOW_THREADS { \
  33. PyThreadState *_save = NULL; \
  34. PySSL_BEGIN_ALLOW_THREADS_S(_save);
  35. #define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
  36. #if defined(HAVE_POLL_H)
  37. #include <poll.h>
  38. #elif defined(HAVE_SYS_POLL_H)
  39. #include <sys/poll.h>
  40. #endif
  41. /* Include OpenSSL header files */
  42. #include "openssl/rsa.h"
  43. #include "openssl/crypto.h"
  44. #include "openssl/x509.h"
  45. #include "openssl/x509v3.h"
  46. #include "openssl/pem.h"
  47. #include "openssl/ssl.h"
  48. #include "openssl/err.h"
  49. #include "openssl/rand.h"
  50. #include "openssl/bio.h"
  51. #include "openssl/dh.h"
  52. #ifndef OPENSSL_THREADS
  53. # error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
  54. #endif
  55. struct py_ssl_error_code {
  56. const char *mnemonic;
  57. int library, reason;
  58. };
  59. struct py_ssl_library_code {
  60. const char *library;
  61. int code;
  62. };
  63. #if defined(MS_WINDOWS) && defined(Py_DEBUG)
  64. /* Debug builds on Windows rely on getting errno directly from OpenSSL.
  65. * However, because it uses a different CRT, we need to transfer the
  66. * value of errno from OpenSSL into our debug CRT.
  67. *
  68. * Don't be fooled - this is horribly ugly code. The only reasonable
  69. * alternative is to do both debug and release builds of OpenSSL, which
  70. * requires much uglier code to transform their automatically generated
  71. * makefile. This is the lesser of all the evils.
  72. */
  73. static void _PySSLFixErrno(void) {
  74. HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
  75. if (!ucrtbase) {
  76. /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
  77. * have a catastrophic failure, but this function is not the
  78. * place to raise it. */
  79. return;
  80. }
  81. typedef int *(__stdcall *errno_func)(void);
  82. errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
  83. if (ssl_errno) {
  84. errno = *ssl_errno();
  85. *ssl_errno() = 0;
  86. } else {
  87. errno = ENOTRECOVERABLE;
  88. }
  89. }
  90. #undef _PySSL_FIX_ERRNO
  91. #define _PySSL_FIX_ERRNO _PySSLFixErrno()
  92. #endif
  93. /* Include generated data (error codes) */
  94. #if (OPENSSL_VERSION_NUMBER >= 0x30100000L)
  95. #include "_ssl_data_31.h"
  96. #elif (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  97. #include "_ssl_data_300.h"
  98. #elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
  99. #include "_ssl_data_111.h"
  100. #else
  101. #include "_ssl_data.h"
  102. #endif
  103. /* OpenSSL API 1.1.0+ does not include version methods */
  104. #ifndef OPENSSL_NO_SSL3_METHOD
  105. extern const SSL_METHOD *SSLv3_method(void);
  106. #endif
  107. #ifndef OPENSSL_NO_TLS1_METHOD
  108. extern const SSL_METHOD *TLSv1_method(void);
  109. #endif
  110. #ifndef OPENSSL_NO_TLS1_1_METHOD
  111. extern const SSL_METHOD *TLSv1_1_method(void);
  112. #endif
  113. #ifndef OPENSSL_NO_TLS1_2_METHOD
  114. extern const SSL_METHOD *TLSv1_2_method(void);
  115. #endif
  116. #ifndef INVALID_SOCKET /* MS defines this */
  117. #define INVALID_SOCKET (-1)
  118. #endif
  119. /* Default cipher suites */
  120. #ifndef PY_SSL_DEFAULT_CIPHERS
  121. #define PY_SSL_DEFAULT_CIPHERS 1
  122. #endif
  123. #if PY_SSL_DEFAULT_CIPHERS == 0
  124. #ifndef PY_SSL_DEFAULT_CIPHER_STRING
  125. #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
  126. #endif
  127. #ifndef PY_SSL_MIN_PROTOCOL
  128. #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
  129. #endif
  130. #elif PY_SSL_DEFAULT_CIPHERS == 1
  131. /* Python custom selection of sensible cipher suites
  132. * @SECLEVEL=2: security level 2 with 112 bits minimum security (e.g. 2048 bits RSA key)
  133. * ECDH+*: enable ephemeral elliptic curve Diffie-Hellman
  134. * DHE+*: fallback to ephemeral finite field Diffie-Hellman
  135. * encryption order: AES AEAD (GCM), ChaCha AEAD, AES CBC
  136. * !aNULL:!eNULL: really no NULL ciphers
  137. * !aDSS: no authentication with discrete logarithm DSA algorithm
  138. * !SHA1: no weak SHA1 MAC
  139. * !AESCCM: no CCM mode, it's uncommon and slow
  140. *
  141. * Based on Hynek's excellent blog post (update 2021-02-11)
  142. * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
  143. */
  144. #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM"
  145. #ifndef PY_SSL_MIN_PROTOCOL
  146. #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
  147. #endif
  148. #elif PY_SSL_DEFAULT_CIPHERS == 2
  149. /* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
  150. #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
  151. #else
  152. #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
  153. #endif
  154. enum py_ssl_error {
  155. /* these mirror ssl.h */
  156. PY_SSL_ERROR_NONE,
  157. PY_SSL_ERROR_SSL,
  158. PY_SSL_ERROR_WANT_READ,
  159. PY_SSL_ERROR_WANT_WRITE,
  160. PY_SSL_ERROR_WANT_X509_LOOKUP,
  161. PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
  162. PY_SSL_ERROR_ZERO_RETURN,
  163. PY_SSL_ERROR_WANT_CONNECT,
  164. /* start of non ssl.h errorcodes */
  165. PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
  166. PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
  167. PY_SSL_ERROR_INVALID_ERROR_CODE
  168. };
  169. enum py_ssl_server_or_client {
  170. PY_SSL_CLIENT,
  171. PY_SSL_SERVER
  172. };
  173. enum py_ssl_cert_requirements {
  174. PY_SSL_CERT_NONE,
  175. PY_SSL_CERT_OPTIONAL,
  176. PY_SSL_CERT_REQUIRED
  177. };
  178. enum py_ssl_version {
  179. PY_SSL_VERSION_SSL2,
  180. PY_SSL_VERSION_SSL3=1,
  181. PY_SSL_VERSION_TLS, /* SSLv23 */
  182. PY_SSL_VERSION_TLS1,
  183. PY_SSL_VERSION_TLS1_1,
  184. PY_SSL_VERSION_TLS1_2,
  185. PY_SSL_VERSION_TLS_CLIENT=0x10,
  186. PY_SSL_VERSION_TLS_SERVER,
  187. };
  188. enum py_proto_version {
  189. PY_PROTO_MINIMUM_SUPPORTED = -2,
  190. PY_PROTO_SSLv3 = SSL3_VERSION,
  191. PY_PROTO_TLSv1 = TLS1_VERSION,
  192. PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
  193. PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
  194. #ifdef TLS1_3_VERSION
  195. PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
  196. #else
  197. PY_PROTO_TLSv1_3 = 0x304,
  198. #endif
  199. PY_PROTO_MAXIMUM_SUPPORTED = -1,
  200. /* OpenSSL has no dedicated API to set the minimum version to the maximum
  201. * available version, and the other way around. We have to figure out the
  202. * minimum and maximum available version on our own and hope for the best.
  203. */
  204. #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
  205. PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
  206. #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
  207. PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
  208. #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
  209. PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
  210. #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
  211. PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
  212. #elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
  213. PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
  214. #else
  215. #error "PY_PROTO_MINIMUM_AVAILABLE not found"
  216. #endif
  217. #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
  218. PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
  219. #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
  220. PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
  221. #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
  222. PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
  223. #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
  224. PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
  225. #elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
  226. PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
  227. #else
  228. #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
  229. #endif
  230. };
  231. /* SSL socket object */
  232. #define X509_NAME_MAXLEN 256
  233. /* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
  234. * older SSL, but let's be safe */
  235. #define PySSL_CB_MAXLEN 128
  236. typedef struct {
  237. PyObject_HEAD
  238. SSL_CTX *ctx;
  239. unsigned char *alpn_protocols;
  240. unsigned int alpn_protocols_len;
  241. PyObject *set_sni_cb;
  242. int check_hostname;
  243. /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
  244. * We have to maintain our own copy. OpenSSL's hostflags default to 0.
  245. */
  246. unsigned int hostflags;
  247. int protocol;
  248. #ifdef TLS1_3_VERSION
  249. int post_handshake_auth;
  250. #endif
  251. PyObject *msg_cb;
  252. PyObject *keylog_filename;
  253. BIO *keylog_bio;
  254. /* Cached module state, also used in SSLSocket and SSLSession code. */
  255. _sslmodulestate *state;
  256. } PySSLContext;
  257. typedef struct {
  258. int ssl; /* last seen error from SSL */
  259. int c; /* last seen error from libc */
  260. #ifdef MS_WINDOWS
  261. int ws; /* last seen error from winsock */
  262. #endif
  263. } _PySSLError;
  264. typedef struct {
  265. PyObject_HEAD
  266. PyObject *Socket; /* weakref to socket on which we're layered */
  267. SSL *ssl;
  268. PySSLContext *ctx; /* weakref to SSL context */
  269. char shutdown_seen_zero;
  270. enum py_ssl_server_or_client socket_type;
  271. PyObject *owner; /* Python level "owner" passed to servername callback */
  272. PyObject *server_hostname;
  273. _PySSLError err; /* last seen error from various sources */
  274. /* Some SSL callbacks don't have error reporting. Callback wrappers
  275. * store exception information on the socket. The handshake, read, write,
  276. * and shutdown methods check for chained exceptions.
  277. */
  278. PyObject *exc;
  279. } PySSLSocket;
  280. typedef struct {
  281. PyObject_HEAD
  282. BIO *bio;
  283. int eof_written;
  284. } PySSLMemoryBIO;
  285. typedef struct {
  286. PyObject_HEAD
  287. SSL_SESSION *session;
  288. PySSLContext *ctx;
  289. } PySSLSession;
  290. static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
  291. {
  292. _PySSLError err = { 0 };
  293. if (failed) {
  294. #ifdef MS_WINDOWS
  295. err.ws = WSAGetLastError();
  296. _PySSL_FIX_ERRNO;
  297. #endif
  298. err.c = errno;
  299. err.ssl = SSL_get_error(ssl, retcode);
  300. }
  301. return err;
  302. }
  303. /*[clinic input]
  304. module _ssl
  305. class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
  306. class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
  307. class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
  308. class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
  309. [clinic start generated code]*/
  310. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
  311. #include "clinic/_ssl.c.h"
  312. static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
  313. static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
  314. static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
  315. typedef enum {
  316. SOCKET_IS_NONBLOCKING,
  317. SOCKET_IS_BLOCKING,
  318. SOCKET_HAS_TIMED_OUT,
  319. SOCKET_HAS_BEEN_CLOSED,
  320. SOCKET_TOO_LARGE_FOR_SELECT,
  321. SOCKET_OPERATION_OK
  322. } timeout_state;
  323. /* Wrap error strings with filename and line # */
  324. #define ERRSTR1(x,y,z) (x ":" y ": " z)
  325. #define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
  326. /* Get the socket from a PySSLSocket, if it has one */
  327. #define GET_SOCKET(obj) ((obj)->Socket ? \
  328. (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
  329. /* If sock is NULL, use a timeout of 0 second */
  330. #define GET_SOCKET_TIMEOUT(sock) \
  331. ((sock != NULL) ? (sock)->sock_timeout : 0)
  332. #include "_ssl/debughelpers.c"
  333. /*
  334. * SSL errors.
  335. */
  336. PyDoc_STRVAR(SSLError_doc,
  337. "An error occurred in the SSL implementation.");
  338. PyDoc_STRVAR(SSLCertVerificationError_doc,
  339. "A certificate could not be verified.");
  340. PyDoc_STRVAR(SSLZeroReturnError_doc,
  341. "SSL/TLS session closed cleanly.");
  342. PyDoc_STRVAR(SSLWantReadError_doc,
  343. "Non-blocking SSL socket needs to read more data\n"
  344. "before the requested operation can be completed.");
  345. PyDoc_STRVAR(SSLWantWriteError_doc,
  346. "Non-blocking SSL socket needs to write more data\n"
  347. "before the requested operation can be completed.");
  348. PyDoc_STRVAR(SSLSyscallError_doc,
  349. "System error when attempting SSL operation.");
  350. PyDoc_STRVAR(SSLEOFError_doc,
  351. "SSL/TLS connection terminated abruptly.");
  352. static PyObject *
  353. SSLError_str(PyOSErrorObject *self)
  354. {
  355. if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
  356. return Py_NewRef(self->strerror);
  357. }
  358. else
  359. return PyObject_Str(self->args);
  360. }
  361. static PyType_Slot sslerror_type_slots[] = {
  362. {Py_tp_doc, (void*)SSLError_doc},
  363. {Py_tp_str, SSLError_str},
  364. {0, 0},
  365. };
  366. static PyType_Spec sslerror_type_spec = {
  367. .name = "ssl.SSLError",
  368. .basicsize = sizeof(PyOSErrorObject),
  369. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
  370. .slots = sslerror_type_slots
  371. };
  372. static void
  373. fill_and_set_sslerror(_sslmodulestate *state,
  374. PySSLSocket *sslsock, PyObject *type, int ssl_errno,
  375. const char *errstr, int lineno, unsigned long errcode)
  376. {
  377. PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
  378. PyObject *verify_obj = NULL, *verify_code_obj = NULL;
  379. PyObject *init_value, *msg, *key;
  380. if (errcode != 0) {
  381. int lib, reason;
  382. lib = ERR_GET_LIB(errcode);
  383. reason = ERR_GET_REASON(errcode);
  384. key = Py_BuildValue("ii", lib, reason);
  385. if (key == NULL)
  386. goto fail;
  387. reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
  388. Py_DECREF(key);
  389. if (reason_obj == NULL && PyErr_Occurred()) {
  390. goto fail;
  391. }
  392. key = PyLong_FromLong(lib);
  393. if (key == NULL)
  394. goto fail;
  395. lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
  396. Py_DECREF(key);
  397. if (lib_obj == NULL && PyErr_Occurred()) {
  398. goto fail;
  399. }
  400. if (errstr == NULL)
  401. errstr = ERR_reason_error_string(errcode);
  402. }
  403. if (errstr == NULL)
  404. errstr = "unknown error";
  405. /* verify code for cert validation error */
  406. if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
  407. const char *verify_str = NULL;
  408. long verify_code;
  409. verify_code = SSL_get_verify_result(sslsock->ssl);
  410. verify_code_obj = PyLong_FromLong(verify_code);
  411. if (verify_code_obj == NULL) {
  412. goto fail;
  413. }
  414. switch (verify_code) {
  415. case X509_V_ERR_HOSTNAME_MISMATCH:
  416. verify_obj = PyUnicode_FromFormat(
  417. "Hostname mismatch, certificate is not valid for '%S'.",
  418. sslsock->server_hostname
  419. );
  420. break;
  421. case X509_V_ERR_IP_ADDRESS_MISMATCH:
  422. verify_obj = PyUnicode_FromFormat(
  423. "IP address mismatch, certificate is not valid for '%S'.",
  424. sslsock->server_hostname
  425. );
  426. break;
  427. default:
  428. verify_str = X509_verify_cert_error_string(verify_code);
  429. if (verify_str != NULL) {
  430. verify_obj = PyUnicode_FromString(verify_str);
  431. } else {
  432. verify_obj = Py_NewRef(Py_None);
  433. }
  434. break;
  435. }
  436. if (verify_obj == NULL) {
  437. goto fail;
  438. }
  439. }
  440. if (verify_obj && reason_obj && lib_obj)
  441. msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
  442. lib_obj, reason_obj, errstr, verify_obj,
  443. lineno);
  444. else if (reason_obj && lib_obj)
  445. msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
  446. lib_obj, reason_obj, errstr, lineno);
  447. else if (lib_obj)
  448. msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
  449. lib_obj, errstr, lineno);
  450. else
  451. msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
  452. if (msg == NULL)
  453. goto fail;
  454. init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
  455. if (init_value == NULL)
  456. goto fail;
  457. err_value = PyObject_CallObject(type, init_value);
  458. Py_DECREF(init_value);
  459. if (err_value == NULL)
  460. goto fail;
  461. if (reason_obj == NULL)
  462. reason_obj = Py_None;
  463. if (PyObject_SetAttr(err_value, state->str_reason, reason_obj))
  464. goto fail;
  465. if (lib_obj == NULL)
  466. lib_obj = Py_None;
  467. if (PyObject_SetAttr(err_value, state->str_library, lib_obj))
  468. goto fail;
  469. if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
  470. /* Only set verify code / message for SSLCertVerificationError */
  471. if (PyObject_SetAttr(err_value, state->str_verify_code,
  472. verify_code_obj))
  473. goto fail;
  474. if (PyObject_SetAttr(err_value, state->str_verify_message, verify_obj))
  475. goto fail;
  476. }
  477. PyErr_SetObject(type, err_value);
  478. fail:
  479. Py_XDECREF(err_value);
  480. Py_XDECREF(verify_code_obj);
  481. Py_XDECREF(verify_obj);
  482. }
  483. static int
  484. PySSL_ChainExceptions(PySSLSocket *sslsock) {
  485. if (sslsock->exc == NULL)
  486. return 0;
  487. _PyErr_ChainExceptions1(sslsock->exc);
  488. sslsock->exc = NULL;
  489. return -1;
  490. }
  491. static PyObject *
  492. PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
  493. {
  494. PyObject *type;
  495. char *errstr = NULL;
  496. _PySSLError err;
  497. enum py_ssl_error p = PY_SSL_ERROR_NONE;
  498. unsigned long e = 0;
  499. assert(sslsock != NULL);
  500. _sslmodulestate *state = get_state_sock(sslsock);
  501. type = state->PySSLErrorObject;
  502. assert(ret <= 0);
  503. e = ERR_peek_last_error();
  504. if (sslsock->ssl != NULL) {
  505. err = sslsock->err;
  506. switch (err.ssl) {
  507. case SSL_ERROR_ZERO_RETURN:
  508. errstr = "TLS/SSL connection has been closed (EOF)";
  509. type = state->PySSLZeroReturnErrorObject;
  510. p = PY_SSL_ERROR_ZERO_RETURN;
  511. break;
  512. case SSL_ERROR_WANT_READ:
  513. errstr = "The operation did not complete (read)";
  514. type = state->PySSLWantReadErrorObject;
  515. p = PY_SSL_ERROR_WANT_READ;
  516. break;
  517. case SSL_ERROR_WANT_WRITE:
  518. p = PY_SSL_ERROR_WANT_WRITE;
  519. type = state->PySSLWantWriteErrorObject;
  520. errstr = "The operation did not complete (write)";
  521. break;
  522. case SSL_ERROR_WANT_X509_LOOKUP:
  523. p = PY_SSL_ERROR_WANT_X509_LOOKUP;
  524. errstr = "The operation did not complete (X509 lookup)";
  525. break;
  526. case SSL_ERROR_WANT_CONNECT:
  527. p = PY_SSL_ERROR_WANT_CONNECT;
  528. errstr = "The operation did not complete (connect)";
  529. break;
  530. case SSL_ERROR_SYSCALL:
  531. {
  532. if (e == 0) {
  533. PySocketSockObject *s = GET_SOCKET(sslsock);
  534. if (ret == 0 || (((PyObject *)s) == Py_None)) {
  535. p = PY_SSL_ERROR_EOF;
  536. type = state->PySSLEOFErrorObject;
  537. errstr = "EOF occurred in violation of protocol";
  538. } else if (s && ret == -1) {
  539. /* underlying BIO reported an I/O error */
  540. ERR_clear_error();
  541. #ifdef MS_WINDOWS
  542. if (err.ws) {
  543. return PyErr_SetFromWindowsErr(err.ws);
  544. }
  545. #endif
  546. if (err.c) {
  547. errno = err.c;
  548. return PyErr_SetFromErrno(PyExc_OSError);
  549. }
  550. else {
  551. p = PY_SSL_ERROR_EOF;
  552. type = state->PySSLEOFErrorObject;
  553. errstr = "EOF occurred in violation of protocol";
  554. }
  555. } else { /* possible? */
  556. p = PY_SSL_ERROR_SYSCALL;
  557. type = state->PySSLSyscallErrorObject;
  558. errstr = "Some I/O error occurred";
  559. }
  560. } else {
  561. if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
  562. ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
  563. type = state->PySSLCertVerificationErrorObject;
  564. }
  565. if (ERR_GET_LIB(e) == ERR_LIB_SYS) {
  566. // A system error is being reported; reason is set to errno
  567. errno = ERR_GET_REASON(e);
  568. return PyErr_SetFromErrno(PyExc_OSError);
  569. }
  570. p = PY_SSL_ERROR_SYSCALL;
  571. }
  572. break;
  573. }
  574. case SSL_ERROR_SSL:
  575. {
  576. p = PY_SSL_ERROR_SSL;
  577. if (e == 0) {
  578. /* possible? */
  579. errstr = "A failure in the SSL library occurred";
  580. }
  581. if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
  582. ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
  583. type = state->PySSLCertVerificationErrorObject;
  584. }
  585. #if defined(SSL_R_UNEXPECTED_EOF_WHILE_READING)
  586. /* OpenSSL 3.0 changed transport EOF from SSL_ERROR_SYSCALL with
  587. * zero return value to SSL_ERROR_SSL with a special error code. */
  588. if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
  589. ERR_GET_REASON(e) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
  590. p = PY_SSL_ERROR_EOF;
  591. type = state->PySSLEOFErrorObject;
  592. errstr = "EOF occurred in violation of protocol";
  593. }
  594. #endif
  595. if (ERR_GET_LIB(e) == ERR_LIB_SYS) {
  596. // A system error is being reported; reason is set to errno
  597. errno = ERR_GET_REASON(e);
  598. return PyErr_SetFromErrno(PyExc_OSError);
  599. }
  600. break;
  601. }
  602. default:
  603. p = PY_SSL_ERROR_INVALID_ERROR_CODE;
  604. errstr = "Invalid error code";
  605. }
  606. }
  607. fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
  608. ERR_clear_error();
  609. PySSL_ChainExceptions(sslsock);
  610. return NULL;
  611. }
  612. static PyObject *
  613. _setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
  614. {
  615. if (errstr == NULL)
  616. errcode = ERR_peek_last_error();
  617. else
  618. errcode = 0;
  619. fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
  620. ERR_clear_error();
  621. return NULL;
  622. }
  623. static int
  624. _ssl_deprecated(const char* msg, int stacklevel) {
  625. return PyErr_WarnEx(
  626. PyExc_DeprecationWarning, msg, stacklevel
  627. );
  628. }
  629. #define PY_SSL_DEPRECATED(name, stacklevel, ret) \
  630. if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
  631. /*
  632. * SSL objects
  633. */
  634. static int
  635. _ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
  636. {
  637. int retval = -1;
  638. ASN1_OCTET_STRING *ip;
  639. PyObject *hostname;
  640. size_t len;
  641. assert(server_hostname);
  642. /* Disable OpenSSL's special mode with leading dot in hostname:
  643. * When name starts with a dot (e.g ".example.com"), it will be
  644. * matched by a certificate valid for any sub-domain of name.
  645. */
  646. len = strlen(server_hostname);
  647. if (len == 0 || *server_hostname == '.') {
  648. PyErr_SetString(
  649. PyExc_ValueError,
  650. "server_hostname cannot be an empty string or start with a "
  651. "leading dot.");
  652. return retval;
  653. }
  654. /* inet_pton is not available on all platforms. */
  655. ip = a2i_IPADDRESS(server_hostname);
  656. if (ip == NULL) {
  657. ERR_clear_error();
  658. }
  659. hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
  660. if (hostname == NULL) {
  661. goto error;
  662. }
  663. self->server_hostname = hostname;
  664. /* Only send SNI extension for non-IP hostnames */
  665. if (ip == NULL) {
  666. if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
  667. _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
  668. goto error;
  669. }
  670. }
  671. if (self->ctx->check_hostname) {
  672. X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
  673. if (ip == NULL) {
  674. if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
  675. strlen(server_hostname))) {
  676. _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
  677. goto error;
  678. }
  679. } else {
  680. if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
  681. ASN1_STRING_length(ip))) {
  682. _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
  683. goto error;
  684. }
  685. }
  686. }
  687. retval = 0;
  688. error:
  689. if (ip != NULL) {
  690. ASN1_OCTET_STRING_free(ip);
  691. }
  692. return retval;
  693. }
  694. static PySSLSocket *
  695. newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
  696. enum py_ssl_server_or_client socket_type,
  697. char *server_hostname,
  698. PyObject *owner, PyObject *session,
  699. PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
  700. {
  701. PySSLSocket *self;
  702. SSL_CTX *ctx = sslctx->ctx;
  703. _PySSLError err = { 0 };
  704. if ((socket_type == PY_SSL_SERVER) &&
  705. (sslctx->protocol == PY_SSL_VERSION_TLS_CLIENT)) {
  706. _setSSLError(get_state_ctx(sslctx),
  707. "Cannot create a server socket with a "
  708. "PROTOCOL_TLS_CLIENT context", 0, __FILE__, __LINE__);
  709. return NULL;
  710. }
  711. if ((socket_type == PY_SSL_CLIENT) &&
  712. (sslctx->protocol == PY_SSL_VERSION_TLS_SERVER)) {
  713. _setSSLError(get_state_ctx(sslctx),
  714. "Cannot create a client socket with a "
  715. "PROTOCOL_TLS_SERVER context", 0, __FILE__, __LINE__);
  716. return NULL;
  717. }
  718. self = PyObject_GC_New(PySSLSocket,
  719. get_state_ctx(sslctx)->PySSLSocket_Type);
  720. if (self == NULL)
  721. return NULL;
  722. self->ssl = NULL;
  723. self->Socket = NULL;
  724. self->ctx = (PySSLContext*)Py_NewRef(sslctx);
  725. self->shutdown_seen_zero = 0;
  726. self->owner = NULL;
  727. self->server_hostname = NULL;
  728. self->err = err;
  729. self->exc = NULL;
  730. /* Make sure the SSL error state is initialized */
  731. ERR_clear_error();
  732. PySSL_BEGIN_ALLOW_THREADS
  733. self->ssl = SSL_new(ctx);
  734. PySSL_END_ALLOW_THREADS
  735. if (self->ssl == NULL) {
  736. Py_DECREF(self);
  737. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  738. return NULL;
  739. }
  740. /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
  741. #if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
  742. X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
  743. X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
  744. #endif
  745. SSL_set_app_data(self->ssl, self);
  746. if (sock) {
  747. SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
  748. } else {
  749. /* BIOs are reference counted and SSL_set_bio borrows our reference.
  750. * To prevent a double free in memory_bio_dealloc() we need to take an
  751. * extra reference here. */
  752. BIO_up_ref(inbio->bio);
  753. BIO_up_ref(outbio->bio);
  754. SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
  755. }
  756. SSL_set_mode(self->ssl,
  757. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
  758. #ifdef TLS1_3_VERSION
  759. if (sslctx->post_handshake_auth == 1) {
  760. if (socket_type == PY_SSL_SERVER) {
  761. /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
  762. * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
  763. * only in combination with SSL_VERIFY_PEER flag. */
  764. int mode = SSL_get_verify_mode(self->ssl);
  765. if (mode & SSL_VERIFY_PEER) {
  766. int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
  767. verify_cb = SSL_get_verify_callback(self->ssl);
  768. mode |= SSL_VERIFY_POST_HANDSHAKE;
  769. SSL_set_verify(self->ssl, mode, verify_cb);
  770. }
  771. } else {
  772. /* client socket */
  773. SSL_set_post_handshake_auth(self->ssl, 1);
  774. }
  775. }
  776. #endif
  777. if (server_hostname != NULL) {
  778. if (_ssl_configure_hostname(self, server_hostname) < 0) {
  779. Py_DECREF(self);
  780. return NULL;
  781. }
  782. }
  783. /* If the socket is in non-blocking mode or timeout mode, set the BIO
  784. * to non-blocking mode (blocking is the default)
  785. */
  786. if (sock && sock->sock_timeout >= 0) {
  787. BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
  788. BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
  789. }
  790. PySSL_BEGIN_ALLOW_THREADS
  791. if (socket_type == PY_SSL_CLIENT)
  792. SSL_set_connect_state(self->ssl);
  793. else
  794. SSL_set_accept_state(self->ssl);
  795. PySSL_END_ALLOW_THREADS
  796. self->socket_type = socket_type;
  797. if (sock != NULL) {
  798. self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
  799. if (self->Socket == NULL) {
  800. Py_DECREF(self);
  801. return NULL;
  802. }
  803. }
  804. if (owner && owner != Py_None) {
  805. if (PySSL_set_owner(self, owner, NULL) == -1) {
  806. Py_DECREF(self);
  807. return NULL;
  808. }
  809. }
  810. if (session && session != Py_None) {
  811. if (PySSL_set_session(self, session, NULL) == -1) {
  812. Py_DECREF(self);
  813. return NULL;
  814. }
  815. }
  816. PyObject_GC_Track(self);
  817. return self;
  818. }
  819. /* SSL object methods */
  820. /*[clinic input]
  821. _ssl._SSLSocket.do_handshake
  822. [clinic start generated code]*/
  823. static PyObject *
  824. _ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
  825. /*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
  826. {
  827. int ret;
  828. _PySSLError err;
  829. int sockstate, nonblocking;
  830. PySocketSockObject *sock = GET_SOCKET(self);
  831. _PyTime_t timeout, deadline = 0;
  832. int has_timeout;
  833. if (sock) {
  834. if (((PyObject*)sock) == Py_None) {
  835. _setSSLError(get_state_sock(self),
  836. "Underlying socket connection gone",
  837. PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
  838. return NULL;
  839. }
  840. Py_INCREF(sock);
  841. /* just in case the blocking state of the socket has been changed */
  842. nonblocking = (sock->sock_timeout >= 0);
  843. BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
  844. BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
  845. }
  846. timeout = GET_SOCKET_TIMEOUT(sock);
  847. has_timeout = (timeout > 0);
  848. if (has_timeout) {
  849. deadline = _PyDeadline_Init(timeout);
  850. }
  851. /* Actually negotiate SSL connection */
  852. /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
  853. do {
  854. PySSL_BEGIN_ALLOW_THREADS
  855. ret = SSL_do_handshake(self->ssl);
  856. err = _PySSL_errno(ret < 1, self->ssl, ret);
  857. PySSL_END_ALLOW_THREADS
  858. self->err = err;
  859. if (PyErr_CheckSignals())
  860. goto error;
  861. if (has_timeout)
  862. timeout = _PyDeadline_Get(deadline);
  863. if (err.ssl == SSL_ERROR_WANT_READ) {
  864. sockstate = PySSL_select(sock, 0, timeout);
  865. } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
  866. sockstate = PySSL_select(sock, 1, timeout);
  867. } else {
  868. sockstate = SOCKET_OPERATION_OK;
  869. }
  870. if (sockstate == SOCKET_HAS_TIMED_OUT) {
  871. PyErr_SetString(PyExc_TimeoutError,
  872. ERRSTR("The handshake operation timed out"));
  873. goto error;
  874. } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
  875. PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
  876. ERRSTR("Underlying socket has been closed."));
  877. goto error;
  878. } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
  879. PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
  880. ERRSTR("Underlying socket too large for select()."));
  881. goto error;
  882. } else if (sockstate == SOCKET_IS_NONBLOCKING) {
  883. break;
  884. }
  885. } while (err.ssl == SSL_ERROR_WANT_READ ||
  886. err.ssl == SSL_ERROR_WANT_WRITE);
  887. Py_XDECREF(sock);
  888. if (ret < 1)
  889. return PySSL_SetError(self, ret, __FILE__, __LINE__);
  890. if (PySSL_ChainExceptions(self) < 0)
  891. return NULL;
  892. Py_RETURN_NONE;
  893. error:
  894. Py_XDECREF(sock);
  895. PySSL_ChainExceptions(self);
  896. return NULL;
  897. }
  898. static PyObject *
  899. _asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
  900. {
  901. char buf[X509_NAME_MAXLEN];
  902. char *namebuf = buf;
  903. int buflen;
  904. PyObject *name_obj = NULL;
  905. buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
  906. if (buflen < 0) {
  907. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  908. return NULL;
  909. }
  910. /* initial buffer is too small for oid + terminating null byte */
  911. if (buflen > X509_NAME_MAXLEN - 1) {
  912. /* make OBJ_obj2txt() calculate the required buflen */
  913. buflen = OBJ_obj2txt(NULL, 0, name, no_name);
  914. /* allocate len + 1 for terminating NULL byte */
  915. namebuf = PyMem_Malloc(buflen + 1);
  916. if (namebuf == NULL) {
  917. PyErr_NoMemory();
  918. return NULL;
  919. }
  920. buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
  921. if (buflen < 0) {
  922. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  923. goto done;
  924. }
  925. }
  926. if (!buflen && no_name) {
  927. name_obj = Py_NewRef(Py_None);
  928. }
  929. else {
  930. name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
  931. }
  932. done:
  933. if (buf != namebuf) {
  934. PyMem_Free(namebuf);
  935. }
  936. return name_obj;
  937. }
  938. static PyObject *
  939. _create_tuple_for_attribute(_sslmodulestate *state,
  940. ASN1_OBJECT *name, ASN1_STRING *value)
  941. {
  942. Py_ssize_t buflen;
  943. PyObject *pyattr;
  944. PyObject *pyname = _asn1obj2py(state, name, 0);
  945. if (pyname == NULL) {
  946. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  947. return NULL;
  948. }
  949. if (ASN1_STRING_type(value) == V_ASN1_BIT_STRING) {
  950. buflen = ASN1_STRING_length(value);
  951. pyattr = Py_BuildValue("Ny#", pyname, ASN1_STRING_get0_data(value), buflen);
  952. } else {
  953. unsigned char *valuebuf = NULL;
  954. buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
  955. if (buflen < 0) {
  956. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  957. Py_DECREF(pyname);
  958. return NULL;
  959. }
  960. pyattr = Py_BuildValue("Ns#", pyname, valuebuf, buflen);
  961. OPENSSL_free(valuebuf);
  962. }
  963. return pyattr;
  964. }
  965. static PyObject *
  966. _create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
  967. {
  968. PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
  969. PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
  970. PyObject *rdnt;
  971. PyObject *attr = NULL; /* tuple to hold an attribute */
  972. int entry_count = X509_NAME_entry_count(xname);
  973. X509_NAME_ENTRY *entry;
  974. ASN1_OBJECT *name;
  975. ASN1_STRING *value;
  976. int index_counter;
  977. int rdn_level = -1;
  978. int retcode;
  979. dn = PyList_New(0);
  980. if (dn == NULL)
  981. return NULL;
  982. /* now create another tuple to hold the top-level RDN */
  983. rdn = PyList_New(0);
  984. if (rdn == NULL)
  985. goto fail0;
  986. for (index_counter = 0;
  987. index_counter < entry_count;
  988. index_counter++)
  989. {
  990. entry = X509_NAME_get_entry(xname, index_counter);
  991. /* check to see if we've gotten to a new RDN */
  992. if (rdn_level >= 0) {
  993. if (rdn_level != X509_NAME_ENTRY_set(entry)) {
  994. /* yes, new RDN */
  995. /* add old RDN to DN */
  996. rdnt = PyList_AsTuple(rdn);
  997. Py_DECREF(rdn);
  998. if (rdnt == NULL)
  999. goto fail0;
  1000. retcode = PyList_Append(dn, rdnt);
  1001. Py_DECREF(rdnt);
  1002. if (retcode < 0)
  1003. goto fail0;
  1004. /* create new RDN */
  1005. rdn = PyList_New(0);
  1006. if (rdn == NULL)
  1007. goto fail0;
  1008. }
  1009. }
  1010. rdn_level = X509_NAME_ENTRY_set(entry);
  1011. /* now add this attribute to the current RDN */
  1012. name = X509_NAME_ENTRY_get_object(entry);
  1013. value = X509_NAME_ENTRY_get_data(entry);
  1014. attr = _create_tuple_for_attribute(state, name, value);
  1015. /*
  1016. fprintf(stderr, "RDN level %d, attribute %s: %s\n",
  1017. entry->set,
  1018. PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
  1019. PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
  1020. */
  1021. if (attr == NULL)
  1022. goto fail1;
  1023. retcode = PyList_Append(rdn, attr);
  1024. Py_DECREF(attr);
  1025. if (retcode < 0)
  1026. goto fail1;
  1027. }
  1028. /* now, there's typically a dangling RDN */
  1029. if (rdn != NULL) {
  1030. if (PyList_GET_SIZE(rdn) > 0) {
  1031. rdnt = PyList_AsTuple(rdn);
  1032. Py_DECREF(rdn);
  1033. if (rdnt == NULL)
  1034. goto fail0;
  1035. retcode = PyList_Append(dn, rdnt);
  1036. Py_DECREF(rdnt);
  1037. if (retcode < 0)
  1038. goto fail0;
  1039. }
  1040. else {
  1041. Py_DECREF(rdn);
  1042. }
  1043. }
  1044. /* convert list to tuple */
  1045. rdnt = PyList_AsTuple(dn);
  1046. Py_DECREF(dn);
  1047. if (rdnt == NULL)
  1048. return NULL;
  1049. return rdnt;
  1050. fail1:
  1051. Py_XDECREF(rdn);
  1052. fail0:
  1053. Py_XDECREF(dn);
  1054. return NULL;
  1055. }
  1056. static PyObject *
  1057. _get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
  1058. /* this code follows the procedure outlined in
  1059. OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
  1060. function to extract the STACK_OF(GENERAL_NAME),
  1061. then iterates through the stack to add the
  1062. names. */
  1063. int j;
  1064. PyObject *peer_alt_names = Py_None;
  1065. PyObject *v = NULL, *t;
  1066. GENERAL_NAMES *names = NULL;
  1067. GENERAL_NAME *name;
  1068. BIO *biobuf = NULL;
  1069. char buf[2048];
  1070. char *vptr;
  1071. int len;
  1072. if (certificate == NULL)
  1073. return peer_alt_names;
  1074. /* get a memory buffer */
  1075. biobuf = BIO_new(BIO_s_mem());
  1076. if (biobuf == NULL) {
  1077. PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
  1078. return NULL;
  1079. }
  1080. names = (GENERAL_NAMES *)X509_get_ext_d2i(
  1081. certificate, NID_subject_alt_name, NULL, NULL);
  1082. if (names != NULL) {
  1083. if (peer_alt_names == Py_None) {
  1084. peer_alt_names = PyList_New(0);
  1085. if (peer_alt_names == NULL)
  1086. goto fail;
  1087. }
  1088. for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
  1089. /* get a rendering of each name in the set of names */
  1090. int gntype;
  1091. ASN1_STRING *as = NULL;
  1092. name = sk_GENERAL_NAME_value(names, j);
  1093. gntype = name->type;
  1094. switch (gntype) {
  1095. case GEN_DIRNAME:
  1096. /* we special-case DirName as a tuple of
  1097. tuples of attributes */
  1098. t = PyTuple_New(2);
  1099. if (t == NULL) {
  1100. goto fail;
  1101. }
  1102. v = PyUnicode_FromString("DirName");
  1103. if (v == NULL) {
  1104. Py_DECREF(t);
  1105. goto fail;
  1106. }
  1107. PyTuple_SET_ITEM(t, 0, v);
  1108. v = _create_tuple_for_X509_NAME(state, name->d.dirn);
  1109. if (v == NULL) {
  1110. Py_DECREF(t);
  1111. goto fail;
  1112. }
  1113. PyTuple_SET_ITEM(t, 1, v);
  1114. break;
  1115. case GEN_EMAIL:
  1116. case GEN_DNS:
  1117. case GEN_URI:
  1118. /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
  1119. correctly, CVE-2013-4238 */
  1120. t = PyTuple_New(2);
  1121. if (t == NULL)
  1122. goto fail;
  1123. switch (gntype) {
  1124. case GEN_EMAIL:
  1125. v = PyUnicode_FromString("email");
  1126. as = name->d.rfc822Name;
  1127. break;
  1128. case GEN_DNS:
  1129. v = PyUnicode_FromString("DNS");
  1130. as = name->d.dNSName;
  1131. break;
  1132. case GEN_URI:
  1133. v = PyUnicode_FromString("URI");
  1134. as = name->d.uniformResourceIdentifier;
  1135. break;
  1136. }
  1137. if (v == NULL) {
  1138. Py_DECREF(t);
  1139. goto fail;
  1140. }
  1141. PyTuple_SET_ITEM(t, 0, v);
  1142. v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
  1143. ASN1_STRING_length(as));
  1144. if (v == NULL) {
  1145. Py_DECREF(t);
  1146. goto fail;
  1147. }
  1148. PyTuple_SET_ITEM(t, 1, v);
  1149. break;
  1150. case GEN_RID:
  1151. t = PyTuple_New(2);
  1152. if (t == NULL)
  1153. goto fail;
  1154. v = PyUnicode_FromString("Registered ID");
  1155. if (v == NULL) {
  1156. Py_DECREF(t);
  1157. goto fail;
  1158. }
  1159. PyTuple_SET_ITEM(t, 0, v);
  1160. len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
  1161. if (len < 0) {
  1162. Py_DECREF(t);
  1163. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  1164. goto fail;
  1165. } else if (len >= (int)sizeof(buf)) {
  1166. v = PyUnicode_FromString("<INVALID>");
  1167. } else {
  1168. v = PyUnicode_FromStringAndSize(buf, len);
  1169. }
  1170. if (v == NULL) {
  1171. Py_DECREF(t);
  1172. goto fail;
  1173. }
  1174. PyTuple_SET_ITEM(t, 1, v);
  1175. break;
  1176. case GEN_IPADD:
  1177. /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
  1178. * the trailing newline. Remove it in all versions
  1179. */
  1180. t = PyTuple_New(2);
  1181. if (t == NULL)
  1182. goto fail;
  1183. v = PyUnicode_FromString("IP Address");
  1184. if (v == NULL) {
  1185. Py_DECREF(t);
  1186. goto fail;
  1187. }
  1188. PyTuple_SET_ITEM(t, 0, v);
  1189. if (name->d.ip->length == 4) {
  1190. unsigned char *p = name->d.ip->data;
  1191. v = PyUnicode_FromFormat(
  1192. "%d.%d.%d.%d",
  1193. p[0], p[1], p[2], p[3]
  1194. );
  1195. } else if (name->d.ip->length == 16) {
  1196. unsigned char *p = name->d.ip->data;
  1197. v = PyUnicode_FromFormat(
  1198. "%X:%X:%X:%X:%X:%X:%X:%X",
  1199. p[0] << 8 | p[1],
  1200. p[2] << 8 | p[3],
  1201. p[4] << 8 | p[5],
  1202. p[6] << 8 | p[7],
  1203. p[8] << 8 | p[9],
  1204. p[10] << 8 | p[11],
  1205. p[12] << 8 | p[13],
  1206. p[14] << 8 | p[15]
  1207. );
  1208. } else {
  1209. v = PyUnicode_FromString("<invalid>");
  1210. }
  1211. if (v == NULL) {
  1212. Py_DECREF(t);
  1213. goto fail;
  1214. }
  1215. PyTuple_SET_ITEM(t, 1, v);
  1216. break;
  1217. default:
  1218. /* for everything else, we use the OpenSSL print form */
  1219. switch (gntype) {
  1220. /* check for new general name type */
  1221. case GEN_OTHERNAME:
  1222. case GEN_X400:
  1223. case GEN_EDIPARTY:
  1224. case GEN_RID:
  1225. break;
  1226. default:
  1227. if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  1228. "Unknown general name type %d",
  1229. gntype) == -1) {
  1230. goto fail;
  1231. }
  1232. break;
  1233. }
  1234. (void) BIO_reset(biobuf);
  1235. GENERAL_NAME_print(biobuf, name);
  1236. len = BIO_gets(biobuf, buf, sizeof(buf)-1);
  1237. if (len < 0) {
  1238. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  1239. goto fail;
  1240. }
  1241. vptr = strchr(buf, ':');
  1242. if (vptr == NULL) {
  1243. PyErr_Format(PyExc_ValueError,
  1244. "Invalid value %.200s",
  1245. buf);
  1246. goto fail;
  1247. }
  1248. t = PyTuple_New(2);
  1249. if (t == NULL)
  1250. goto fail;
  1251. v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
  1252. if (v == NULL) {
  1253. Py_DECREF(t);
  1254. goto fail;
  1255. }
  1256. PyTuple_SET_ITEM(t, 0, v);
  1257. v = PyUnicode_FromStringAndSize((vptr + 1),
  1258. (len - (vptr - buf + 1)));
  1259. if (v == NULL) {
  1260. Py_DECREF(t);
  1261. goto fail;
  1262. }
  1263. PyTuple_SET_ITEM(t, 1, v);
  1264. break;
  1265. }
  1266. /* and add that rendering to the list */
  1267. if (PyList_Append(peer_alt_names, t) < 0) {
  1268. Py_DECREF(t);
  1269. goto fail;
  1270. }
  1271. Py_DECREF(t);
  1272. }
  1273. sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
  1274. }
  1275. BIO_free(biobuf);
  1276. if (peer_alt_names != Py_None) {
  1277. v = PyList_AsTuple(peer_alt_names);
  1278. Py_DECREF(peer_alt_names);
  1279. return v;
  1280. } else {
  1281. return peer_alt_names;
  1282. }
  1283. fail:
  1284. if (biobuf != NULL)
  1285. BIO_free(biobuf);
  1286. if (peer_alt_names != Py_None) {
  1287. Py_XDECREF(peer_alt_names);
  1288. }
  1289. return NULL;
  1290. }
  1291. static PyObject *
  1292. _get_aia_uri(X509 *certificate, int nid) {
  1293. PyObject *lst = NULL, *ostr = NULL;
  1294. int i, result;
  1295. AUTHORITY_INFO_ACCESS *info;
  1296. info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
  1297. if (info == NULL)
  1298. return Py_None;
  1299. if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
  1300. AUTHORITY_INFO_ACCESS_free(info);
  1301. return Py_None;
  1302. }
  1303. if ((lst = PyList_New(0)) == NULL) {
  1304. goto fail;
  1305. }
  1306. for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
  1307. ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
  1308. ASN1_IA5STRING *uri;
  1309. if ((OBJ_obj2nid(ad->method) != nid) ||
  1310. (ad->location->type != GEN_URI)) {
  1311. continue;
  1312. }
  1313. uri = ad->location->d.uniformResourceIdentifier;
  1314. ostr = PyUnicode_FromStringAndSize((char *)uri->data,
  1315. uri->length);
  1316. if (ostr == NULL) {
  1317. goto fail;
  1318. }
  1319. result = PyList_Append(lst, ostr);
  1320. Py_DECREF(ostr);
  1321. if (result < 0) {
  1322. goto fail;
  1323. }
  1324. }
  1325. AUTHORITY_INFO_ACCESS_free(info);
  1326. /* convert to tuple or None */
  1327. if (PyList_Size(lst) == 0) {
  1328. Py_DECREF(lst);
  1329. return Py_None;
  1330. } else {
  1331. PyObject *tup;
  1332. tup = PyList_AsTuple(lst);
  1333. Py_DECREF(lst);
  1334. return tup;
  1335. }
  1336. fail:
  1337. AUTHORITY_INFO_ACCESS_free(info);
  1338. Py_XDECREF(lst);
  1339. return NULL;
  1340. }
  1341. static PyObject *
  1342. _get_crl_dp(X509 *certificate) {
  1343. STACK_OF(DIST_POINT) *dps;
  1344. int i, j;
  1345. PyObject *lst, *res = NULL;
  1346. dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
  1347. if (dps == NULL)
  1348. return Py_None;
  1349. lst = PyList_New(0);
  1350. if (lst == NULL)
  1351. goto done;
  1352. for (i=0; i < sk_DIST_POINT_num(dps); i++) {
  1353. DIST_POINT *dp;
  1354. STACK_OF(GENERAL_NAME) *gns;
  1355. dp = sk_DIST_POINT_value(dps, i);
  1356. if (dp->distpoint == NULL) {
  1357. /* Ignore empty DP value, CVE-2019-5010 */
  1358. continue;
  1359. }
  1360. gns = dp->distpoint->name.fullname;
  1361. for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
  1362. GENERAL_NAME *gn;
  1363. ASN1_IA5STRING *uri;
  1364. PyObject *ouri;
  1365. int err;
  1366. gn = sk_GENERAL_NAME_value(gns, j);
  1367. if (gn->type != GEN_URI) {
  1368. continue;
  1369. }
  1370. uri = gn->d.uniformResourceIdentifier;
  1371. ouri = PyUnicode_FromStringAndSize((char *)uri->data,
  1372. uri->length);
  1373. if (ouri == NULL)
  1374. goto done;
  1375. err = PyList_Append(lst, ouri);
  1376. Py_DECREF(ouri);
  1377. if (err < 0)
  1378. goto done;
  1379. }
  1380. }
  1381. /* Convert to tuple. */
  1382. res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
  1383. done:
  1384. Py_XDECREF(lst);
  1385. CRL_DIST_POINTS_free(dps);
  1386. return res;
  1387. }
  1388. static PyObject *
  1389. _decode_certificate(_sslmodulestate *state, X509 *certificate) {
  1390. PyObject *retval = NULL;
  1391. BIO *biobuf = NULL;
  1392. PyObject *peer;
  1393. PyObject *peer_alt_names = NULL;
  1394. PyObject *issuer;
  1395. PyObject *version;
  1396. PyObject *sn_obj;
  1397. PyObject *obj;
  1398. ASN1_INTEGER *serialNumber;
  1399. char buf[2048];
  1400. int len, result;
  1401. const ASN1_TIME *notBefore, *notAfter;
  1402. PyObject *pnotBefore, *pnotAfter;
  1403. retval = PyDict_New();
  1404. if (retval == NULL)
  1405. return NULL;
  1406. peer = _create_tuple_for_X509_NAME(
  1407. state,
  1408. X509_get_subject_name(certificate));
  1409. if (peer == NULL)
  1410. goto fail0;
  1411. if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
  1412. Py_DECREF(peer);
  1413. goto fail0;
  1414. }
  1415. Py_DECREF(peer);
  1416. issuer = _create_tuple_for_X509_NAME(
  1417. state,
  1418. X509_get_issuer_name(certificate));
  1419. if (issuer == NULL)
  1420. goto fail0;
  1421. if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
  1422. Py_DECREF(issuer);
  1423. goto fail0;
  1424. }
  1425. Py_DECREF(issuer);
  1426. version = PyLong_FromLong(X509_get_version(certificate) + 1);
  1427. if (version == NULL)
  1428. goto fail0;
  1429. if (PyDict_SetItemString(retval, "version", version) < 0) {
  1430. Py_DECREF(version);
  1431. goto fail0;
  1432. }
  1433. Py_DECREF(version);
  1434. /* get a memory buffer */
  1435. biobuf = BIO_new(BIO_s_mem());
  1436. if (biobuf == NULL) {
  1437. PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
  1438. goto fail0;
  1439. }
  1440. (void) BIO_reset(biobuf);
  1441. serialNumber = X509_get_serialNumber(certificate);
  1442. /* should not exceed 20 octets, 160 bits, so buf is big enough */
  1443. i2a_ASN1_INTEGER(biobuf, serialNumber);
  1444. len = BIO_gets(biobuf, buf, sizeof(buf)-1);
  1445. if (len < 0) {
  1446. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  1447. goto fail1;
  1448. }
  1449. sn_obj = PyUnicode_FromStringAndSize(buf, len);
  1450. if (sn_obj == NULL)
  1451. goto fail1;
  1452. if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
  1453. Py_DECREF(sn_obj);
  1454. goto fail1;
  1455. }
  1456. Py_DECREF(sn_obj);
  1457. (void) BIO_reset(biobuf);
  1458. notBefore = X509_get0_notBefore(certificate);
  1459. ASN1_TIME_print(biobuf, notBefore);
  1460. len = BIO_gets(biobuf, buf, sizeof(buf)-1);
  1461. if (len < 0) {
  1462. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  1463. goto fail1;
  1464. }
  1465. pnotBefore = PyUnicode_FromStringAndSize(buf, len);
  1466. if (pnotBefore == NULL)
  1467. goto fail1;
  1468. if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
  1469. Py_DECREF(pnotBefore);
  1470. goto fail1;
  1471. }
  1472. Py_DECREF(pnotBefore);
  1473. (void) BIO_reset(biobuf);
  1474. notAfter = X509_get0_notAfter(certificate);
  1475. ASN1_TIME_print(biobuf, notAfter);
  1476. len = BIO_gets(biobuf, buf, sizeof(buf)-1);
  1477. if (len < 0) {
  1478. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  1479. goto fail1;
  1480. }
  1481. pnotAfter = PyUnicode_FromStringAndSize(buf, len);
  1482. if (pnotAfter == NULL)
  1483. goto fail1;
  1484. if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
  1485. Py_DECREF(pnotAfter);
  1486. goto fail1;
  1487. }
  1488. Py_DECREF(pnotAfter);
  1489. /* Now look for subjectAltName */
  1490. peer_alt_names = _get_peer_alt_names(state, certificate);
  1491. if (peer_alt_names == NULL)
  1492. goto fail1;
  1493. else if (peer_alt_names != Py_None) {
  1494. if (PyDict_SetItemString(retval, "subjectAltName",
  1495. peer_alt_names) < 0) {
  1496. Py_DECREF(peer_alt_names);
  1497. goto fail1;
  1498. }
  1499. Py_DECREF(peer_alt_names);
  1500. }
  1501. /* Authority Information Access: OCSP URIs */
  1502. obj = _get_aia_uri(certificate, NID_ad_OCSP);
  1503. if (obj == NULL) {
  1504. goto fail1;
  1505. } else if (obj != Py_None) {
  1506. result = PyDict_SetItemString(retval, "OCSP", obj);
  1507. Py_DECREF(obj);
  1508. if (result < 0) {
  1509. goto fail1;
  1510. }
  1511. }
  1512. obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
  1513. if (obj == NULL) {
  1514. goto fail1;
  1515. } else if (obj != Py_None) {
  1516. result = PyDict_SetItemString(retval, "caIssuers", obj);
  1517. Py_DECREF(obj);
  1518. if (result < 0) {
  1519. goto fail1;
  1520. }
  1521. }
  1522. /* CDP (CRL distribution points) */
  1523. obj = _get_crl_dp(certificate);
  1524. if (obj == NULL) {
  1525. goto fail1;
  1526. } else if (obj != Py_None) {
  1527. result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
  1528. Py_DECREF(obj);
  1529. if (result < 0) {
  1530. goto fail1;
  1531. }
  1532. }
  1533. BIO_free(biobuf);
  1534. return retval;
  1535. fail1:
  1536. if (biobuf != NULL)
  1537. BIO_free(biobuf);
  1538. fail0:
  1539. Py_XDECREF(retval);
  1540. return NULL;
  1541. }
  1542. static PyObject *
  1543. _certificate_to_der(_sslmodulestate *state, X509 *certificate)
  1544. {
  1545. unsigned char *bytes_buf = NULL;
  1546. int len;
  1547. PyObject *retval;
  1548. bytes_buf = NULL;
  1549. len = i2d_X509(certificate, &bytes_buf);
  1550. if (len < 0) {
  1551. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  1552. return NULL;
  1553. }
  1554. /* this is actually an immutable bytes sequence */
  1555. retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
  1556. OPENSSL_free(bytes_buf);
  1557. return retval;
  1558. }
  1559. #include "_ssl/misc.c"
  1560. #include "_ssl/cert.c"
  1561. /*[clinic input]
  1562. _ssl._test_decode_cert
  1563. path: object(converter="PyUnicode_FSConverter")
  1564. /
  1565. [clinic start generated code]*/
  1566. static PyObject *
  1567. _ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
  1568. /*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
  1569. {
  1570. PyObject *retval = NULL;
  1571. X509 *x=NULL;
  1572. BIO *cert;
  1573. _sslmodulestate *state = get_ssl_state(module);
  1574. if ((cert=BIO_new(BIO_s_file())) == NULL) {
  1575. PyErr_SetString(state->PySSLErrorObject,
  1576. "Can't malloc memory to read file");
  1577. goto fail0;
  1578. }
  1579. if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
  1580. PyErr_SetString(state->PySSLErrorObject,
  1581. "Can't open file");
  1582. goto fail0;
  1583. }
  1584. x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
  1585. if (x == NULL) {
  1586. PyErr_SetString(state->PySSLErrorObject,
  1587. "Error decoding PEM-encoded file");
  1588. goto fail0;
  1589. }
  1590. retval = _decode_certificate(state, x);
  1591. X509_free(x);
  1592. fail0:
  1593. Py_DECREF(path);
  1594. if (cert != NULL) BIO_free(cert);
  1595. return retval;
  1596. }
  1597. /*[clinic input]
  1598. _ssl._SSLSocket.getpeercert
  1599. der as binary_mode: bool = False
  1600. /
  1601. Returns the certificate for the peer.
  1602. If no certificate was provided, returns None. If a certificate was
  1603. provided, but not validated, returns an empty dictionary. Otherwise
  1604. returns a dict containing information about the peer certificate.
  1605. If the optional argument is True, returns a DER-encoded copy of the
  1606. peer certificate, or None if no certificate was provided. This will
  1607. return the certificate even if it wasn't validated.
  1608. [clinic start generated code]*/
  1609. static PyObject *
  1610. _ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
  1611. /*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
  1612. {
  1613. int verification;
  1614. X509 *peer_cert;
  1615. PyObject *result;
  1616. if (!SSL_is_init_finished(self->ssl)) {
  1617. PyErr_SetString(PyExc_ValueError,
  1618. "handshake not done yet");
  1619. return NULL;
  1620. }
  1621. peer_cert = SSL_get_peer_certificate(self->ssl);
  1622. if (peer_cert == NULL)
  1623. Py_RETURN_NONE;
  1624. if (binary_mode) {
  1625. /* return cert in DER-encoded format */
  1626. result = _certificate_to_der(get_state_sock(self), peer_cert);
  1627. } else {
  1628. verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
  1629. if ((verification & SSL_VERIFY_PEER) == 0)
  1630. result = PyDict_New();
  1631. else
  1632. result = _decode_certificate(get_state_sock(self), peer_cert);
  1633. }
  1634. X509_free(peer_cert);
  1635. return result;
  1636. }
  1637. /*[clinic input]
  1638. _ssl._SSLSocket.get_verified_chain
  1639. [clinic start generated code]*/
  1640. static PyObject *
  1641. _ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
  1642. /*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
  1643. {
  1644. /* borrowed reference */
  1645. STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
  1646. if (chain == NULL) {
  1647. Py_RETURN_NONE;
  1648. }
  1649. return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
  1650. }
  1651. /*[clinic input]
  1652. _ssl._SSLSocket.get_unverified_chain
  1653. [clinic start generated code]*/
  1654. static PyObject *
  1655. _ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
  1656. /*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
  1657. {
  1658. PyObject *retval;
  1659. /* borrowed reference */
  1660. /* TODO: include SSL_get_peer_certificate() for server-side sockets */
  1661. STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
  1662. if (chain == NULL) {
  1663. Py_RETURN_NONE;
  1664. }
  1665. retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
  1666. if (retval == NULL) {
  1667. return NULL;
  1668. }
  1669. /* OpenSSL does not include peer cert for server side connections */
  1670. if (self->socket_type == PY_SSL_SERVER) {
  1671. PyObject *peerobj = NULL;
  1672. X509 *peer = SSL_get_peer_certificate(self->ssl);
  1673. if (peer == NULL) {
  1674. peerobj = Py_NewRef(Py_None);
  1675. } else {
  1676. /* consume X509 reference on success */
  1677. peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
  1678. if (peerobj == NULL) {
  1679. X509_free(peer);
  1680. Py_DECREF(retval);
  1681. return NULL;
  1682. }
  1683. }
  1684. int res = PyList_Insert(retval, 0, peerobj);
  1685. Py_DECREF(peerobj);
  1686. if (res < 0) {
  1687. Py_DECREF(retval);
  1688. return NULL;
  1689. }
  1690. }
  1691. return retval;
  1692. }
  1693. static PyObject *
  1694. cipher_to_tuple(const SSL_CIPHER *cipher)
  1695. {
  1696. const char *cipher_name, *cipher_protocol;
  1697. PyObject *v, *retval = PyTuple_New(3);
  1698. if (retval == NULL)
  1699. return NULL;
  1700. cipher_name = SSL_CIPHER_get_name(cipher);
  1701. if (cipher_name == NULL) {
  1702. PyTuple_SET_ITEM(retval, 0, Py_NewRef(Py_None));
  1703. } else {
  1704. v = PyUnicode_FromString(cipher_name);
  1705. if (v == NULL)
  1706. goto fail;
  1707. PyTuple_SET_ITEM(retval, 0, v);
  1708. }
  1709. cipher_protocol = SSL_CIPHER_get_version(cipher);
  1710. if (cipher_protocol == NULL) {
  1711. PyTuple_SET_ITEM(retval, 1, Py_NewRef(Py_None));
  1712. } else {
  1713. v = PyUnicode_FromString(cipher_protocol);
  1714. if (v == NULL)
  1715. goto fail;
  1716. PyTuple_SET_ITEM(retval, 1, v);
  1717. }
  1718. v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
  1719. if (v == NULL)
  1720. goto fail;
  1721. PyTuple_SET_ITEM(retval, 2, v);
  1722. return retval;
  1723. fail:
  1724. Py_DECREF(retval);
  1725. return NULL;
  1726. }
  1727. static PyObject *
  1728. cipher_to_dict(const SSL_CIPHER *cipher)
  1729. {
  1730. const char *cipher_name, *cipher_protocol;
  1731. unsigned long cipher_id;
  1732. int alg_bits, strength_bits, len;
  1733. char buf[512] = {0};
  1734. int aead, nid;
  1735. const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
  1736. /* can be NULL */
  1737. cipher_name = SSL_CIPHER_get_name(cipher);
  1738. cipher_protocol = SSL_CIPHER_get_version(cipher);
  1739. cipher_id = SSL_CIPHER_get_id(cipher);
  1740. SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
  1741. /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
  1742. len = (int)strlen(buf);
  1743. if (len > 1 && buf[len-1] == '\n')
  1744. buf[len-1] = '\0';
  1745. strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
  1746. aead = SSL_CIPHER_is_aead(cipher);
  1747. nid = SSL_CIPHER_get_cipher_nid(cipher);
  1748. skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
  1749. nid = SSL_CIPHER_get_digest_nid(cipher);
  1750. digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
  1751. nid = SSL_CIPHER_get_kx_nid(cipher);
  1752. kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
  1753. nid = SSL_CIPHER_get_auth_nid(cipher);
  1754. auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
  1755. return Py_BuildValue(
  1756. "{sksssssssisi"
  1757. "sOssssssss"
  1758. "}",
  1759. "id", cipher_id,
  1760. "name", cipher_name,
  1761. "protocol", cipher_protocol,
  1762. "description", buf,
  1763. "strength_bits", strength_bits,
  1764. "alg_bits", alg_bits
  1765. ,"aead", aead ? Py_True : Py_False,
  1766. "symmetric", skcipher,
  1767. "digest", digest,
  1768. "kea", kx,
  1769. "auth", auth
  1770. );
  1771. }
  1772. /*[clinic input]
  1773. _ssl._SSLSocket.shared_ciphers
  1774. [clinic start generated code]*/
  1775. static PyObject *
  1776. _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
  1777. /*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
  1778. {
  1779. STACK_OF(SSL_CIPHER) *server_ciphers;
  1780. STACK_OF(SSL_CIPHER) *client_ciphers;
  1781. int i, len;
  1782. PyObject *res;
  1783. const SSL_CIPHER* cipher;
  1784. /* Rather than use SSL_get_shared_ciphers, we use an equivalent algorithm because:
  1785. 1) It returns a colon separated list of strings, in an undefined
  1786. order, that we would have to post process back into tuples.
  1787. 2) It will return a truncated string with no indication that it has
  1788. done so, if the buffer is too small.
  1789. */
  1790. server_ciphers = SSL_get_ciphers(self->ssl);
  1791. if (!server_ciphers)
  1792. Py_RETURN_NONE;
  1793. client_ciphers = SSL_get_client_ciphers(self->ssl);
  1794. if (!client_ciphers)
  1795. Py_RETURN_NONE;
  1796. res = PyList_New(sk_SSL_CIPHER_num(server_ciphers));
  1797. if (!res)
  1798. return NULL;
  1799. len = 0;
  1800. for (i = 0; i < sk_SSL_CIPHER_num(server_ciphers); i++) {
  1801. cipher = sk_SSL_CIPHER_value(server_ciphers, i);
  1802. if (sk_SSL_CIPHER_find(client_ciphers, cipher) < 0)
  1803. continue;
  1804. PyObject *tup = cipher_to_tuple(cipher);
  1805. if (!tup) {
  1806. Py_DECREF(res);
  1807. return NULL;
  1808. }
  1809. PyList_SET_ITEM(res, len++, tup);
  1810. }
  1811. Py_SET_SIZE(res, len);
  1812. return res;
  1813. }
  1814. /*[clinic input]
  1815. _ssl._SSLSocket.cipher
  1816. [clinic start generated code]*/
  1817. static PyObject *
  1818. _ssl__SSLSocket_cipher_impl(PySSLSocket *self)
  1819. /*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
  1820. {
  1821. const SSL_CIPHER *current;
  1822. if (self->ssl == NULL)
  1823. Py_RETURN_NONE;
  1824. current = SSL_get_current_cipher(self->ssl);
  1825. if (current == NULL)
  1826. Py_RETURN_NONE;
  1827. return cipher_to_tuple(current);
  1828. }
  1829. /*[clinic input]
  1830. _ssl._SSLSocket.version
  1831. [clinic start generated code]*/
  1832. static PyObject *
  1833. _ssl__SSLSocket_version_impl(PySSLSocket *self)
  1834. /*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
  1835. {
  1836. const char *version;
  1837. if (self->ssl == NULL)
  1838. Py_RETURN_NONE;
  1839. if (!SSL_is_init_finished(self->ssl)) {
  1840. /* handshake not finished */
  1841. Py_RETURN_NONE;
  1842. }
  1843. version = SSL_get_version(self->ssl);
  1844. if (!strcmp(version, "unknown"))
  1845. Py_RETURN_NONE;
  1846. return PyUnicode_FromString(version);
  1847. }
  1848. /*[clinic input]
  1849. _ssl._SSLSocket.selected_alpn_protocol
  1850. [clinic start generated code]*/
  1851. static PyObject *
  1852. _ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
  1853. /*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
  1854. {
  1855. const unsigned char *out;
  1856. unsigned int outlen;
  1857. SSL_get0_alpn_selected(self->ssl, &out, &outlen);
  1858. if (out == NULL)
  1859. Py_RETURN_NONE;
  1860. return PyUnicode_FromStringAndSize((char *)out, outlen);
  1861. }
  1862. /*[clinic input]
  1863. _ssl._SSLSocket.compression
  1864. [clinic start generated code]*/
  1865. static PyObject *
  1866. _ssl__SSLSocket_compression_impl(PySSLSocket *self)
  1867. /*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
  1868. {
  1869. #ifdef OPENSSL_NO_COMP
  1870. Py_RETURN_NONE;
  1871. #else
  1872. const COMP_METHOD *comp_method;
  1873. const char *short_name;
  1874. if (self->ssl == NULL)
  1875. Py_RETURN_NONE;
  1876. comp_method = SSL_get_current_compression(self->ssl);
  1877. if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
  1878. Py_RETURN_NONE;
  1879. short_name = OBJ_nid2sn(COMP_get_type(comp_method));
  1880. if (short_name == NULL)
  1881. Py_RETURN_NONE;
  1882. return PyUnicode_DecodeFSDefault(short_name);
  1883. #endif
  1884. }
  1885. static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
  1886. return (PySSLContext*)Py_NewRef(self->ctx);
  1887. }
  1888. static int PySSL_set_context(PySSLSocket *self, PyObject *value,
  1889. void *closure) {
  1890. if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
  1891. Py_SETREF(self->ctx, (PySSLContext *)Py_NewRef(value));
  1892. SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
  1893. /* Set SSL* internal msg_callback to state of new context's state */
  1894. SSL_set_msg_callback(
  1895. self->ssl,
  1896. self->ctx->msg_cb ? _PySSL_msg_callback : NULL
  1897. );
  1898. } else {
  1899. PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
  1900. return -1;
  1901. }
  1902. return 0;
  1903. }
  1904. PyDoc_STRVAR(PySSL_set_context_doc,
  1905. "_setter_context(ctx)\n\
  1906. \
  1907. This changes the context associated with the SSLSocket. This is typically\n\
  1908. used from within a callback function set by the sni_callback\n\
  1909. on the SSLContext to change the certificate information associated with the\n\
  1910. SSLSocket before the cryptographic exchange handshake messages\n");
  1911. static PyObject *
  1912. PySSL_get_server_side(PySSLSocket *self, void *c)
  1913. {
  1914. return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
  1915. }
  1916. PyDoc_STRVAR(PySSL_get_server_side_doc,
  1917. "Whether this is a server-side socket.");
  1918. static PyObject *
  1919. PySSL_get_server_hostname(PySSLSocket *self, void *c)
  1920. {
  1921. if (self->server_hostname == NULL)
  1922. Py_RETURN_NONE;
  1923. return Py_NewRef(self->server_hostname);
  1924. }
  1925. PyDoc_STRVAR(PySSL_get_server_hostname_doc,
  1926. "The currently set server hostname (for SNI).");
  1927. static PyObject *
  1928. PySSL_get_owner(PySSLSocket *self, void *c)
  1929. {
  1930. PyObject *owner;
  1931. if (self->owner == NULL)
  1932. Py_RETURN_NONE;
  1933. owner = PyWeakref_GetObject(self->owner);
  1934. return Py_NewRef(owner);
  1935. }
  1936. static int
  1937. PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
  1938. {
  1939. Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
  1940. if (self->owner == NULL)
  1941. return -1;
  1942. return 0;
  1943. }
  1944. PyDoc_STRVAR(PySSL_get_owner_doc,
  1945. "The Python-level owner of this object.\
  1946. Passed as \"self\" in servername callback.");
  1947. static int
  1948. PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
  1949. {
  1950. Py_VISIT(self->exc);
  1951. Py_VISIT(Py_TYPE(self));
  1952. return 0;
  1953. }
  1954. static int
  1955. PySSL_clear(PySSLSocket *self)
  1956. {
  1957. Py_CLEAR(self->exc);
  1958. return 0;
  1959. }
  1960. static void
  1961. PySSL_dealloc(PySSLSocket *self)
  1962. {
  1963. PyTypeObject *tp = Py_TYPE(self);
  1964. PyObject_GC_UnTrack(self);
  1965. if (self->ssl) {
  1966. // If we free the SSL socket object without having called SSL_shutdown,
  1967. // OpenSSL will invalidate the linked SSL session object. While this
  1968. // behavior is strictly RFC-compliant, it makes session reuse less
  1969. // likely and it would also break compatibility with older stdlib
  1970. // versions (which used an ugly workaround of duplicating the
  1971. // SSL_SESSION object).
  1972. // Therefore, we ensure the socket is marked as shutdown in any case.
  1973. //
  1974. // See elaborate explanation at
  1975. // https://github.com/python/cpython/pull/123249#discussion_r1766164530
  1976. SSL_set_shutdown(self->ssl, SSL_SENT_SHUTDOWN | SSL_get_shutdown(self->ssl));
  1977. SSL_free(self->ssl);
  1978. }
  1979. Py_XDECREF(self->Socket);
  1980. Py_XDECREF(self->ctx);
  1981. Py_XDECREF(self->server_hostname);
  1982. Py_XDECREF(self->owner);
  1983. PyObject_GC_Del(self);
  1984. Py_DECREF(tp);
  1985. }
  1986. /* If the socket has a timeout, do a select()/poll() on the socket.
  1987. The argument writing indicates the direction.
  1988. Returns one of the possibilities in the timeout_state enum (above).
  1989. */
  1990. static int
  1991. PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
  1992. {
  1993. int rc;
  1994. #ifdef HAVE_POLL
  1995. struct pollfd pollfd;
  1996. _PyTime_t ms;
  1997. #else
  1998. int nfds;
  1999. fd_set fds;
  2000. struct timeval tv;
  2001. #endif
  2002. /* Nothing to do unless we're in timeout mode (not non-blocking) */
  2003. if ((s == NULL) || (timeout == 0))
  2004. return SOCKET_IS_NONBLOCKING;
  2005. else if (timeout < 0) {
  2006. if (s->sock_timeout > 0)
  2007. return SOCKET_HAS_TIMED_OUT;
  2008. else
  2009. return SOCKET_IS_BLOCKING;
  2010. }
  2011. /* Guard against closed socket */
  2012. if (s->sock_fd == INVALID_SOCKET)
  2013. return SOCKET_HAS_BEEN_CLOSED;
  2014. /* Prefer poll, if available, since you can poll() any fd
  2015. * which can't be done with select(). */
  2016. #ifdef HAVE_POLL
  2017. pollfd.fd = s->sock_fd;
  2018. pollfd.events = writing ? POLLOUT : POLLIN;
  2019. /* timeout is in seconds, poll() uses milliseconds */
  2020. ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
  2021. assert(ms <= INT_MAX);
  2022. PySSL_BEGIN_ALLOW_THREADS
  2023. rc = poll(&pollfd, 1, (int)ms);
  2024. PySSL_END_ALLOW_THREADS
  2025. #else
  2026. /* Guard against socket too large for select*/
  2027. if (!_PyIsSelectable_fd(s->sock_fd))
  2028. return SOCKET_TOO_LARGE_FOR_SELECT;
  2029. _PyTime_AsTimeval_clamp(timeout, &tv, _PyTime_ROUND_CEILING);
  2030. FD_ZERO(&fds);
  2031. FD_SET(s->sock_fd, &fds);
  2032. /* Wait until the socket becomes ready */
  2033. PySSL_BEGIN_ALLOW_THREADS
  2034. nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
  2035. if (writing)
  2036. rc = select(nfds, NULL, &fds, NULL, &tv);
  2037. else
  2038. rc = select(nfds, &fds, NULL, NULL, &tv);
  2039. PySSL_END_ALLOW_THREADS
  2040. #endif
  2041. /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
  2042. (when we are able to write or when there's something to read) */
  2043. return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
  2044. }
  2045. /*[clinic input]
  2046. _ssl._SSLSocket.write
  2047. b: Py_buffer
  2048. /
  2049. Writes the bytes-like object b into the SSL object.
  2050. Returns the number of bytes written.
  2051. [clinic start generated code]*/
  2052. static PyObject *
  2053. _ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
  2054. /*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
  2055. {
  2056. size_t count = 0;
  2057. int retval;
  2058. int sockstate;
  2059. _PySSLError err;
  2060. int nonblocking;
  2061. PySocketSockObject *sock = GET_SOCKET(self);
  2062. _PyTime_t timeout, deadline = 0;
  2063. int has_timeout;
  2064. if (sock != NULL) {
  2065. if (((PyObject*)sock) == Py_None) {
  2066. _setSSLError(get_state_sock(self),
  2067. "Underlying socket connection gone",
  2068. PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
  2069. return NULL;
  2070. }
  2071. Py_INCREF(sock);
  2072. }
  2073. if (sock != NULL) {
  2074. /* just in case the blocking state of the socket has been changed */
  2075. nonblocking = (sock->sock_timeout >= 0);
  2076. BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
  2077. BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
  2078. }
  2079. timeout = GET_SOCKET_TIMEOUT(sock);
  2080. has_timeout = (timeout > 0);
  2081. if (has_timeout) {
  2082. deadline = _PyDeadline_Init(timeout);
  2083. }
  2084. sockstate = PySSL_select(sock, 1, timeout);
  2085. if (sockstate == SOCKET_HAS_TIMED_OUT) {
  2086. PyErr_SetString(PyExc_TimeoutError,
  2087. "The write operation timed out");
  2088. goto error;
  2089. } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
  2090. PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
  2091. "Underlying socket has been closed.");
  2092. goto error;
  2093. } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
  2094. PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
  2095. "Underlying socket too large for select().");
  2096. goto error;
  2097. }
  2098. do {
  2099. PySSL_BEGIN_ALLOW_THREADS
  2100. retval = SSL_write_ex(self->ssl, b->buf, (size_t)b->len, &count);
  2101. err = _PySSL_errno(retval == 0, self->ssl, retval);
  2102. PySSL_END_ALLOW_THREADS
  2103. self->err = err;
  2104. if (PyErr_CheckSignals())
  2105. goto error;
  2106. if (has_timeout) {
  2107. timeout = _PyDeadline_Get(deadline);
  2108. }
  2109. if (err.ssl == SSL_ERROR_WANT_READ) {
  2110. sockstate = PySSL_select(sock, 0, timeout);
  2111. } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
  2112. sockstate = PySSL_select(sock, 1, timeout);
  2113. } else {
  2114. sockstate = SOCKET_OPERATION_OK;
  2115. }
  2116. if (sockstate == SOCKET_HAS_TIMED_OUT) {
  2117. PyErr_SetString(PyExc_TimeoutError,
  2118. "The write operation timed out");
  2119. goto error;
  2120. } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
  2121. PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
  2122. "Underlying socket has been closed.");
  2123. goto error;
  2124. } else if (sockstate == SOCKET_IS_NONBLOCKING) {
  2125. break;
  2126. }
  2127. } while (err.ssl == SSL_ERROR_WANT_READ ||
  2128. err.ssl == SSL_ERROR_WANT_WRITE);
  2129. Py_XDECREF(sock);
  2130. if (retval == 0)
  2131. return PySSL_SetError(self, retval, __FILE__, __LINE__);
  2132. if (PySSL_ChainExceptions(self) < 0)
  2133. return NULL;
  2134. return PyLong_FromSize_t(count);
  2135. error:
  2136. Py_XDECREF(sock);
  2137. PySSL_ChainExceptions(self);
  2138. return NULL;
  2139. }
  2140. /*[clinic input]
  2141. _ssl._SSLSocket.pending
  2142. Returns the number of already decrypted bytes available for read, pending on the connection.
  2143. [clinic start generated code]*/
  2144. static PyObject *
  2145. _ssl__SSLSocket_pending_impl(PySSLSocket *self)
  2146. /*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
  2147. {
  2148. int count = 0;
  2149. _PySSLError err;
  2150. PySSL_BEGIN_ALLOW_THREADS
  2151. count = SSL_pending(self->ssl);
  2152. err = _PySSL_errno(count < 0, self->ssl, count);
  2153. PySSL_END_ALLOW_THREADS
  2154. self->err = err;
  2155. if (count < 0)
  2156. return PySSL_SetError(self, count, __FILE__, __LINE__);
  2157. else
  2158. return PyLong_FromLong(count);
  2159. }
  2160. /*[clinic input]
  2161. _ssl._SSLSocket.read
  2162. size as len: Py_ssize_t
  2163. [
  2164. buffer: Py_buffer(accept={rwbuffer})
  2165. ]
  2166. /
  2167. Read up to size bytes from the SSL socket.
  2168. [clinic start generated code]*/
  2169. static PyObject *
  2170. _ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
  2171. int group_right_1, Py_buffer *buffer)
  2172. /*[clinic end generated code: output=49b16e6406023734 input=ec48bf622be1c4a1]*/
  2173. {
  2174. PyObject *dest = NULL;
  2175. char *mem;
  2176. size_t count = 0;
  2177. int retval;
  2178. int sockstate;
  2179. _PySSLError err;
  2180. int nonblocking;
  2181. PySocketSockObject *sock = GET_SOCKET(self);
  2182. _PyTime_t timeout, deadline = 0;
  2183. int has_timeout;
  2184. if (!group_right_1 && len < 0) {
  2185. PyErr_SetString(PyExc_ValueError, "size should not be negative");
  2186. return NULL;
  2187. }
  2188. if (sock != NULL) {
  2189. if (((PyObject*)sock) == Py_None) {
  2190. _setSSLError(get_state_sock(self),
  2191. "Underlying socket connection gone",
  2192. PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
  2193. return NULL;
  2194. }
  2195. Py_INCREF(sock);
  2196. }
  2197. if (!group_right_1) {
  2198. dest = PyBytes_FromStringAndSize(NULL, len);
  2199. if (dest == NULL)
  2200. goto error;
  2201. if (len == 0) {
  2202. Py_XDECREF(sock);
  2203. return dest;
  2204. }
  2205. mem = PyBytes_AS_STRING(dest);
  2206. }
  2207. else {
  2208. mem = buffer->buf;
  2209. if (len <= 0 || len > buffer->len) {
  2210. len = (int) buffer->len;
  2211. if (buffer->len != len) {
  2212. PyErr_SetString(PyExc_OverflowError,
  2213. "maximum length can't fit in a C 'int'");
  2214. goto error;
  2215. }
  2216. if (len == 0) {
  2217. count = 0;
  2218. goto done;
  2219. }
  2220. }
  2221. }
  2222. if (sock != NULL) {
  2223. /* just in case the blocking state of the socket has been changed */
  2224. nonblocking = (sock->sock_timeout >= 0);
  2225. BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
  2226. BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
  2227. }
  2228. timeout = GET_SOCKET_TIMEOUT(sock);
  2229. has_timeout = (timeout > 0);
  2230. if (has_timeout)
  2231. deadline = _PyDeadline_Init(timeout);
  2232. do {
  2233. PySSL_BEGIN_ALLOW_THREADS
  2234. retval = SSL_read_ex(self->ssl, mem, (size_t)len, &count);
  2235. err = _PySSL_errno(retval == 0, self->ssl, retval);
  2236. PySSL_END_ALLOW_THREADS
  2237. self->err = err;
  2238. if (PyErr_CheckSignals())
  2239. goto error;
  2240. if (has_timeout) {
  2241. timeout = _PyDeadline_Get(deadline);
  2242. }
  2243. if (err.ssl == SSL_ERROR_WANT_READ) {
  2244. sockstate = PySSL_select(sock, 0, timeout);
  2245. } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
  2246. sockstate = PySSL_select(sock, 1, timeout);
  2247. } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
  2248. SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
  2249. {
  2250. count = 0;
  2251. goto done;
  2252. }
  2253. else
  2254. sockstate = SOCKET_OPERATION_OK;
  2255. if (sockstate == SOCKET_HAS_TIMED_OUT) {
  2256. PyErr_SetString(PyExc_TimeoutError,
  2257. "The read operation timed out");
  2258. goto error;
  2259. } else if (sockstate == SOCKET_IS_NONBLOCKING) {
  2260. break;
  2261. }
  2262. } while (err.ssl == SSL_ERROR_WANT_READ ||
  2263. err.ssl == SSL_ERROR_WANT_WRITE);
  2264. if (retval == 0) {
  2265. PySSL_SetError(self, retval, __FILE__, __LINE__);
  2266. goto error;
  2267. }
  2268. if (self->exc != NULL)
  2269. goto error;
  2270. done:
  2271. Py_XDECREF(sock);
  2272. if (!group_right_1) {
  2273. _PyBytes_Resize(&dest, count);
  2274. return dest;
  2275. }
  2276. else {
  2277. return PyLong_FromSize_t(count);
  2278. }
  2279. error:
  2280. PySSL_ChainExceptions(self);
  2281. Py_XDECREF(sock);
  2282. if (!group_right_1)
  2283. Py_XDECREF(dest);
  2284. return NULL;
  2285. }
  2286. /*[clinic input]
  2287. _ssl._SSLSocket.shutdown
  2288. Does the SSL shutdown handshake with the remote end.
  2289. [clinic start generated code]*/
  2290. static PyObject *
  2291. _ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
  2292. /*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
  2293. {
  2294. _PySSLError err;
  2295. int sockstate, nonblocking, ret;
  2296. int zeros = 0;
  2297. PySocketSockObject *sock = GET_SOCKET(self);
  2298. _PyTime_t timeout, deadline = 0;
  2299. int has_timeout;
  2300. if (sock != NULL) {
  2301. /* Guard against closed socket */
  2302. if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
  2303. _setSSLError(get_state_sock(self),
  2304. "Underlying socket connection gone",
  2305. PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
  2306. return NULL;
  2307. }
  2308. Py_INCREF(sock);
  2309. /* Just in case the blocking state of the socket has been changed */
  2310. nonblocking = (sock->sock_timeout >= 0);
  2311. BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
  2312. BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
  2313. }
  2314. timeout = GET_SOCKET_TIMEOUT(sock);
  2315. has_timeout = (timeout > 0);
  2316. if (has_timeout) {
  2317. deadline = _PyDeadline_Init(timeout);
  2318. }
  2319. while (1) {
  2320. PySSL_BEGIN_ALLOW_THREADS
  2321. /* Disable read-ahead so that unwrap can work correctly.
  2322. * Otherwise OpenSSL might read in too much data,
  2323. * eating clear text data that happens to be
  2324. * transmitted after the SSL shutdown.
  2325. * Should be safe to call repeatedly every time this
  2326. * function is used and the shutdown_seen_zero != 0
  2327. * condition is met.
  2328. */
  2329. if (self->shutdown_seen_zero)
  2330. SSL_set_read_ahead(self->ssl, 0);
  2331. ret = SSL_shutdown(self->ssl);
  2332. err = _PySSL_errno(ret < 0, self->ssl, ret);
  2333. PySSL_END_ALLOW_THREADS
  2334. self->err = err;
  2335. /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
  2336. if (ret > 0)
  2337. break;
  2338. if (ret == 0) {
  2339. /* Don't loop endlessly; instead preserve legacy
  2340. behaviour of trying SSL_shutdown() only twice.
  2341. This looks necessary for OpenSSL < 0.9.8m */
  2342. if (++zeros > 1)
  2343. break;
  2344. /* Shutdown was sent, now try receiving */
  2345. self->shutdown_seen_zero = 1;
  2346. continue;
  2347. }
  2348. if (has_timeout) {
  2349. timeout = _PyDeadline_Get(deadline);
  2350. }
  2351. /* Possibly retry shutdown until timeout or failure */
  2352. if (err.ssl == SSL_ERROR_WANT_READ)
  2353. sockstate = PySSL_select(sock, 0, timeout);
  2354. else if (err.ssl == SSL_ERROR_WANT_WRITE)
  2355. sockstate = PySSL_select(sock, 1, timeout);
  2356. else
  2357. break;
  2358. if (sockstate == SOCKET_HAS_TIMED_OUT) {
  2359. if (err.ssl == SSL_ERROR_WANT_READ)
  2360. PyErr_SetString(PyExc_TimeoutError,
  2361. "The read operation timed out");
  2362. else
  2363. PyErr_SetString(PyExc_TimeoutError,
  2364. "The write operation timed out");
  2365. goto error;
  2366. }
  2367. else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
  2368. PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
  2369. "Underlying socket too large for select().");
  2370. goto error;
  2371. }
  2372. else if (sockstate != SOCKET_OPERATION_OK)
  2373. /* Retain the SSL error code */
  2374. break;
  2375. }
  2376. if (ret < 0) {
  2377. Py_XDECREF(sock);
  2378. PySSL_SetError(self, ret, __FILE__, __LINE__);
  2379. return NULL;
  2380. }
  2381. if (self->exc != NULL)
  2382. goto error;
  2383. if (sock)
  2384. /* It's already INCREF'ed */
  2385. return (PyObject *) sock;
  2386. else
  2387. Py_RETURN_NONE;
  2388. error:
  2389. Py_XDECREF(sock);
  2390. PySSL_ChainExceptions(self);
  2391. return NULL;
  2392. }
  2393. /*[clinic input]
  2394. _ssl._SSLSocket.get_channel_binding
  2395. cb_type: str = "tls-unique"
  2396. Get channel binding data for current connection.
  2397. Raise ValueError if the requested `cb_type` is not supported. Return bytes
  2398. of the data or None if the data is not available (e.g. before the handshake).
  2399. Only 'tls-unique' channel binding data from RFC 5929 is supported.
  2400. [clinic start generated code]*/
  2401. static PyObject *
  2402. _ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
  2403. const char *cb_type)
  2404. /*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
  2405. {
  2406. char buf[PySSL_CB_MAXLEN];
  2407. size_t len;
  2408. if (strcmp(cb_type, "tls-unique") == 0) {
  2409. if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
  2410. /* if session is resumed XOR we are the client */
  2411. len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
  2412. }
  2413. else {
  2414. /* if a new session XOR we are the server */
  2415. len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
  2416. }
  2417. }
  2418. else {
  2419. PyErr_Format(
  2420. PyExc_ValueError,
  2421. "'%s' channel binding type not implemented",
  2422. cb_type
  2423. );
  2424. return NULL;
  2425. }
  2426. /* It cannot be negative in current OpenSSL version as of July 2011 */
  2427. if (len == 0)
  2428. Py_RETURN_NONE;
  2429. return PyBytes_FromStringAndSize(buf, len);
  2430. }
  2431. /*[clinic input]
  2432. _ssl._SSLSocket.verify_client_post_handshake
  2433. Initiate TLS 1.3 post-handshake authentication
  2434. [clinic start generated code]*/
  2435. static PyObject *
  2436. _ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
  2437. /*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
  2438. {
  2439. #ifdef TLS1_3_VERSION
  2440. int err = SSL_verify_client_post_handshake(self->ssl);
  2441. if (err == 0)
  2442. return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
  2443. else
  2444. Py_RETURN_NONE;
  2445. #else
  2446. PyErr_SetString(PyExc_NotImplementedError,
  2447. "Post-handshake auth is not supported by your "
  2448. "OpenSSL version.");
  2449. return NULL;
  2450. #endif
  2451. }
  2452. static PyObject *
  2453. PySSL_get_session(PySSLSocket *self, void *closure) {
  2454. /* get_session can return sessions from a server-side connection,
  2455. * it does not check for handshake done or client socket. */
  2456. PySSLSession *pysess;
  2457. SSL_SESSION *session;
  2458. session = SSL_get1_session(self->ssl);
  2459. if (session == NULL) {
  2460. Py_RETURN_NONE;
  2461. }
  2462. pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
  2463. if (pysess == NULL) {
  2464. SSL_SESSION_free(session);
  2465. return NULL;
  2466. }
  2467. assert(self->ctx);
  2468. pysess->ctx = (PySSLContext*)Py_NewRef(self->ctx);
  2469. pysess->session = session;
  2470. PyObject_GC_Track(pysess);
  2471. return (PyObject *)pysess;
  2472. }
  2473. static int PySSL_set_session(PySSLSocket *self, PyObject *value,
  2474. void *closure) {
  2475. PySSLSession *pysess;
  2476. if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
  2477. PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
  2478. return -1;
  2479. }
  2480. pysess = (PySSLSession *)value;
  2481. if (self->ctx->ctx != pysess->ctx->ctx) {
  2482. PyErr_SetString(PyExc_ValueError,
  2483. "Session refers to a different SSLContext.");
  2484. return -1;
  2485. }
  2486. if (self->socket_type != PY_SSL_CLIENT) {
  2487. PyErr_SetString(PyExc_ValueError,
  2488. "Cannot set session for server-side SSLSocket.");
  2489. return -1;
  2490. }
  2491. if (SSL_is_init_finished(self->ssl)) {
  2492. PyErr_SetString(PyExc_ValueError,
  2493. "Cannot set session after handshake.");
  2494. return -1;
  2495. }
  2496. if (SSL_set_session(self->ssl, pysess->session) == 0) {
  2497. _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
  2498. return -1;
  2499. }
  2500. return 0;
  2501. }
  2502. PyDoc_STRVAR(PySSL_set_session_doc,
  2503. "_setter_session(session)\n\
  2504. \
  2505. Get / set SSLSession.");
  2506. static PyObject *
  2507. PySSL_get_session_reused(PySSLSocket *self, void *closure) {
  2508. if (SSL_session_reused(self->ssl)) {
  2509. Py_RETURN_TRUE;
  2510. } else {
  2511. Py_RETURN_FALSE;
  2512. }
  2513. }
  2514. PyDoc_STRVAR(PySSL_get_session_reused_doc,
  2515. "Was the client session reused during handshake?");
  2516. static PyGetSetDef ssl_getsetlist[] = {
  2517. {"context", (getter) PySSL_get_context,
  2518. (setter) PySSL_set_context, PySSL_set_context_doc},
  2519. {"server_side", (getter) PySSL_get_server_side, NULL,
  2520. PySSL_get_server_side_doc},
  2521. {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
  2522. PySSL_get_server_hostname_doc},
  2523. {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
  2524. PySSL_get_owner_doc},
  2525. {"session", (getter) PySSL_get_session,
  2526. (setter) PySSL_set_session, PySSL_set_session_doc},
  2527. {"session_reused", (getter) PySSL_get_session_reused, NULL,
  2528. PySSL_get_session_reused_doc},
  2529. {NULL}, /* sentinel */
  2530. };
  2531. static PyMethodDef PySSLMethods[] = {
  2532. _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
  2533. _SSL__SSLSOCKET_WRITE_METHODDEF
  2534. _SSL__SSLSOCKET_READ_METHODDEF
  2535. _SSL__SSLSOCKET_PENDING_METHODDEF
  2536. _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
  2537. _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
  2538. _SSL__SSLSOCKET_CIPHER_METHODDEF
  2539. _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
  2540. _SSL__SSLSOCKET_VERSION_METHODDEF
  2541. _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
  2542. _SSL__SSLSOCKET_COMPRESSION_METHODDEF
  2543. _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
  2544. _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
  2545. _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
  2546. _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
  2547. {NULL, NULL}
  2548. };
  2549. static PyType_Slot PySSLSocket_slots[] = {
  2550. {Py_tp_methods, PySSLMethods},
  2551. {Py_tp_getset, ssl_getsetlist},
  2552. {Py_tp_dealloc, PySSL_dealloc},
  2553. {Py_tp_traverse, PySSL_traverse},
  2554. {Py_tp_clear, PySSL_clear},
  2555. {0, 0},
  2556. };
  2557. static PyType_Spec PySSLSocket_spec = {
  2558. .name = "_ssl._SSLSocket",
  2559. .basicsize = sizeof(PySSLSocket),
  2560. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
  2561. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  2562. .slots = PySSLSocket_slots,
  2563. };
  2564. /*
  2565. * _SSLContext objects
  2566. */
  2567. static int
  2568. _set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
  2569. {
  2570. int mode;
  2571. int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
  2572. switch(n) {
  2573. case PY_SSL_CERT_NONE:
  2574. mode = SSL_VERIFY_NONE;
  2575. break;
  2576. case PY_SSL_CERT_OPTIONAL:
  2577. mode = SSL_VERIFY_PEER;
  2578. break;
  2579. case PY_SSL_CERT_REQUIRED:
  2580. mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  2581. break;
  2582. default:
  2583. PyErr_SetString(PyExc_ValueError,
  2584. "invalid value for verify_mode");
  2585. return -1;
  2586. }
  2587. /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
  2588. * server sockets and SSL_set_post_handshake_auth() for client. */
  2589. /* keep current verify cb */
  2590. verify_cb = SSL_CTX_get_verify_callback(self->ctx);
  2591. SSL_CTX_set_verify(self->ctx, mode, verify_cb);
  2592. return 0;
  2593. }
  2594. /*[clinic input]
  2595. @classmethod
  2596. _ssl._SSLContext.__new__
  2597. protocol as proto_version: int
  2598. /
  2599. [clinic start generated code]*/
  2600. static PyObject *
  2601. _ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
  2602. /*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
  2603. {
  2604. PySSLContext *self;
  2605. uint64_t options;
  2606. const SSL_METHOD *method = NULL;
  2607. SSL_CTX *ctx = NULL;
  2608. X509_VERIFY_PARAM *params;
  2609. int result;
  2610. /* slower approach, walk MRO and get borrowed reference to module.
  2611. * PyType_GetModuleByDef is required for SSLContext subclasses */
  2612. PyObject *module = PyType_GetModuleByDef(type, &_sslmodule_def);
  2613. if (module == NULL) {
  2614. PyErr_SetString(PyExc_RuntimeError,
  2615. "Cannot find internal module state");
  2616. return NULL;
  2617. }
  2618. switch(proto_version) {
  2619. #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
  2620. case PY_SSL_VERSION_SSL3:
  2621. PY_SSL_DEPRECATED("ssl.PROTOCOL_SSLv3 is deprecated", 2, NULL);
  2622. method = SSLv3_method();
  2623. break;
  2624. #endif
  2625. #if (defined(TLS1_VERSION) && \
  2626. !defined(OPENSSL_NO_TLS1) && \
  2627. !defined(OPENSSL_NO_TLS1_METHOD))
  2628. case PY_SSL_VERSION_TLS1:
  2629. PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1 is deprecated", 2, NULL);
  2630. method = TLSv1_method();
  2631. break;
  2632. #endif
  2633. #if (defined(TLS1_1_VERSION) && \
  2634. !defined(OPENSSL_NO_TLS1_1) && \
  2635. !defined(OPENSSL_NO_TLS1_1_METHOD))
  2636. case PY_SSL_VERSION_TLS1_1:
  2637. PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_1 is deprecated", 2, NULL);
  2638. method = TLSv1_1_method();
  2639. break;
  2640. #endif
  2641. #if (defined(TLS1_2_VERSION) && \
  2642. !defined(OPENSSL_NO_TLS1_2) && \
  2643. !defined(OPENSSL_NO_TLS1_2_METHOD))
  2644. case PY_SSL_VERSION_TLS1_2:
  2645. PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_2 is deprecated", 2, NULL);
  2646. method = TLSv1_2_method();
  2647. break;
  2648. #endif
  2649. case PY_SSL_VERSION_TLS:
  2650. PY_SSL_DEPRECATED("ssl.PROTOCOL_TLS is deprecated", 2, NULL);
  2651. method = TLS_method();
  2652. break;
  2653. case PY_SSL_VERSION_TLS_CLIENT:
  2654. method = TLS_client_method();
  2655. break;
  2656. case PY_SSL_VERSION_TLS_SERVER:
  2657. method = TLS_server_method();
  2658. break;
  2659. default:
  2660. method = NULL;
  2661. }
  2662. if (method == NULL) {
  2663. PyErr_Format(PyExc_ValueError,
  2664. "invalid or unsupported protocol version %i",
  2665. proto_version);
  2666. return NULL;
  2667. }
  2668. PySSL_BEGIN_ALLOW_THREADS
  2669. ctx = SSL_CTX_new(method);
  2670. PySSL_END_ALLOW_THREADS
  2671. if (ctx == NULL) {
  2672. _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
  2673. return NULL;
  2674. }
  2675. assert(type != NULL && type->tp_alloc != NULL);
  2676. self = (PySSLContext *) type->tp_alloc(type, 0);
  2677. if (self == NULL) {
  2678. SSL_CTX_free(ctx);
  2679. return NULL;
  2680. }
  2681. self->ctx = ctx;
  2682. self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
  2683. self->protocol = proto_version;
  2684. self->msg_cb = NULL;
  2685. self->keylog_filename = NULL;
  2686. self->keylog_bio = NULL;
  2687. self->alpn_protocols = NULL;
  2688. self->set_sni_cb = NULL;
  2689. self->state = get_ssl_state(module);
  2690. /* Don't check host name by default */
  2691. if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
  2692. self->check_hostname = 1;
  2693. if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
  2694. Py_DECREF(self);
  2695. return NULL;
  2696. }
  2697. } else {
  2698. self->check_hostname = 0;
  2699. if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
  2700. Py_DECREF(self);
  2701. return NULL;
  2702. }
  2703. }
  2704. /* Defaults */
  2705. options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
  2706. if (proto_version != PY_SSL_VERSION_SSL2)
  2707. options |= SSL_OP_NO_SSLv2;
  2708. if (proto_version != PY_SSL_VERSION_SSL3)
  2709. options |= SSL_OP_NO_SSLv3;
  2710. /* Minimal security flags for server and client side context.
  2711. * Client sockets ignore server-side parameters. */
  2712. #ifdef SSL_OP_NO_COMPRESSION
  2713. options |= SSL_OP_NO_COMPRESSION;
  2714. #endif
  2715. #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
  2716. options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
  2717. #endif
  2718. #ifdef SSL_OP_SINGLE_DH_USE
  2719. options |= SSL_OP_SINGLE_DH_USE;
  2720. #endif
  2721. #ifdef SSL_OP_SINGLE_ECDH_USE
  2722. options |= SSL_OP_SINGLE_ECDH_USE;
  2723. #endif
  2724. SSL_CTX_set_options(self->ctx, options);
  2725. /* A bare minimum cipher list without completely broken cipher suites.
  2726. * It's far from perfect but gives users a better head start. */
  2727. if (proto_version != PY_SSL_VERSION_SSL2) {
  2728. #if PY_SSL_DEFAULT_CIPHERS == 2
  2729. /* stick to OpenSSL's default settings */
  2730. result = 1;
  2731. #else
  2732. result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
  2733. #endif
  2734. } else {
  2735. /* SSLv2 needs MD5 */
  2736. result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
  2737. }
  2738. if (result == 0) {
  2739. ERR_clear_error();
  2740. PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
  2741. "No cipher can be selected.");
  2742. goto error;
  2743. }
  2744. #ifdef PY_SSL_MIN_PROTOCOL
  2745. switch(proto_version) {
  2746. case PY_SSL_VERSION_TLS:
  2747. case PY_SSL_VERSION_TLS_CLIENT:
  2748. case PY_SSL_VERSION_TLS_SERVER:
  2749. result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
  2750. if (result == 0) {
  2751. PyErr_Format(PyExc_ValueError,
  2752. "Failed to set minimum protocol 0x%x",
  2753. PY_SSL_MIN_PROTOCOL);
  2754. goto error;
  2755. }
  2756. break;
  2757. default:
  2758. break;
  2759. }
  2760. #endif
  2761. /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
  2762. usage for no cost at all. */
  2763. SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
  2764. #define SID_CTX "Python"
  2765. SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
  2766. sizeof(SID_CTX));
  2767. #undef SID_CTX
  2768. params = SSL_CTX_get0_param(self->ctx);
  2769. /* Improve trust chain building when cross-signed intermediate
  2770. certificates are present. See https://bugs.python.org/issue23476. */
  2771. X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
  2772. X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
  2773. #ifdef TLS1_3_VERSION
  2774. self->post_handshake_auth = 0;
  2775. SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
  2776. #endif
  2777. return (PyObject *)self;
  2778. error:
  2779. Py_XDECREF(self);
  2780. ERR_clear_error();
  2781. return NULL;
  2782. }
  2783. static int
  2784. context_traverse(PySSLContext *self, visitproc visit, void *arg)
  2785. {
  2786. Py_VISIT(self->set_sni_cb);
  2787. Py_VISIT(self->msg_cb);
  2788. Py_VISIT(Py_TYPE(self));
  2789. return 0;
  2790. }
  2791. static int
  2792. context_clear(PySSLContext *self)
  2793. {
  2794. Py_CLEAR(self->set_sni_cb);
  2795. Py_CLEAR(self->msg_cb);
  2796. Py_CLEAR(self->keylog_filename);
  2797. if (self->keylog_bio != NULL) {
  2798. PySSL_BEGIN_ALLOW_THREADS
  2799. BIO_free_all(self->keylog_bio);
  2800. PySSL_END_ALLOW_THREADS
  2801. self->keylog_bio = NULL;
  2802. }
  2803. return 0;
  2804. }
  2805. static void
  2806. context_dealloc(PySSLContext *self)
  2807. {
  2808. PyTypeObject *tp = Py_TYPE(self);
  2809. /* bpo-31095: UnTrack is needed before calling any callbacks */
  2810. PyObject_GC_UnTrack(self);
  2811. context_clear(self);
  2812. SSL_CTX_free(self->ctx);
  2813. PyMem_FREE(self->alpn_protocols);
  2814. Py_TYPE(self)->tp_free(self);
  2815. Py_DECREF(tp);
  2816. }
  2817. /*[clinic input]
  2818. _ssl._SSLContext.set_ciphers
  2819. cipherlist: str
  2820. /
  2821. [clinic start generated code]*/
  2822. static PyObject *
  2823. _ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
  2824. /*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
  2825. {
  2826. int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
  2827. if (ret == 0) {
  2828. /* Clearing the error queue is necessary on some OpenSSL versions,
  2829. otherwise the error will be reported again when another SSL call
  2830. is done. */
  2831. ERR_clear_error();
  2832. PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
  2833. "No cipher can be selected.");
  2834. return NULL;
  2835. }
  2836. Py_RETURN_NONE;
  2837. }
  2838. /*[clinic input]
  2839. _ssl._SSLContext.get_ciphers
  2840. [clinic start generated code]*/
  2841. static PyObject *
  2842. _ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
  2843. /*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
  2844. {
  2845. SSL *ssl = NULL;
  2846. STACK_OF(SSL_CIPHER) *sk = NULL;
  2847. const SSL_CIPHER *cipher;
  2848. int i=0;
  2849. PyObject *result = NULL, *dct;
  2850. ssl = SSL_new(self->ctx);
  2851. if (ssl == NULL) {
  2852. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  2853. goto exit;
  2854. }
  2855. sk = SSL_get_ciphers(ssl);
  2856. result = PyList_New(sk_SSL_CIPHER_num(sk));
  2857. if (result == NULL) {
  2858. goto exit;
  2859. }
  2860. for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
  2861. cipher = sk_SSL_CIPHER_value(sk, i);
  2862. dct = cipher_to_dict(cipher);
  2863. if (dct == NULL) {
  2864. Py_CLEAR(result);
  2865. goto exit;
  2866. }
  2867. PyList_SET_ITEM(result, i, dct);
  2868. }
  2869. exit:
  2870. if (ssl != NULL)
  2871. SSL_free(ssl);
  2872. return result;
  2873. }
  2874. static int
  2875. do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
  2876. const unsigned char *server_protocols, unsigned int server_protocols_len,
  2877. const unsigned char *client_protocols, unsigned int client_protocols_len)
  2878. {
  2879. int ret;
  2880. if (client_protocols == NULL) {
  2881. client_protocols = (unsigned char *)"";
  2882. client_protocols_len = 0;
  2883. }
  2884. if (server_protocols == NULL) {
  2885. server_protocols = (unsigned char *)"";
  2886. server_protocols_len = 0;
  2887. }
  2888. ret = SSL_select_next_proto(out, outlen,
  2889. server_protocols, server_protocols_len,
  2890. client_protocols, client_protocols_len);
  2891. if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
  2892. return SSL_TLSEXT_ERR_NOACK;
  2893. return SSL_TLSEXT_ERR_OK;
  2894. }
  2895. static int
  2896. _selectALPN_cb(SSL *s,
  2897. const unsigned char **out, unsigned char *outlen,
  2898. const unsigned char *client_protocols, unsigned int client_protocols_len,
  2899. void *args)
  2900. {
  2901. PySSLContext *ctx = (PySSLContext *)args;
  2902. return do_protocol_selection(1, (unsigned char **)out, outlen,
  2903. ctx->alpn_protocols, ctx->alpn_protocols_len,
  2904. client_protocols, client_protocols_len);
  2905. }
  2906. /*[clinic input]
  2907. _ssl._SSLContext._set_alpn_protocols
  2908. protos: Py_buffer
  2909. /
  2910. [clinic start generated code]*/
  2911. static PyObject *
  2912. _ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
  2913. Py_buffer *protos)
  2914. /*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
  2915. {
  2916. if ((size_t)protos->len > UINT_MAX) {
  2917. PyErr_Format(PyExc_OverflowError,
  2918. "protocols longer than %u bytes", UINT_MAX);
  2919. return NULL;
  2920. }
  2921. PyMem_Free(self->alpn_protocols);
  2922. self->alpn_protocols = PyMem_Malloc(protos->len);
  2923. if (!self->alpn_protocols)
  2924. return PyErr_NoMemory();
  2925. memcpy(self->alpn_protocols, protos->buf, protos->len);
  2926. self->alpn_protocols_len = (unsigned int)protos->len;
  2927. if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
  2928. return PyErr_NoMemory();
  2929. SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
  2930. Py_RETURN_NONE;
  2931. }
  2932. static PyObject *
  2933. get_verify_mode(PySSLContext *self, void *c)
  2934. {
  2935. /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
  2936. int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
  2937. SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
  2938. switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
  2939. case SSL_VERIFY_NONE:
  2940. return PyLong_FromLong(PY_SSL_CERT_NONE);
  2941. case SSL_VERIFY_PEER:
  2942. return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
  2943. case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
  2944. return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
  2945. }
  2946. PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
  2947. "invalid return value from SSL_CTX_get_verify_mode");
  2948. return NULL;
  2949. }
  2950. static int
  2951. set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
  2952. {
  2953. int n;
  2954. if (!PyArg_Parse(arg, "i", &n))
  2955. return -1;
  2956. if (n == PY_SSL_CERT_NONE && self->check_hostname) {
  2957. PyErr_SetString(PyExc_ValueError,
  2958. "Cannot set verify_mode to CERT_NONE when "
  2959. "check_hostname is enabled.");
  2960. return -1;
  2961. }
  2962. return _set_verify_mode(self, n);
  2963. }
  2964. static PyObject *
  2965. get_verify_flags(PySSLContext *self, void *c)
  2966. {
  2967. X509_VERIFY_PARAM *param;
  2968. unsigned long flags;
  2969. param = SSL_CTX_get0_param(self->ctx);
  2970. flags = X509_VERIFY_PARAM_get_flags(param);
  2971. return PyLong_FromUnsignedLong(flags);
  2972. }
  2973. static int
  2974. set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
  2975. {
  2976. X509_VERIFY_PARAM *param;
  2977. unsigned long new_flags, flags, set, clear;
  2978. if (!PyArg_Parse(arg, "k", &new_flags))
  2979. return -1;
  2980. param = SSL_CTX_get0_param(self->ctx);
  2981. flags = X509_VERIFY_PARAM_get_flags(param);
  2982. clear = flags & ~new_flags;
  2983. set = ~flags & new_flags;
  2984. if (clear) {
  2985. if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
  2986. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  2987. return -1;
  2988. }
  2989. }
  2990. if (set) {
  2991. if (!X509_VERIFY_PARAM_set_flags(param, set)) {
  2992. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  2993. return -1;
  2994. }
  2995. }
  2996. return 0;
  2997. }
  2998. /* Getter and setter for protocol version */
  2999. static int
  3000. set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
  3001. {
  3002. long v;
  3003. int result;
  3004. if (!PyArg_Parse(arg, "l", &v))
  3005. return -1;
  3006. if (v > INT_MAX) {
  3007. PyErr_SetString(PyExc_OverflowError, "Option is too long");
  3008. return -1;
  3009. }
  3010. switch(self->protocol) {
  3011. case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
  3012. case PY_SSL_VERSION_TLS_SERVER: /* fall through */
  3013. case PY_SSL_VERSION_TLS:
  3014. break;
  3015. default:
  3016. PyErr_SetString(
  3017. PyExc_ValueError,
  3018. "The context's protocol doesn't support modification of "
  3019. "highest and lowest version."
  3020. );
  3021. return -1;
  3022. }
  3023. /* check for deprecations and supported values */
  3024. switch(v) {
  3025. case PY_PROTO_SSLv3:
  3026. PY_SSL_DEPRECATED("ssl.TLSVersion.SSLv3 is deprecated", 2, -1);
  3027. break;
  3028. case PY_PROTO_TLSv1:
  3029. PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1 is deprecated", 2, -1);
  3030. break;
  3031. case PY_PROTO_TLSv1_1:
  3032. PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1_1 is deprecated", 2, -1);
  3033. break;
  3034. case PY_PROTO_MINIMUM_SUPPORTED:
  3035. case PY_PROTO_MAXIMUM_SUPPORTED:
  3036. case PY_PROTO_TLSv1_2:
  3037. case PY_PROTO_TLSv1_3:
  3038. /* ok */
  3039. break;
  3040. default:
  3041. PyErr_Format(PyExc_ValueError,
  3042. "Unsupported TLS/SSL version 0x%x", v);
  3043. return -1;
  3044. }
  3045. if (what == 0) {
  3046. switch(v) {
  3047. case PY_PROTO_MINIMUM_SUPPORTED:
  3048. v = 0;
  3049. break;
  3050. case PY_PROTO_MAXIMUM_SUPPORTED:
  3051. /* Emulate max for set_min_proto_version */
  3052. v = PY_PROTO_MAXIMUM_AVAILABLE;
  3053. break;
  3054. default:
  3055. break;
  3056. }
  3057. result = SSL_CTX_set_min_proto_version(self->ctx, v);
  3058. }
  3059. else {
  3060. switch(v) {
  3061. case PY_PROTO_MAXIMUM_SUPPORTED:
  3062. v = 0;
  3063. break;
  3064. case PY_PROTO_MINIMUM_SUPPORTED:
  3065. /* Emulate max for set_min_proto_version */
  3066. v = PY_PROTO_MINIMUM_AVAILABLE;
  3067. break;
  3068. default:
  3069. break;
  3070. }
  3071. result = SSL_CTX_set_max_proto_version(self->ctx, v);
  3072. }
  3073. if (result == 0) {
  3074. PyErr_Format(PyExc_ValueError,
  3075. "Unsupported protocol version 0x%x", v);
  3076. return -1;
  3077. }
  3078. return 0;
  3079. }
  3080. static PyObject *
  3081. get_minimum_version(PySSLContext *self, void *c)
  3082. {
  3083. int v = SSL_CTX_get_min_proto_version(self->ctx);
  3084. if (v == 0) {
  3085. v = PY_PROTO_MINIMUM_SUPPORTED;
  3086. }
  3087. return PyLong_FromLong(v);
  3088. }
  3089. static int
  3090. set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
  3091. {
  3092. return set_min_max_proto_version(self, arg, 0);
  3093. }
  3094. static PyObject *
  3095. get_maximum_version(PySSLContext *self, void *c)
  3096. {
  3097. int v = SSL_CTX_get_max_proto_version(self->ctx);
  3098. if (v == 0) {
  3099. v = PY_PROTO_MAXIMUM_SUPPORTED;
  3100. }
  3101. return PyLong_FromLong(v);
  3102. }
  3103. static int
  3104. set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
  3105. {
  3106. return set_min_max_proto_version(self, arg, 1);
  3107. }
  3108. #ifdef TLS1_3_VERSION
  3109. static PyObject *
  3110. get_num_tickets(PySSLContext *self, void *c)
  3111. {
  3112. return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
  3113. }
  3114. static int
  3115. set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
  3116. {
  3117. long num;
  3118. if (!PyArg_Parse(arg, "l", &num))
  3119. return -1;
  3120. if (num < 0) {
  3121. PyErr_SetString(PyExc_ValueError, "value must be non-negative");
  3122. return -1;
  3123. }
  3124. if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
  3125. PyErr_SetString(PyExc_ValueError,
  3126. "SSLContext is not a server context.");
  3127. return -1;
  3128. }
  3129. if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
  3130. PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
  3131. return -1;
  3132. }
  3133. return 0;
  3134. }
  3135. PyDoc_STRVAR(PySSLContext_num_tickets_doc,
  3136. "Control the number of TLSv1.3 session tickets");
  3137. #endif /* TLS1_3_VERSION */
  3138. static PyObject *
  3139. get_security_level(PySSLContext *self, void *c)
  3140. {
  3141. return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
  3142. }
  3143. PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
  3144. static PyObject *
  3145. get_options(PySSLContext *self, void *c)
  3146. {
  3147. uint64_t options = SSL_CTX_get_options(self->ctx);
  3148. Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(options));
  3149. return PyLong_FromUnsignedLongLong(options);
  3150. }
  3151. static int
  3152. set_options(PySSLContext *self, PyObject *arg, void *c)
  3153. {
  3154. PyObject *new_opts_obj;
  3155. unsigned long long new_opts_arg;
  3156. uint64_t new_opts, opts, clear, set;
  3157. uint64_t opt_no = (
  3158. SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
  3159. SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3
  3160. );
  3161. if (!PyArg_Parse(arg, "O!", &PyLong_Type, &new_opts_obj)) {
  3162. return -1;
  3163. }
  3164. new_opts_arg = PyLong_AsUnsignedLongLong(new_opts_obj);
  3165. if (new_opts_arg == (unsigned long long)-1 && PyErr_Occurred()) {
  3166. return -1;
  3167. }
  3168. Py_BUILD_ASSERT(sizeof(new_opts) >= sizeof(new_opts_arg));
  3169. new_opts = (uint64_t)new_opts_arg;
  3170. opts = SSL_CTX_get_options(self->ctx);
  3171. clear = opts & ~new_opts;
  3172. set = ~opts & new_opts;
  3173. if ((set & opt_no) != 0) {
  3174. if (_ssl_deprecated("ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are "
  3175. "deprecated", 2) < 0) {
  3176. return -1;
  3177. }
  3178. }
  3179. if (clear) {
  3180. SSL_CTX_clear_options(self->ctx, clear);
  3181. }
  3182. if (set) {
  3183. SSL_CTX_set_options(self->ctx, set);
  3184. }
  3185. return 0;
  3186. }
  3187. static PyObject *
  3188. get_host_flags(PySSLContext *self, void *c)
  3189. {
  3190. return PyLong_FromUnsignedLong(self->hostflags);
  3191. }
  3192. static int
  3193. set_host_flags(PySSLContext *self, PyObject *arg, void *c)
  3194. {
  3195. X509_VERIFY_PARAM *param;
  3196. unsigned int new_flags = 0;
  3197. if (!PyArg_Parse(arg, "I", &new_flags))
  3198. return -1;
  3199. param = SSL_CTX_get0_param(self->ctx);
  3200. self->hostflags = new_flags;
  3201. X509_VERIFY_PARAM_set_hostflags(param, new_flags);
  3202. return 0;
  3203. }
  3204. static PyObject *
  3205. get_check_hostname(PySSLContext *self, void *c)
  3206. {
  3207. return PyBool_FromLong(self->check_hostname);
  3208. }
  3209. static int
  3210. set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
  3211. {
  3212. int check_hostname;
  3213. if (!PyArg_Parse(arg, "p", &check_hostname))
  3214. return -1;
  3215. if (check_hostname &&
  3216. SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
  3217. /* check_hostname = True sets verify_mode = CERT_REQUIRED */
  3218. if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
  3219. return -1;
  3220. }
  3221. }
  3222. self->check_hostname = check_hostname;
  3223. return 0;
  3224. }
  3225. static PyObject *
  3226. get_post_handshake_auth(PySSLContext *self, void *c) {
  3227. #if TLS1_3_VERSION
  3228. return PyBool_FromLong(self->post_handshake_auth);
  3229. #else
  3230. Py_RETURN_NONE;
  3231. #endif
  3232. }
  3233. #if TLS1_3_VERSION
  3234. static int
  3235. set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
  3236. if (arg == NULL) {
  3237. PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
  3238. return -1;
  3239. }
  3240. int pha = PyObject_IsTrue(arg);
  3241. if (pha == -1) {
  3242. return -1;
  3243. }
  3244. self->post_handshake_auth = pha;
  3245. /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
  3246. * server sockets and SSL_set_post_handshake_auth() for client. */
  3247. return 0;
  3248. }
  3249. #endif
  3250. static PyObject *
  3251. get_protocol(PySSLContext *self, void *c) {
  3252. return PyLong_FromLong(self->protocol);
  3253. }
  3254. typedef struct {
  3255. PyThreadState *thread_state;
  3256. PyObject *callable;
  3257. char *password;
  3258. int size;
  3259. int error;
  3260. } _PySSLPasswordInfo;
  3261. static int
  3262. _pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
  3263. const char *bad_type_error)
  3264. {
  3265. /* Set the password and size fields of a _PySSLPasswordInfo struct
  3266. from a unicode, bytes, or byte array object.
  3267. The password field will be dynamically allocated and must be freed
  3268. by the caller */
  3269. PyObject *password_bytes = NULL;
  3270. const char *data = NULL;
  3271. Py_ssize_t size;
  3272. if (PyUnicode_Check(password)) {
  3273. password_bytes = PyUnicode_AsUTF8String(password);
  3274. if (!password_bytes) {
  3275. goto error;
  3276. }
  3277. data = PyBytes_AS_STRING(password_bytes);
  3278. size = PyBytes_GET_SIZE(password_bytes);
  3279. } else if (PyBytes_Check(password)) {
  3280. data = PyBytes_AS_STRING(password);
  3281. size = PyBytes_GET_SIZE(password);
  3282. } else if (PyByteArray_Check(password)) {
  3283. data = PyByteArray_AS_STRING(password);
  3284. size = PyByteArray_GET_SIZE(password);
  3285. } else {
  3286. PyErr_SetString(PyExc_TypeError, bad_type_error);
  3287. goto error;
  3288. }
  3289. if (size > (Py_ssize_t)INT_MAX) {
  3290. PyErr_Format(PyExc_ValueError,
  3291. "password cannot be longer than %d bytes", INT_MAX);
  3292. goto error;
  3293. }
  3294. PyMem_Free(pw_info->password);
  3295. pw_info->password = PyMem_Malloc(size);
  3296. if (!pw_info->password) {
  3297. PyErr_SetString(PyExc_MemoryError,
  3298. "unable to allocate password buffer");
  3299. goto error;
  3300. }
  3301. memcpy(pw_info->password, data, size);
  3302. pw_info->size = (int)size;
  3303. Py_XDECREF(password_bytes);
  3304. return 1;
  3305. error:
  3306. Py_XDECREF(password_bytes);
  3307. return 0;
  3308. }
  3309. static int
  3310. _password_callback(char *buf, int size, int rwflag, void *userdata)
  3311. {
  3312. _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
  3313. PyObject *fn_ret = NULL;
  3314. PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
  3315. if (pw_info->error) {
  3316. /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
  3317. * callback multiple times which can lead to fatal Python error in
  3318. * exception check. */
  3319. goto error;
  3320. }
  3321. if (pw_info->callable) {
  3322. fn_ret = PyObject_CallNoArgs(pw_info->callable);
  3323. if (!fn_ret) {
  3324. /* TODO: It would be nice to move _ctypes_add_traceback() into the
  3325. core python API, so we could use it to add a frame here */
  3326. goto error;
  3327. }
  3328. if (!_pwinfo_set(pw_info, fn_ret,
  3329. "password callback must return a string")) {
  3330. goto error;
  3331. }
  3332. Py_CLEAR(fn_ret);
  3333. }
  3334. if (pw_info->size > size) {
  3335. PyErr_Format(PyExc_ValueError,
  3336. "password cannot be longer than %d bytes", size);
  3337. goto error;
  3338. }
  3339. PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
  3340. memcpy(buf, pw_info->password, pw_info->size);
  3341. return pw_info->size;
  3342. error:
  3343. Py_XDECREF(fn_ret);
  3344. PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
  3345. pw_info->error = 1;
  3346. return -1;
  3347. }
  3348. /*[clinic input]
  3349. _ssl._SSLContext.load_cert_chain
  3350. certfile: object
  3351. keyfile: object = None
  3352. password: object = None
  3353. [clinic start generated code]*/
  3354. static PyObject *
  3355. _ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
  3356. PyObject *keyfile, PyObject *password)
  3357. /*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
  3358. {
  3359. PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
  3360. pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
  3361. void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
  3362. _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
  3363. int r;
  3364. errno = 0;
  3365. ERR_clear_error();
  3366. if (keyfile == Py_None)
  3367. keyfile = NULL;
  3368. if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
  3369. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  3370. PyErr_SetString(PyExc_TypeError,
  3371. "certfile should be a valid filesystem path");
  3372. }
  3373. return NULL;
  3374. }
  3375. if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
  3376. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  3377. PyErr_SetString(PyExc_TypeError,
  3378. "keyfile should be a valid filesystem path");
  3379. }
  3380. goto error;
  3381. }
  3382. if (password != Py_None) {
  3383. if (PyCallable_Check(password)) {
  3384. pw_info.callable = password;
  3385. } else if (!_pwinfo_set(&pw_info, password,
  3386. "password should be a string or callable")) {
  3387. goto error;
  3388. }
  3389. SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
  3390. SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
  3391. }
  3392. PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
  3393. r = SSL_CTX_use_certificate_chain_file(self->ctx,
  3394. PyBytes_AS_STRING(certfile_bytes));
  3395. PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
  3396. if (r != 1) {
  3397. if (pw_info.error) {
  3398. ERR_clear_error();
  3399. /* the password callback has already set the error information */
  3400. }
  3401. else if (errno != 0) {
  3402. PyErr_SetFromErrno(PyExc_OSError);
  3403. ERR_clear_error();
  3404. }
  3405. else {
  3406. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3407. }
  3408. goto error;
  3409. }
  3410. PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
  3411. r = SSL_CTX_use_PrivateKey_file(self->ctx,
  3412. PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
  3413. SSL_FILETYPE_PEM);
  3414. PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
  3415. Py_CLEAR(keyfile_bytes);
  3416. Py_CLEAR(certfile_bytes);
  3417. if (r != 1) {
  3418. if (pw_info.error) {
  3419. ERR_clear_error();
  3420. /* the password callback has already set the error information */
  3421. }
  3422. else if (errno != 0) {
  3423. PyErr_SetFromErrno(PyExc_OSError);
  3424. ERR_clear_error();
  3425. }
  3426. else {
  3427. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3428. }
  3429. goto error;
  3430. }
  3431. PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
  3432. r = SSL_CTX_check_private_key(self->ctx);
  3433. PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
  3434. if (r != 1) {
  3435. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3436. goto error;
  3437. }
  3438. SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
  3439. SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
  3440. PyMem_Free(pw_info.password);
  3441. Py_RETURN_NONE;
  3442. error:
  3443. SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
  3444. SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
  3445. PyMem_Free(pw_info.password);
  3446. Py_XDECREF(keyfile_bytes);
  3447. Py_XDECREF(certfile_bytes);
  3448. return NULL;
  3449. }
  3450. /* internal helper function, returns -1 on error
  3451. */
  3452. static int
  3453. _add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
  3454. int filetype)
  3455. {
  3456. BIO *biobuf = NULL;
  3457. X509_STORE *store;
  3458. int retval = -1, err, loaded = 0, was_bio_eof = 0;
  3459. assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
  3460. if (len <= 0) {
  3461. PyErr_SetString(PyExc_ValueError,
  3462. "Empty certificate data");
  3463. return -1;
  3464. } else if (len > INT_MAX) {
  3465. PyErr_SetString(PyExc_OverflowError,
  3466. "Certificate data is too long.");
  3467. return -1;
  3468. }
  3469. biobuf = BIO_new_mem_buf(data, (int)len);
  3470. if (biobuf == NULL) {
  3471. _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
  3472. return -1;
  3473. }
  3474. store = SSL_CTX_get_cert_store(self->ctx);
  3475. assert(store != NULL);
  3476. while (1) {
  3477. X509 *cert = NULL;
  3478. int r;
  3479. if (filetype == SSL_FILETYPE_ASN1) {
  3480. if (BIO_eof(biobuf)) {
  3481. was_bio_eof = 1;
  3482. break;
  3483. }
  3484. cert = d2i_X509_bio(biobuf, NULL);
  3485. } else {
  3486. cert = PEM_read_bio_X509(biobuf, NULL,
  3487. SSL_CTX_get_default_passwd_cb(self->ctx),
  3488. SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
  3489. );
  3490. }
  3491. if (cert == NULL) {
  3492. break;
  3493. }
  3494. r = X509_STORE_add_cert(store, cert);
  3495. X509_free(cert);
  3496. if (!r) {
  3497. err = ERR_peek_last_error();
  3498. if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
  3499. (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
  3500. /* cert already in hash table, not an error */
  3501. ERR_clear_error();
  3502. } else {
  3503. break;
  3504. }
  3505. }
  3506. loaded++;
  3507. }
  3508. err = ERR_peek_last_error();
  3509. if (loaded == 0) {
  3510. const char *msg = NULL;
  3511. if (filetype == SSL_FILETYPE_PEM) {
  3512. msg = "no start line: cadata does not contain a certificate";
  3513. } else {
  3514. msg = "not enough data: cadata does not contain a certificate";
  3515. }
  3516. _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
  3517. retval = -1;
  3518. } else if ((filetype == SSL_FILETYPE_ASN1) && was_bio_eof) {
  3519. /* EOF ASN1 file, not an error */
  3520. ERR_clear_error();
  3521. retval = 0;
  3522. } else if ((filetype == SSL_FILETYPE_PEM) &&
  3523. (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
  3524. (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
  3525. /* EOF PEM file, not an error */
  3526. ERR_clear_error();
  3527. retval = 0;
  3528. } else if (err != 0) {
  3529. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3530. retval = -1;
  3531. } else {
  3532. retval = 0;
  3533. }
  3534. BIO_free(biobuf);
  3535. return retval;
  3536. }
  3537. /*[clinic input]
  3538. _ssl._SSLContext.load_verify_locations
  3539. cafile: object = None
  3540. capath: object = None
  3541. cadata: object = None
  3542. [clinic start generated code]*/
  3543. static PyObject *
  3544. _ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
  3545. PyObject *cafile,
  3546. PyObject *capath,
  3547. PyObject *cadata)
  3548. /*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
  3549. {
  3550. PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
  3551. const char *cafile_buf = NULL, *capath_buf = NULL;
  3552. int r = 0, ok = 1;
  3553. errno = 0;
  3554. if (cafile == Py_None)
  3555. cafile = NULL;
  3556. if (capath == Py_None)
  3557. capath = NULL;
  3558. if (cadata == Py_None)
  3559. cadata = NULL;
  3560. if (cafile == NULL && capath == NULL && cadata == NULL) {
  3561. PyErr_SetString(PyExc_TypeError,
  3562. "cafile, capath and cadata cannot be all omitted");
  3563. goto error;
  3564. }
  3565. if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
  3566. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  3567. PyErr_SetString(PyExc_TypeError,
  3568. "cafile should be a valid filesystem path");
  3569. }
  3570. goto error;
  3571. }
  3572. if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
  3573. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  3574. PyErr_SetString(PyExc_TypeError,
  3575. "capath should be a valid filesystem path");
  3576. }
  3577. goto error;
  3578. }
  3579. /* validate cadata type and load cadata */
  3580. if (cadata) {
  3581. if (PyUnicode_Check(cadata)) {
  3582. PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
  3583. if (cadata_ascii == NULL) {
  3584. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
  3585. goto invalid_cadata;
  3586. }
  3587. goto error;
  3588. }
  3589. r = _add_ca_certs(self,
  3590. PyBytes_AS_STRING(cadata_ascii),
  3591. PyBytes_GET_SIZE(cadata_ascii),
  3592. SSL_FILETYPE_PEM);
  3593. Py_DECREF(cadata_ascii);
  3594. if (r == -1) {
  3595. goto error;
  3596. }
  3597. }
  3598. else if (PyObject_CheckBuffer(cadata)) {
  3599. Py_buffer buf;
  3600. if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
  3601. goto error;
  3602. }
  3603. if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
  3604. PyBuffer_Release(&buf);
  3605. PyErr_SetString(PyExc_TypeError,
  3606. "cadata should be a contiguous buffer with "
  3607. "a single dimension");
  3608. goto error;
  3609. }
  3610. r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
  3611. PyBuffer_Release(&buf);
  3612. if (r == -1) {
  3613. goto error;
  3614. }
  3615. }
  3616. else {
  3617. invalid_cadata:
  3618. PyErr_SetString(PyExc_TypeError,
  3619. "cadata should be an ASCII string or a "
  3620. "bytes-like object");
  3621. goto error;
  3622. }
  3623. }
  3624. /* load cafile or capath */
  3625. if (cafile || capath) {
  3626. if (cafile)
  3627. cafile_buf = PyBytes_AS_STRING(cafile_bytes);
  3628. if (capath)
  3629. capath_buf = PyBytes_AS_STRING(capath_bytes);
  3630. PySSL_BEGIN_ALLOW_THREADS
  3631. r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
  3632. PySSL_END_ALLOW_THREADS
  3633. if (r != 1) {
  3634. if (errno != 0) {
  3635. PyErr_SetFromErrno(PyExc_OSError);
  3636. ERR_clear_error();
  3637. }
  3638. else {
  3639. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3640. }
  3641. goto error;
  3642. }
  3643. }
  3644. goto end;
  3645. error:
  3646. ok = 0;
  3647. end:
  3648. Py_XDECREF(cafile_bytes);
  3649. Py_XDECREF(capath_bytes);
  3650. if (ok) {
  3651. Py_RETURN_NONE;
  3652. } else {
  3653. return NULL;
  3654. }
  3655. }
  3656. /*[clinic input]
  3657. _ssl._SSLContext.load_dh_params
  3658. path as filepath: object
  3659. /
  3660. [clinic start generated code]*/
  3661. static PyObject *
  3662. _ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
  3663. /*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
  3664. {
  3665. FILE *f;
  3666. DH *dh;
  3667. f = _Py_fopen_obj(filepath, "rb");
  3668. if (f == NULL)
  3669. return NULL;
  3670. errno = 0;
  3671. PySSL_BEGIN_ALLOW_THREADS
  3672. dh = PEM_read_DHparams(f, NULL, NULL, NULL);
  3673. fclose(f);
  3674. PySSL_END_ALLOW_THREADS
  3675. if (dh == NULL) {
  3676. if (errno != 0) {
  3677. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
  3678. ERR_clear_error();
  3679. }
  3680. else {
  3681. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3682. }
  3683. return NULL;
  3684. }
  3685. if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
  3686. DH_free(dh);
  3687. return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3688. }
  3689. DH_free(dh);
  3690. Py_RETURN_NONE;
  3691. }
  3692. /*[clinic input]
  3693. _ssl._SSLContext._wrap_socket
  3694. sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
  3695. server_side: bool
  3696. server_hostname as hostname_obj: object = None
  3697. *
  3698. owner: object = None
  3699. session: object = None
  3700. [clinic start generated code]*/
  3701. static PyObject *
  3702. _ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
  3703. int server_side, PyObject *hostname_obj,
  3704. PyObject *owner, PyObject *session)
  3705. /*[clinic end generated code: output=f103f238633940b4 input=700ca8fedff53994]*/
  3706. {
  3707. char *hostname = NULL;
  3708. PyObject *res;
  3709. /* server_hostname is either None (or absent), or to be encoded
  3710. as IDN A-label (ASCII str) without NULL bytes. */
  3711. if (hostname_obj != Py_None) {
  3712. if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
  3713. return NULL;
  3714. }
  3715. res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
  3716. server_side, hostname,
  3717. owner, session,
  3718. NULL, NULL);
  3719. if (hostname != NULL)
  3720. PyMem_Free(hostname);
  3721. return res;
  3722. }
  3723. /*[clinic input]
  3724. _ssl._SSLContext._wrap_bio
  3725. incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
  3726. outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
  3727. server_side: bool
  3728. server_hostname as hostname_obj: object = None
  3729. *
  3730. owner: object = None
  3731. session: object = None
  3732. [clinic start generated code]*/
  3733. static PyObject *
  3734. _ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
  3735. PySSLMemoryBIO *outgoing, int server_side,
  3736. PyObject *hostname_obj, PyObject *owner,
  3737. PyObject *session)
  3738. /*[clinic end generated code: output=5c5d6d9b41f99332 input=a9205d097fd45a82]*/
  3739. {
  3740. char *hostname = NULL;
  3741. PyObject *res;
  3742. /* server_hostname is either None (or absent), or to be encoded
  3743. as IDN A-label (ASCII str) without NULL bytes. */
  3744. if (hostname_obj != Py_None) {
  3745. if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
  3746. return NULL;
  3747. }
  3748. res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
  3749. owner, session,
  3750. incoming, outgoing);
  3751. PyMem_Free(hostname);
  3752. return res;
  3753. }
  3754. /*[clinic input]
  3755. _ssl._SSLContext.session_stats
  3756. [clinic start generated code]*/
  3757. static PyObject *
  3758. _ssl__SSLContext_session_stats_impl(PySSLContext *self)
  3759. /*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
  3760. {
  3761. int r;
  3762. PyObject *value, *stats = PyDict_New();
  3763. if (!stats)
  3764. return NULL;
  3765. #define ADD_STATS(SSL_NAME, KEY_NAME) \
  3766. value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
  3767. if (value == NULL) \
  3768. goto error; \
  3769. r = PyDict_SetItemString(stats, KEY_NAME, value); \
  3770. Py_DECREF(value); \
  3771. if (r < 0) \
  3772. goto error;
  3773. ADD_STATS(number, "number");
  3774. ADD_STATS(connect, "connect");
  3775. ADD_STATS(connect_good, "connect_good");
  3776. ADD_STATS(connect_renegotiate, "connect_renegotiate");
  3777. ADD_STATS(accept, "accept");
  3778. ADD_STATS(accept_good, "accept_good");
  3779. ADD_STATS(accept_renegotiate, "accept_renegotiate");
  3780. ADD_STATS(accept, "accept");
  3781. ADD_STATS(hits, "hits");
  3782. ADD_STATS(misses, "misses");
  3783. ADD_STATS(timeouts, "timeouts");
  3784. ADD_STATS(cache_full, "cache_full");
  3785. #undef ADD_STATS
  3786. return stats;
  3787. error:
  3788. Py_DECREF(stats);
  3789. return NULL;
  3790. }
  3791. /*[clinic input]
  3792. _ssl._SSLContext.set_default_verify_paths
  3793. [clinic start generated code]*/
  3794. static PyObject *
  3795. _ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
  3796. /*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
  3797. {
  3798. int rc;
  3799. Py_BEGIN_ALLOW_THREADS
  3800. rc = SSL_CTX_set_default_verify_paths(self->ctx);
  3801. Py_END_ALLOW_THREADS
  3802. if (!rc) {
  3803. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3804. return NULL;
  3805. }
  3806. Py_RETURN_NONE;
  3807. }
  3808. /*[clinic input]
  3809. _ssl._SSLContext.set_ecdh_curve
  3810. name: object
  3811. /
  3812. [clinic start generated code]*/
  3813. static PyObject *
  3814. _ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
  3815. /*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
  3816. {
  3817. PyObject *name_bytes;
  3818. int nid;
  3819. if (!PyUnicode_FSConverter(name, &name_bytes))
  3820. return NULL;
  3821. assert(PyBytes_Check(name_bytes));
  3822. nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
  3823. Py_DECREF(name_bytes);
  3824. if (nid == 0) {
  3825. PyErr_Format(PyExc_ValueError,
  3826. "unknown elliptic curve name %R", name);
  3827. return NULL;
  3828. }
  3829. #if OPENSSL_VERSION_MAJOR < 3
  3830. EC_KEY *key = EC_KEY_new_by_curve_name(nid);
  3831. if (key == NULL) {
  3832. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3833. return NULL;
  3834. }
  3835. SSL_CTX_set_tmp_ecdh(self->ctx, key);
  3836. EC_KEY_free(key);
  3837. #else
  3838. if (!SSL_CTX_set1_groups(self->ctx, &nid, 1)) {
  3839. _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
  3840. return NULL;
  3841. }
  3842. #endif
  3843. Py_RETURN_NONE;
  3844. }
  3845. static int
  3846. _servername_callback(SSL *s, int *al, void *args)
  3847. {
  3848. int ret;
  3849. PySSLContext *sslctx = (PySSLContext *) args;
  3850. PySSLSocket *ssl;
  3851. PyObject *result;
  3852. /* The high-level ssl.SSLSocket object */
  3853. PyObject *ssl_socket;
  3854. const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
  3855. PyGILState_STATE gstate = PyGILState_Ensure();
  3856. if (sslctx->set_sni_cb == NULL) {
  3857. /* remove race condition in this the call back while if removing the
  3858. * callback is in progress */
  3859. PyGILState_Release(gstate);
  3860. return SSL_TLSEXT_ERR_OK;
  3861. }
  3862. ssl = SSL_get_app_data(s);
  3863. assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
  3864. /* The servername callback expects an argument that represents the current
  3865. * SSL connection and that has a .context attribute that can be changed to
  3866. * identify the requested hostname. Since the official API is the Python
  3867. * level API we want to pass the callback a Python level object rather than
  3868. * a _ssl.SSLSocket instance. If there's an "owner" (typically an
  3869. * SSLObject) that will be passed. Otherwise if there's a socket then that
  3870. * will be passed. If both do not exist only then the C-level object is
  3871. * passed. */
  3872. if (ssl->owner)
  3873. ssl_socket = PyWeakref_GetObject(ssl->owner);
  3874. else if (ssl->Socket)
  3875. ssl_socket = PyWeakref_GetObject(ssl->Socket);
  3876. else
  3877. ssl_socket = (PyObject *) ssl;
  3878. Py_INCREF(ssl_socket);
  3879. if (ssl_socket == Py_None)
  3880. goto error;
  3881. if (servername == NULL) {
  3882. result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
  3883. Py_None, sslctx, NULL);
  3884. }
  3885. else {
  3886. PyObject *servername_bytes;
  3887. PyObject *servername_str;
  3888. servername_bytes = PyBytes_FromString(servername);
  3889. if (servername_bytes == NULL) {
  3890. PyErr_WriteUnraisable((PyObject *) sslctx);
  3891. goto error;
  3892. }
  3893. /* server_hostname was encoded to an A-label by our caller; put it
  3894. * back into a str object, but still as an A-label (bpo-28414)
  3895. */
  3896. servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
  3897. if (servername_str == NULL) {
  3898. PyErr_WriteUnraisable(servername_bytes);
  3899. Py_DECREF(servername_bytes);
  3900. goto error;
  3901. }
  3902. Py_DECREF(servername_bytes);
  3903. result = PyObject_CallFunctionObjArgs(
  3904. sslctx->set_sni_cb, ssl_socket, servername_str,
  3905. sslctx, NULL);
  3906. Py_DECREF(servername_str);
  3907. }
  3908. Py_DECREF(ssl_socket);
  3909. if (result == NULL) {
  3910. PyErr_WriteUnraisable(sslctx->set_sni_cb);
  3911. *al = SSL_AD_HANDSHAKE_FAILURE;
  3912. ret = SSL_TLSEXT_ERR_ALERT_FATAL;
  3913. }
  3914. else {
  3915. /* Result may be None, a SSLContext or an integer
  3916. * None and SSLContext are OK, integer or other values are an error.
  3917. */
  3918. if (result == Py_None) {
  3919. ret = SSL_TLSEXT_ERR_OK;
  3920. } else {
  3921. *al = (int) PyLong_AsLong(result);
  3922. if (PyErr_Occurred()) {
  3923. PyErr_WriteUnraisable(result);
  3924. *al = SSL_AD_INTERNAL_ERROR;
  3925. }
  3926. ret = SSL_TLSEXT_ERR_ALERT_FATAL;
  3927. }
  3928. Py_DECREF(result);
  3929. }
  3930. PyGILState_Release(gstate);
  3931. return ret;
  3932. error:
  3933. Py_DECREF(ssl_socket);
  3934. *al = SSL_AD_INTERNAL_ERROR;
  3935. ret = SSL_TLSEXT_ERR_ALERT_FATAL;
  3936. PyGILState_Release(gstate);
  3937. return ret;
  3938. }
  3939. static PyObject *
  3940. get_sni_callback(PySSLContext *self, void *c)
  3941. {
  3942. PyObject *cb = self->set_sni_cb;
  3943. if (cb == NULL) {
  3944. Py_RETURN_NONE;
  3945. }
  3946. return Py_NewRef(cb);
  3947. }
  3948. static int
  3949. set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
  3950. {
  3951. if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
  3952. PyErr_SetString(PyExc_ValueError,
  3953. "sni_callback cannot be set on TLS_CLIENT context");
  3954. return -1;
  3955. }
  3956. Py_CLEAR(self->set_sni_cb);
  3957. if (arg == Py_None) {
  3958. SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
  3959. }
  3960. else {
  3961. if (!PyCallable_Check(arg)) {
  3962. SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
  3963. PyErr_SetString(PyExc_TypeError,
  3964. "not a callable object");
  3965. return -1;
  3966. }
  3967. self->set_sni_cb = Py_NewRef(arg);
  3968. SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
  3969. SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
  3970. }
  3971. return 0;
  3972. }
  3973. #if OPENSSL_VERSION_NUMBER < 0x30300000L
  3974. static X509_OBJECT *x509_object_dup(const X509_OBJECT *obj)
  3975. {
  3976. int ok;
  3977. X509_OBJECT *ret = X509_OBJECT_new();
  3978. if (ret == NULL) {
  3979. return NULL;
  3980. }
  3981. switch (X509_OBJECT_get_type(obj)) {
  3982. case X509_LU_X509:
  3983. ok = X509_OBJECT_set1_X509(ret, X509_OBJECT_get0_X509(obj));
  3984. break;
  3985. case X509_LU_CRL:
  3986. /* X509_OBJECT_get0_X509_CRL was not const-correct prior to 3.0.*/
  3987. ok = X509_OBJECT_set1_X509_CRL(
  3988. ret, X509_OBJECT_get0_X509_CRL((X509_OBJECT *)obj));
  3989. break;
  3990. default:
  3991. /* We cannot duplicate unrecognized types in a polyfill, but it is
  3992. * safe to leave an empty object. The caller will ignore it. */
  3993. ok = 1;
  3994. break;
  3995. }
  3996. if (!ok) {
  3997. X509_OBJECT_free(ret);
  3998. return NULL;
  3999. }
  4000. return ret;
  4001. }
  4002. static STACK_OF(X509_OBJECT) *
  4003. X509_STORE_get1_objects(X509_STORE *store)
  4004. {
  4005. STACK_OF(X509_OBJECT) *ret;
  4006. if (!X509_STORE_lock(store)) {
  4007. return NULL;
  4008. }
  4009. ret = sk_X509_OBJECT_deep_copy(X509_STORE_get0_objects(store),
  4010. x509_object_dup, X509_OBJECT_free);
  4011. X509_STORE_unlock(store);
  4012. return ret;
  4013. }
  4014. #endif
  4015. PyDoc_STRVAR(PySSLContext_sni_callback_doc,
  4016. "Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
  4017. \n\
  4018. If the argument is None then the callback is disabled. The method is called\n\
  4019. with the SSLSocket, the server name as a string, and the SSLContext object.\n\
  4020. See RFC 6066 for details of the SNI extension.");
  4021. /*[clinic input]
  4022. _ssl._SSLContext.cert_store_stats
  4023. Returns quantities of loaded X.509 certificates.
  4024. X.509 certificates with a CA extension and certificate revocation lists
  4025. inside the context's cert store.
  4026. NOTE: Certificates in a capath directory aren't loaded unless they have
  4027. been used at least once.
  4028. [clinic start generated code]*/
  4029. static PyObject *
  4030. _ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
  4031. /*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
  4032. {
  4033. X509_STORE *store;
  4034. STACK_OF(X509_OBJECT) *objs;
  4035. X509_OBJECT *obj;
  4036. int x509 = 0, crl = 0, ca = 0, i;
  4037. store = SSL_CTX_get_cert_store(self->ctx);
  4038. objs = X509_STORE_get1_objects(store);
  4039. if (objs == NULL) {
  4040. PyErr_SetString(PyExc_MemoryError, "failed to query cert store");
  4041. return NULL;
  4042. }
  4043. for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  4044. obj = sk_X509_OBJECT_value(objs, i);
  4045. switch (X509_OBJECT_get_type(obj)) {
  4046. case X509_LU_X509:
  4047. x509++;
  4048. if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
  4049. ca++;
  4050. }
  4051. break;
  4052. case X509_LU_CRL:
  4053. crl++;
  4054. break;
  4055. default:
  4056. /* Ignore unrecognized types. */
  4057. break;
  4058. }
  4059. }
  4060. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  4061. return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
  4062. "x509_ca", ca);
  4063. }
  4064. /*[clinic input]
  4065. _ssl._SSLContext.get_ca_certs
  4066. binary_form: bool = False
  4067. Returns a list of dicts with information of loaded CA certs.
  4068. If the optional argument is True, returns a DER-encoded copy of the CA
  4069. certificate.
  4070. NOTE: Certificates in a capath directory aren't loaded unless they have
  4071. been used at least once.
  4072. [clinic start generated code]*/
  4073. static PyObject *
  4074. _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
  4075. /*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
  4076. {
  4077. X509_STORE *store;
  4078. STACK_OF(X509_OBJECT) *objs;
  4079. PyObject *ci = NULL, *rlist = NULL;
  4080. int i;
  4081. if ((rlist = PyList_New(0)) == NULL) {
  4082. return NULL;
  4083. }
  4084. store = SSL_CTX_get_cert_store(self->ctx);
  4085. objs = X509_STORE_get1_objects(store);
  4086. if (objs == NULL) {
  4087. PyErr_SetString(PyExc_MemoryError, "failed to query cert store");
  4088. goto error;
  4089. }
  4090. for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
  4091. X509_OBJECT *obj;
  4092. X509 *cert;
  4093. obj = sk_X509_OBJECT_value(objs, i);
  4094. if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
  4095. /* not a x509 cert */
  4096. continue;
  4097. }
  4098. /* CA for any purpose */
  4099. cert = X509_OBJECT_get0_X509(obj);
  4100. if (!X509_check_ca(cert)) {
  4101. continue;
  4102. }
  4103. if (binary_form) {
  4104. ci = _certificate_to_der(get_state_ctx(self), cert);
  4105. } else {
  4106. ci = _decode_certificate(get_state_ctx(self), cert);
  4107. }
  4108. if (ci == NULL) {
  4109. goto error;
  4110. }
  4111. if (PyList_Append(rlist, ci) == -1) {
  4112. goto error;
  4113. }
  4114. Py_CLEAR(ci);
  4115. }
  4116. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  4117. return rlist;
  4118. error:
  4119. sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
  4120. Py_XDECREF(ci);
  4121. Py_XDECREF(rlist);
  4122. return NULL;
  4123. }
  4124. static PyGetSetDef context_getsetlist[] = {
  4125. {"check_hostname", (getter) get_check_hostname,
  4126. (setter) set_check_hostname, NULL},
  4127. {"_host_flags", (getter) get_host_flags,
  4128. (setter) set_host_flags, NULL},
  4129. {"minimum_version", (getter) get_minimum_version,
  4130. (setter) set_minimum_version, NULL},
  4131. {"maximum_version", (getter) get_maximum_version,
  4132. (setter) set_maximum_version, NULL},
  4133. {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
  4134. (setter) _PySSLContext_set_keylog_filename, NULL},
  4135. {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
  4136. (setter) _PySSLContext_set_msg_callback, NULL},
  4137. {"sni_callback", (getter) get_sni_callback,
  4138. (setter) set_sni_callback, PySSLContext_sni_callback_doc},
  4139. #ifdef TLS1_3_VERSION
  4140. {"num_tickets", (getter) get_num_tickets,
  4141. (setter) set_num_tickets, PySSLContext_num_tickets_doc},
  4142. #endif
  4143. {"options", (getter) get_options,
  4144. (setter) set_options, NULL},
  4145. {"post_handshake_auth", (getter) get_post_handshake_auth,
  4146. #ifdef TLS1_3_VERSION
  4147. (setter) set_post_handshake_auth,
  4148. #else
  4149. NULL,
  4150. #endif
  4151. NULL},
  4152. {"protocol", (getter) get_protocol,
  4153. NULL, NULL},
  4154. {"verify_flags", (getter) get_verify_flags,
  4155. (setter) set_verify_flags, NULL},
  4156. {"verify_mode", (getter) get_verify_mode,
  4157. (setter) set_verify_mode, NULL},
  4158. {"security_level", (getter) get_security_level,
  4159. NULL, PySSLContext_security_level_doc},
  4160. {NULL}, /* sentinel */
  4161. };
  4162. static struct PyMethodDef context_methods[] = {
  4163. _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
  4164. _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
  4165. _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
  4166. _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
  4167. _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
  4168. _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
  4169. _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
  4170. _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
  4171. _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
  4172. _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
  4173. _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
  4174. _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
  4175. _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
  4176. {NULL, NULL} /* sentinel */
  4177. };
  4178. static PyType_Slot PySSLContext_slots[] = {
  4179. {Py_tp_methods, context_methods},
  4180. {Py_tp_getset, context_getsetlist},
  4181. {Py_tp_new, _ssl__SSLContext},
  4182. {Py_tp_dealloc, context_dealloc},
  4183. {Py_tp_traverse, context_traverse},
  4184. {Py_tp_clear, context_clear},
  4185. {0, 0},
  4186. };
  4187. static PyType_Spec PySSLContext_spec = {
  4188. .name = "_ssl._SSLContext",
  4189. .basicsize = sizeof(PySSLContext),
  4190. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  4191. Py_TPFLAGS_IMMUTABLETYPE),
  4192. .slots = PySSLContext_slots,
  4193. };
  4194. /*
  4195. * MemoryBIO objects
  4196. */
  4197. /*[clinic input]
  4198. @classmethod
  4199. _ssl.MemoryBIO.__new__
  4200. [clinic start generated code]*/
  4201. static PyObject *
  4202. _ssl_MemoryBIO_impl(PyTypeObject *type)
  4203. /*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
  4204. {
  4205. BIO *bio;
  4206. PySSLMemoryBIO *self;
  4207. bio = BIO_new(BIO_s_mem());
  4208. if (bio == NULL) {
  4209. PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
  4210. return NULL;
  4211. }
  4212. /* Since our BIO is non-blocking an empty read() does not indicate EOF,
  4213. * just that no data is currently available. The SSL routines should retry
  4214. * the read, which we can achieve by calling BIO_set_retry_read(). */
  4215. BIO_set_retry_read(bio);
  4216. BIO_set_mem_eof_return(bio, -1);
  4217. assert(type != NULL && type->tp_alloc != NULL);
  4218. self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
  4219. if (self == NULL) {
  4220. BIO_free(bio);
  4221. return NULL;
  4222. }
  4223. self->bio = bio;
  4224. self->eof_written = 0;
  4225. return (PyObject *) self;
  4226. }
  4227. static int
  4228. memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
  4229. {
  4230. Py_VISIT(Py_TYPE(self));
  4231. return 0;
  4232. }
  4233. static void
  4234. memory_bio_dealloc(PySSLMemoryBIO *self)
  4235. {
  4236. PyTypeObject *tp = Py_TYPE(self);
  4237. PyObject_GC_UnTrack(self);
  4238. BIO_free(self->bio);
  4239. Py_TYPE(self)->tp_free(self);
  4240. Py_DECREF(tp);
  4241. }
  4242. static PyObject *
  4243. memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
  4244. {
  4245. return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
  4246. }
  4247. PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
  4248. "The number of bytes pending in the memory BIO.");
  4249. static PyObject *
  4250. memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
  4251. {
  4252. return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
  4253. && self->eof_written);
  4254. }
  4255. PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
  4256. "Whether the memory BIO is at EOF.");
  4257. /*[clinic input]
  4258. _ssl.MemoryBIO.read
  4259. size as len: int = -1
  4260. /
  4261. Read up to size bytes from the memory BIO.
  4262. If size is not specified, read the entire buffer.
  4263. If the return value is an empty bytes instance, this means either
  4264. EOF or that no data is available. Use the "eof" property to
  4265. distinguish between the two.
  4266. [clinic start generated code]*/
  4267. static PyObject *
  4268. _ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
  4269. /*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
  4270. {
  4271. int avail, nbytes;
  4272. PyObject *result;
  4273. avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
  4274. if ((len < 0) || (len > avail))
  4275. len = avail;
  4276. result = PyBytes_FromStringAndSize(NULL, len);
  4277. if ((result == NULL) || (len == 0))
  4278. return result;
  4279. nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
  4280. if (nbytes < 0) {
  4281. _sslmodulestate *state = get_state_mbio(self);
  4282. Py_DECREF(result);
  4283. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  4284. return NULL;
  4285. }
  4286. /* There should never be any short reads but check anyway. */
  4287. if (nbytes < len) {
  4288. _PyBytes_Resize(&result, nbytes);
  4289. }
  4290. return result;
  4291. }
  4292. /*[clinic input]
  4293. _ssl.MemoryBIO.write
  4294. b: Py_buffer
  4295. /
  4296. Writes the bytes b into the memory BIO.
  4297. Returns the number of bytes written.
  4298. [clinic start generated code]*/
  4299. static PyObject *
  4300. _ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
  4301. /*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
  4302. {
  4303. int nbytes;
  4304. if (b->len > INT_MAX) {
  4305. PyErr_Format(PyExc_OverflowError,
  4306. "string longer than %d bytes", INT_MAX);
  4307. return NULL;
  4308. }
  4309. if (self->eof_written) {
  4310. PyObject *module = PyType_GetModule(Py_TYPE(self));
  4311. if (module == NULL)
  4312. return NULL;
  4313. PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
  4314. "cannot write() after write_eof()");
  4315. return NULL;
  4316. }
  4317. nbytes = BIO_write(self->bio, b->buf, (int)b->len);
  4318. if (nbytes < 0) {
  4319. _sslmodulestate *state = get_state_mbio(self);
  4320. _setSSLError(state, NULL, 0, __FILE__, __LINE__);
  4321. return NULL;
  4322. }
  4323. return PyLong_FromLong(nbytes);
  4324. }
  4325. /*[clinic input]
  4326. _ssl.MemoryBIO.write_eof
  4327. Write an EOF marker to the memory BIO.
  4328. When all data has been read, the "eof" property will be True.
  4329. [clinic start generated code]*/
  4330. static PyObject *
  4331. _ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
  4332. /*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
  4333. {
  4334. self->eof_written = 1;
  4335. /* After an EOF is written, a zero return from read() should be a real EOF
  4336. * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
  4337. BIO_clear_retry_flags(self->bio);
  4338. BIO_set_mem_eof_return(self->bio, 0);
  4339. Py_RETURN_NONE;
  4340. }
  4341. static PyGetSetDef memory_bio_getsetlist[] = {
  4342. {"pending", (getter) memory_bio_get_pending, NULL,
  4343. PySSL_memory_bio_pending_doc},
  4344. {"eof", (getter) memory_bio_get_eof, NULL,
  4345. PySSL_memory_bio_eof_doc},
  4346. {NULL}, /* sentinel */
  4347. };
  4348. static struct PyMethodDef memory_bio_methods[] = {
  4349. _SSL_MEMORYBIO_READ_METHODDEF
  4350. _SSL_MEMORYBIO_WRITE_METHODDEF
  4351. _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
  4352. {NULL, NULL} /* sentinel */
  4353. };
  4354. static PyType_Slot PySSLMemoryBIO_slots[] = {
  4355. {Py_tp_methods, memory_bio_methods},
  4356. {Py_tp_getset, memory_bio_getsetlist},
  4357. {Py_tp_new, _ssl_MemoryBIO},
  4358. {Py_tp_dealloc, memory_bio_dealloc},
  4359. {Py_tp_traverse, memory_bio_traverse},
  4360. {0, 0},
  4361. };
  4362. static PyType_Spec PySSLMemoryBIO_spec = {
  4363. .name = "_ssl.MemoryBIO",
  4364. .basicsize = sizeof(PySSLMemoryBIO),
  4365. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
  4366. Py_TPFLAGS_HAVE_GC),
  4367. .slots = PySSLMemoryBIO_slots,
  4368. };
  4369. /*
  4370. * SSL Session object
  4371. */
  4372. static void
  4373. PySSLSession_dealloc(PySSLSession *self)
  4374. {
  4375. PyTypeObject *tp = Py_TYPE(self);
  4376. /* bpo-31095: UnTrack is needed before calling any callbacks */
  4377. PyObject_GC_UnTrack(self);
  4378. Py_XDECREF(self->ctx);
  4379. if (self->session != NULL) {
  4380. SSL_SESSION_free(self->session);
  4381. }
  4382. PyObject_GC_Del(self);
  4383. Py_DECREF(tp);
  4384. }
  4385. static PyObject *
  4386. PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
  4387. {
  4388. if (left == NULL || right == NULL) {
  4389. PyErr_BadInternalCall();
  4390. return NULL;
  4391. }
  4392. int result;
  4393. PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
  4394. if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
  4395. Py_RETURN_NOTIMPLEMENTED;
  4396. }
  4397. if (left == right) {
  4398. result = 0;
  4399. } else {
  4400. const unsigned char *left_id, *right_id;
  4401. unsigned int left_len, right_len;
  4402. left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
  4403. &left_len);
  4404. right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
  4405. &right_len);
  4406. if (left_len == right_len) {
  4407. result = memcmp(left_id, right_id, left_len);
  4408. } else {
  4409. result = 1;
  4410. }
  4411. }
  4412. switch (op) {
  4413. case Py_EQ:
  4414. if (result == 0) {
  4415. Py_RETURN_TRUE;
  4416. } else {
  4417. Py_RETURN_FALSE;
  4418. }
  4419. break;
  4420. case Py_NE:
  4421. if (result != 0) {
  4422. Py_RETURN_TRUE;
  4423. } else {
  4424. Py_RETURN_FALSE;
  4425. }
  4426. break;
  4427. case Py_LT:
  4428. case Py_LE:
  4429. case Py_GT:
  4430. case Py_GE:
  4431. Py_RETURN_NOTIMPLEMENTED;
  4432. break;
  4433. default:
  4434. PyErr_BadArgument();
  4435. return NULL;
  4436. }
  4437. }
  4438. static int
  4439. PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
  4440. {
  4441. Py_VISIT(self->ctx);
  4442. Py_VISIT(Py_TYPE(self));
  4443. return 0;
  4444. }
  4445. static int
  4446. PySSLSession_clear(PySSLSession *self)
  4447. {
  4448. Py_CLEAR(self->ctx);
  4449. return 0;
  4450. }
  4451. static PyObject *
  4452. PySSLSession_get_time(PySSLSession *self, void *closure) {
  4453. return PyLong_FromLong(SSL_SESSION_get_time(self->session));
  4454. }
  4455. PyDoc_STRVAR(PySSLSession_get_time_doc,
  4456. "Session creation time (seconds since epoch).");
  4457. static PyObject *
  4458. PySSLSession_get_timeout(PySSLSession *self, void *closure) {
  4459. return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
  4460. }
  4461. PyDoc_STRVAR(PySSLSession_get_timeout_doc,
  4462. "Session timeout (delta in seconds).");
  4463. static PyObject *
  4464. PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
  4465. unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
  4466. return PyLong_FromUnsignedLong(hint);
  4467. }
  4468. PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
  4469. "Ticket life time hint.");
  4470. static PyObject *
  4471. PySSLSession_get_session_id(PySSLSession *self, void *closure) {
  4472. const unsigned char *id;
  4473. unsigned int len;
  4474. id = SSL_SESSION_get_id(self->session, &len);
  4475. return PyBytes_FromStringAndSize((const char *)id, len);
  4476. }
  4477. PyDoc_STRVAR(PySSLSession_get_session_id_doc,
  4478. "Session id");
  4479. static PyObject *
  4480. PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
  4481. if (SSL_SESSION_has_ticket(self->session)) {
  4482. Py_RETURN_TRUE;
  4483. } else {
  4484. Py_RETURN_FALSE;
  4485. }
  4486. }
  4487. PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
  4488. "Does the session contain a ticket?");
  4489. static PyGetSetDef PySSLSession_getsetlist[] = {
  4490. {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
  4491. PySSLSession_get_has_ticket_doc},
  4492. {"id", (getter) PySSLSession_get_session_id, NULL,
  4493. PySSLSession_get_session_id_doc},
  4494. {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
  4495. NULL, PySSLSession_get_ticket_lifetime_hint_doc},
  4496. {"time", (getter) PySSLSession_get_time, NULL,
  4497. PySSLSession_get_time_doc},
  4498. {"timeout", (getter) PySSLSession_get_timeout, NULL,
  4499. PySSLSession_get_timeout_doc},
  4500. {NULL}, /* sentinel */
  4501. };
  4502. static PyType_Slot PySSLSession_slots[] = {
  4503. {Py_tp_getset,PySSLSession_getsetlist},
  4504. {Py_tp_richcompare, PySSLSession_richcompare},
  4505. {Py_tp_dealloc, PySSLSession_dealloc},
  4506. {Py_tp_traverse, PySSLSession_traverse},
  4507. {Py_tp_clear, PySSLSession_clear},
  4508. {0, 0},
  4509. };
  4510. static PyType_Spec PySSLSession_spec = {
  4511. .name = "_ssl.SSLSession",
  4512. .basicsize = sizeof(PySSLSession),
  4513. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  4514. Py_TPFLAGS_IMMUTABLETYPE |
  4515. Py_TPFLAGS_DISALLOW_INSTANTIATION),
  4516. .slots = PySSLSession_slots,
  4517. };
  4518. /* helper routines for seeding the SSL PRNG */
  4519. /*[clinic input]
  4520. _ssl.RAND_add
  4521. string as view: Py_buffer(accept={str, buffer})
  4522. entropy: double
  4523. /
  4524. Mix string into the OpenSSL PRNG state.
  4525. entropy (a float) is a lower bound on the entropy contained in
  4526. string. See RFC 4086.
  4527. [clinic start generated code]*/
  4528. static PyObject *
  4529. _ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
  4530. /*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
  4531. {
  4532. const char *buf;
  4533. Py_ssize_t len, written;
  4534. buf = (const char *)view->buf;
  4535. len = view->len;
  4536. do {
  4537. written = Py_MIN(len, INT_MAX);
  4538. RAND_add(buf, (int)written, entropy);
  4539. buf += written;
  4540. len -= written;
  4541. } while (len);
  4542. Py_RETURN_NONE;
  4543. }
  4544. static PyObject *
  4545. PySSL_RAND(PyObject *module, int len, int pseudo)
  4546. {
  4547. int ok;
  4548. PyObject *bytes;
  4549. unsigned long err;
  4550. const char *errstr;
  4551. PyObject *v;
  4552. if (len < 0) {
  4553. PyErr_SetString(PyExc_ValueError, "num must be positive");
  4554. return NULL;
  4555. }
  4556. bytes = PyBytes_FromStringAndSize(NULL, len);
  4557. if (bytes == NULL)
  4558. return NULL;
  4559. if (pseudo) {
  4560. ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
  4561. if (ok == 0 || ok == 1)
  4562. return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
  4563. }
  4564. else {
  4565. ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
  4566. if (ok == 1)
  4567. return bytes;
  4568. }
  4569. Py_DECREF(bytes);
  4570. err = ERR_get_error();
  4571. errstr = ERR_reason_error_string(err);
  4572. v = Py_BuildValue("(ks)", err, errstr);
  4573. if (v != NULL) {
  4574. PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
  4575. Py_DECREF(v);
  4576. }
  4577. return NULL;
  4578. }
  4579. /*[clinic input]
  4580. _ssl.RAND_bytes
  4581. n: int
  4582. /
  4583. Generate n cryptographically strong pseudo-random bytes.
  4584. [clinic start generated code]*/
  4585. static PyObject *
  4586. _ssl_RAND_bytes_impl(PyObject *module, int n)
  4587. /*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
  4588. {
  4589. return PySSL_RAND(module, n, 0);
  4590. }
  4591. /*[clinic input]
  4592. _ssl.RAND_status
  4593. Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
  4594. It is necessary to seed the PRNG with RAND_add() on some platforms before
  4595. using the ssl() function.
  4596. [clinic start generated code]*/
  4597. static PyObject *
  4598. _ssl_RAND_status_impl(PyObject *module)
  4599. /*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
  4600. {
  4601. return PyBool_FromLong(RAND_status());
  4602. }
  4603. /*[clinic input]
  4604. _ssl.get_default_verify_paths
  4605. Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
  4606. The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
  4607. [clinic start generated code]*/
  4608. static PyObject *
  4609. _ssl_get_default_verify_paths_impl(PyObject *module)
  4610. /*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
  4611. {
  4612. PyObject *ofile_env = NULL;
  4613. PyObject *ofile = NULL;
  4614. PyObject *odir_env = NULL;
  4615. PyObject *odir = NULL;
  4616. #define CONVERT(info, target) { \
  4617. const char *tmp = (info); \
  4618. target = NULL; \
  4619. if (!tmp) { target = Py_NewRef(Py_None); } \
  4620. else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
  4621. target = PyBytes_FromString(tmp); } \
  4622. if (!target) goto error; \
  4623. }
  4624. CONVERT(X509_get_default_cert_file_env(), ofile_env);
  4625. CONVERT(X509_get_default_cert_file(), ofile);
  4626. CONVERT(X509_get_default_cert_dir_env(), odir_env);
  4627. CONVERT(X509_get_default_cert_dir(), odir);
  4628. #undef CONVERT
  4629. return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
  4630. error:
  4631. Py_XDECREF(ofile_env);
  4632. Py_XDECREF(ofile);
  4633. Py_XDECREF(odir_env);
  4634. Py_XDECREF(odir);
  4635. return NULL;
  4636. }
  4637. static PyObject*
  4638. asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
  4639. {
  4640. int nid;
  4641. const char *ln, *sn;
  4642. nid = OBJ_obj2nid(obj);
  4643. if (nid == NID_undef) {
  4644. PyErr_Format(PyExc_ValueError, "Unknown object");
  4645. return NULL;
  4646. }
  4647. sn = OBJ_nid2sn(nid);
  4648. ln = OBJ_nid2ln(nid);
  4649. return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
  4650. }
  4651. /*[clinic input]
  4652. _ssl.txt2obj
  4653. txt: str
  4654. name: bool = False
  4655. Lookup NID, short name, long name and OID of an ASN1_OBJECT.
  4656. By default objects are looked up by OID. With name=True short and
  4657. long name are also matched.
  4658. [clinic start generated code]*/
  4659. static PyObject *
  4660. _ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
  4661. /*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
  4662. {
  4663. PyObject *result = NULL;
  4664. ASN1_OBJECT *obj;
  4665. obj = OBJ_txt2obj(txt, name ? 0 : 1);
  4666. if (obj == NULL) {
  4667. PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
  4668. return NULL;
  4669. }
  4670. result = asn1obj2py(get_ssl_state(module), obj);
  4671. ASN1_OBJECT_free(obj);
  4672. return result;
  4673. }
  4674. /*[clinic input]
  4675. _ssl.nid2obj
  4676. nid: int
  4677. /
  4678. Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
  4679. [clinic start generated code]*/
  4680. static PyObject *
  4681. _ssl_nid2obj_impl(PyObject *module, int nid)
  4682. /*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
  4683. {
  4684. PyObject *result = NULL;
  4685. ASN1_OBJECT *obj;
  4686. if (nid < NID_undef) {
  4687. PyErr_SetString(PyExc_ValueError, "NID must be positive.");
  4688. return NULL;
  4689. }
  4690. obj = OBJ_nid2obj(nid);
  4691. if (obj == NULL) {
  4692. PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
  4693. return NULL;
  4694. }
  4695. result = asn1obj2py(get_ssl_state(module), obj);
  4696. ASN1_OBJECT_free(obj);
  4697. return result;
  4698. }
  4699. #ifdef _MSC_VER
  4700. static PyObject*
  4701. certEncodingType(DWORD encodingType)
  4702. {
  4703. static PyObject *x509_asn = NULL;
  4704. static PyObject *pkcs_7_asn = NULL;
  4705. if (x509_asn == NULL) {
  4706. x509_asn = PyUnicode_InternFromString("x509_asn");
  4707. if (x509_asn == NULL)
  4708. return NULL;
  4709. }
  4710. if (pkcs_7_asn == NULL) {
  4711. pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
  4712. if (pkcs_7_asn == NULL)
  4713. return NULL;
  4714. }
  4715. switch(encodingType) {
  4716. case X509_ASN_ENCODING:
  4717. return Py_NewRef(x509_asn);
  4718. case PKCS_7_ASN_ENCODING:
  4719. return Py_NewRef(pkcs_7_asn);
  4720. default:
  4721. return PyLong_FromLong(encodingType);
  4722. }
  4723. }
  4724. static PyObject*
  4725. parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
  4726. {
  4727. CERT_ENHKEY_USAGE *usage;
  4728. DWORD size, error, i;
  4729. PyObject *retval;
  4730. if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
  4731. error = GetLastError();
  4732. if (error == CRYPT_E_NOT_FOUND) {
  4733. Py_RETURN_TRUE;
  4734. }
  4735. return PyErr_SetFromWindowsErr(error);
  4736. }
  4737. usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
  4738. if (usage == NULL) {
  4739. return PyErr_NoMemory();
  4740. }
  4741. /* Now get the actual enhanced usage property */
  4742. if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
  4743. PyMem_Free(usage);
  4744. error = GetLastError();
  4745. if (error == CRYPT_E_NOT_FOUND) {
  4746. Py_RETURN_TRUE;
  4747. }
  4748. return PyErr_SetFromWindowsErr(error);
  4749. }
  4750. retval = PyFrozenSet_New(NULL);
  4751. if (retval == NULL) {
  4752. goto error;
  4753. }
  4754. for (i = 0; i < usage->cUsageIdentifier; ++i) {
  4755. if (usage->rgpszUsageIdentifier[i]) {
  4756. PyObject *oid;
  4757. int err;
  4758. oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
  4759. if (oid == NULL) {
  4760. Py_CLEAR(retval);
  4761. goto error;
  4762. }
  4763. err = PySet_Add(retval, oid);
  4764. Py_DECREF(oid);
  4765. if (err == -1) {
  4766. Py_CLEAR(retval);
  4767. goto error;
  4768. }
  4769. }
  4770. }
  4771. error:
  4772. PyMem_Free(usage);
  4773. return retval;
  4774. }
  4775. static HCERTSTORE
  4776. ssl_collect_certificates(const char *store_name)
  4777. {
  4778. /* this function collects the system certificate stores listed in
  4779. * system_stores into a collection certificate store for being
  4780. * enumerated. The store must be readable to be added to the
  4781. * store collection.
  4782. */
  4783. HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
  4784. static DWORD system_stores[] = {
  4785. CERT_SYSTEM_STORE_LOCAL_MACHINE,
  4786. CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
  4787. CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
  4788. CERT_SYSTEM_STORE_CURRENT_USER,
  4789. CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
  4790. CERT_SYSTEM_STORE_SERVICES,
  4791. CERT_SYSTEM_STORE_USERS};
  4792. size_t i, storesAdded;
  4793. BOOL result;
  4794. hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
  4795. (HCRYPTPROV)NULL, 0, NULL);
  4796. if (!hCollectionStore) {
  4797. return NULL;
  4798. }
  4799. storesAdded = 0;
  4800. for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
  4801. hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
  4802. (HCRYPTPROV)NULL,
  4803. CERT_STORE_READONLY_FLAG |
  4804. system_stores[i], store_name);
  4805. if (hSystemStore) {
  4806. result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
  4807. CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
  4808. if (result) {
  4809. ++storesAdded;
  4810. }
  4811. CertCloseStore(hSystemStore, 0); /* flag must be 0 */
  4812. }
  4813. }
  4814. if (storesAdded == 0) {
  4815. CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
  4816. return NULL;
  4817. }
  4818. return hCollectionStore;
  4819. }
  4820. /*[clinic input]
  4821. _ssl.enum_certificates
  4822. store_name: str
  4823. Retrieve certificates from Windows' cert store.
  4824. store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
  4825. more cert storages, too. The function returns a list of (bytes,
  4826. encoding_type, trust) tuples. The encoding_type flag can be interpreted
  4827. with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
  4828. a set of OIDs or the boolean True.
  4829. [clinic start generated code]*/
  4830. static PyObject *
  4831. _ssl_enum_certificates_impl(PyObject *module, const char *store_name)
  4832. /*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
  4833. {
  4834. HCERTSTORE hCollectionStore = NULL;
  4835. PCCERT_CONTEXT pCertCtx = NULL;
  4836. PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
  4837. PyObject *result = NULL;
  4838. result = PySet_New(NULL);
  4839. if (result == NULL) {
  4840. return NULL;
  4841. }
  4842. hCollectionStore = ssl_collect_certificates(store_name);
  4843. if (hCollectionStore == NULL) {
  4844. Py_DECREF(result);
  4845. return PyErr_SetFromWindowsErr(GetLastError());
  4846. }
  4847. while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
  4848. cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
  4849. pCertCtx->cbCertEncoded);
  4850. if (!cert) {
  4851. Py_CLEAR(result);
  4852. break;
  4853. }
  4854. if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
  4855. Py_CLEAR(result);
  4856. break;
  4857. }
  4858. keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
  4859. if (keyusage == Py_True) {
  4860. Py_DECREF(keyusage);
  4861. keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
  4862. }
  4863. if (keyusage == NULL) {
  4864. Py_CLEAR(result);
  4865. break;
  4866. }
  4867. if ((tup = PyTuple_New(3)) == NULL) {
  4868. Py_CLEAR(result);
  4869. break;
  4870. }
  4871. PyTuple_SET_ITEM(tup, 0, cert);
  4872. cert = NULL;
  4873. PyTuple_SET_ITEM(tup, 1, enc);
  4874. enc = NULL;
  4875. PyTuple_SET_ITEM(tup, 2, keyusage);
  4876. keyusage = NULL;
  4877. if (PySet_Add(result, tup) == -1) {
  4878. Py_CLEAR(result);
  4879. Py_CLEAR(tup);
  4880. break;
  4881. }
  4882. Py_CLEAR(tup);
  4883. }
  4884. if (pCertCtx) {
  4885. /* loop ended with an error, need to clean up context manually */
  4886. CertFreeCertificateContext(pCertCtx);
  4887. }
  4888. /* In error cases cert, enc and tup may not be NULL */
  4889. Py_XDECREF(cert);
  4890. Py_XDECREF(enc);
  4891. Py_XDECREF(keyusage);
  4892. Py_XDECREF(tup);
  4893. /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
  4894. associated with the store, in this case our collection store and the
  4895. associated system stores. */
  4896. if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
  4897. /* This error case might shadow another exception.*/
  4898. Py_XDECREF(result);
  4899. return PyErr_SetFromWindowsErr(GetLastError());
  4900. }
  4901. /* convert set to list */
  4902. if (result == NULL) {
  4903. return NULL;
  4904. } else {
  4905. PyObject *lst = PySequence_List(result);
  4906. Py_DECREF(result);
  4907. return lst;
  4908. }
  4909. }
  4910. /*[clinic input]
  4911. _ssl.enum_crls
  4912. store_name: str
  4913. Retrieve CRLs from Windows' cert store.
  4914. store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
  4915. more cert storages, too. The function returns a list of (bytes,
  4916. encoding_type) tuples. The encoding_type flag can be interpreted with
  4917. X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
  4918. [clinic start generated code]*/
  4919. static PyObject *
  4920. _ssl_enum_crls_impl(PyObject *module, const char *store_name)
  4921. /*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
  4922. {
  4923. HCERTSTORE hCollectionStore = NULL;
  4924. PCCRL_CONTEXT pCrlCtx = NULL;
  4925. PyObject *crl = NULL, *enc = NULL, *tup = NULL;
  4926. PyObject *result = NULL;
  4927. result = PySet_New(NULL);
  4928. if (result == NULL) {
  4929. return NULL;
  4930. }
  4931. hCollectionStore = ssl_collect_certificates(store_name);
  4932. if (hCollectionStore == NULL) {
  4933. Py_DECREF(result);
  4934. return PyErr_SetFromWindowsErr(GetLastError());
  4935. }
  4936. while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
  4937. crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
  4938. pCrlCtx->cbCrlEncoded);
  4939. if (!crl) {
  4940. Py_CLEAR(result);
  4941. break;
  4942. }
  4943. if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
  4944. Py_CLEAR(result);
  4945. break;
  4946. }
  4947. if ((tup = PyTuple_New(2)) == NULL) {
  4948. Py_CLEAR(result);
  4949. break;
  4950. }
  4951. PyTuple_SET_ITEM(tup, 0, crl);
  4952. crl = NULL;
  4953. PyTuple_SET_ITEM(tup, 1, enc);
  4954. enc = NULL;
  4955. if (PySet_Add(result, tup) == -1) {
  4956. Py_CLEAR(result);
  4957. Py_CLEAR(tup);
  4958. break;
  4959. }
  4960. Py_CLEAR(tup);
  4961. }
  4962. if (pCrlCtx) {
  4963. /* loop ended with an error, need to clean up context manually */
  4964. CertFreeCRLContext(pCrlCtx);
  4965. }
  4966. /* In error cases cert, enc and tup may not be NULL */
  4967. Py_XDECREF(crl);
  4968. Py_XDECREF(enc);
  4969. Py_XDECREF(tup);
  4970. /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
  4971. associated with the store, in this case our collection store and the
  4972. associated system stores. */
  4973. if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
  4974. /* This error case might shadow another exception.*/
  4975. Py_XDECREF(result);
  4976. return PyErr_SetFromWindowsErr(GetLastError());
  4977. }
  4978. /* convert set to list */
  4979. if (result == NULL) {
  4980. return NULL;
  4981. } else {
  4982. PyObject *lst = PySequence_List(result);
  4983. Py_DECREF(result);
  4984. return lst;
  4985. }
  4986. }
  4987. #endif /* _MSC_VER */
  4988. /* List of functions exported by this module. */
  4989. static PyMethodDef PySSL_methods[] = {
  4990. _SSL__TEST_DECODE_CERT_METHODDEF
  4991. _SSL_RAND_ADD_METHODDEF
  4992. _SSL_RAND_BYTES_METHODDEF
  4993. _SSL_RAND_STATUS_METHODDEF
  4994. _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
  4995. _SSL_ENUM_CERTIFICATES_METHODDEF
  4996. _SSL_ENUM_CRLS_METHODDEF
  4997. _SSL_TXT2OBJ_METHODDEF
  4998. _SSL_NID2OBJ_METHODDEF
  4999. {NULL, NULL} /* Sentinel */
  5000. };
  5001. PyDoc_STRVAR(module_doc,
  5002. "Implementation module for SSL socket operations. See the socket module\n\
  5003. for documentation.");
  5004. static int
  5005. sslmodule_init_exceptions(PyObject *module)
  5006. {
  5007. _sslmodulestate *state = get_ssl_state(module);
  5008. PyObject *bases = NULL;
  5009. #define add_exception(exc, name, doc, base) \
  5010. do { \
  5011. (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
  5012. if ((state) == NULL) goto error; \
  5013. if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
  5014. } while(0)
  5015. state->PySSLErrorObject = PyType_FromSpecWithBases(
  5016. &sslerror_type_spec, PyExc_OSError);
  5017. if (state->PySSLErrorObject == NULL) {
  5018. goto error;
  5019. }
  5020. if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
  5021. goto error;
  5022. }
  5023. /* ssl.CertificateError used to be a subclass of ValueError */
  5024. bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
  5025. if (bases == NULL) {
  5026. goto error;
  5027. }
  5028. add_exception(
  5029. state->PySSLCertVerificationErrorObject,
  5030. "SSLCertVerificationError",
  5031. SSLCertVerificationError_doc,
  5032. bases
  5033. );
  5034. Py_CLEAR(bases);
  5035. add_exception(
  5036. state->PySSLZeroReturnErrorObject,
  5037. "SSLZeroReturnError",
  5038. SSLZeroReturnError_doc,
  5039. state->PySSLErrorObject
  5040. );
  5041. add_exception(
  5042. state->PySSLWantWriteErrorObject,
  5043. "SSLWantWriteError",
  5044. SSLWantWriteError_doc,
  5045. state->PySSLErrorObject
  5046. );
  5047. add_exception(
  5048. state->PySSLWantReadErrorObject,
  5049. "SSLWantReadError",
  5050. SSLWantReadError_doc,
  5051. state->PySSLErrorObject
  5052. );
  5053. add_exception(
  5054. state->PySSLSyscallErrorObject,
  5055. "SSLSyscallError",
  5056. SSLSyscallError_doc,
  5057. state->PySSLErrorObject
  5058. );
  5059. add_exception(
  5060. state->PySSLEOFErrorObject,
  5061. "SSLEOFError",
  5062. SSLEOFError_doc,
  5063. state->PySSLErrorObject
  5064. );
  5065. #undef add_exception
  5066. return 0;
  5067. error:
  5068. Py_XDECREF(bases);
  5069. return -1;
  5070. }
  5071. static int
  5072. sslmodule_init_socketapi(PyObject *module)
  5073. {
  5074. _sslmodulestate *state = get_ssl_state(module);
  5075. PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
  5076. if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
  5077. return -1;
  5078. }
  5079. state->Sock_Type = (PyTypeObject*)Py_NewRef(sockmod->Sock_Type);
  5080. return 0;
  5081. }
  5082. static int
  5083. sslmodule_add_option(PyObject *m, const char *name, uint64_t value)
  5084. {
  5085. Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(value));
  5086. PyObject *obj = PyLong_FromUnsignedLongLong(value);
  5087. if (obj == NULL) {
  5088. return -1;
  5089. }
  5090. int res = PyModule_AddObjectRef(m, name, obj);
  5091. Py_DECREF(obj);
  5092. return res;
  5093. }
  5094. static int
  5095. sslmodule_init_constants(PyObject *m)
  5096. {
  5097. PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
  5098. PY_SSL_DEFAULT_CIPHER_STRING);
  5099. PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
  5100. PY_SSL_ERROR_ZERO_RETURN);
  5101. PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
  5102. PY_SSL_ERROR_WANT_READ);
  5103. PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
  5104. PY_SSL_ERROR_WANT_WRITE);
  5105. PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
  5106. PY_SSL_ERROR_WANT_X509_LOOKUP);
  5107. PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
  5108. PY_SSL_ERROR_SYSCALL);
  5109. PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
  5110. PY_SSL_ERROR_SSL);
  5111. PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
  5112. PY_SSL_ERROR_WANT_CONNECT);
  5113. /* non ssl.h errorcodes */
  5114. PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
  5115. PY_SSL_ERROR_EOF);
  5116. PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
  5117. PY_SSL_ERROR_INVALID_ERROR_CODE);
  5118. /* cert requirements */
  5119. PyModule_AddIntConstant(m, "CERT_NONE",
  5120. PY_SSL_CERT_NONE);
  5121. PyModule_AddIntConstant(m, "CERT_OPTIONAL",
  5122. PY_SSL_CERT_OPTIONAL);
  5123. PyModule_AddIntConstant(m, "CERT_REQUIRED",
  5124. PY_SSL_CERT_REQUIRED);
  5125. /* CRL verification for verification_flags */
  5126. PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
  5127. 0);
  5128. PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
  5129. X509_V_FLAG_CRL_CHECK);
  5130. PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
  5131. X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
  5132. PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
  5133. X509_V_FLAG_X509_STRICT);
  5134. PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
  5135. X509_V_FLAG_ALLOW_PROXY_CERTS);
  5136. PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
  5137. X509_V_FLAG_TRUSTED_FIRST);
  5138. #ifdef X509_V_FLAG_PARTIAL_CHAIN
  5139. PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
  5140. X509_V_FLAG_PARTIAL_CHAIN);
  5141. #endif
  5142. /* Alert Descriptions from ssl.h */
  5143. /* note RESERVED constants no longer intended for use have been removed */
  5144. /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
  5145. #define ADD_AD_CONSTANT(s) \
  5146. PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
  5147. SSL_AD_##s)
  5148. ADD_AD_CONSTANT(CLOSE_NOTIFY);
  5149. ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
  5150. ADD_AD_CONSTANT(BAD_RECORD_MAC);
  5151. ADD_AD_CONSTANT(RECORD_OVERFLOW);
  5152. ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
  5153. ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
  5154. ADD_AD_CONSTANT(BAD_CERTIFICATE);
  5155. ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
  5156. ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
  5157. ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
  5158. ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
  5159. ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
  5160. ADD_AD_CONSTANT(UNKNOWN_CA);
  5161. ADD_AD_CONSTANT(ACCESS_DENIED);
  5162. ADD_AD_CONSTANT(DECODE_ERROR);
  5163. ADD_AD_CONSTANT(DECRYPT_ERROR);
  5164. ADD_AD_CONSTANT(PROTOCOL_VERSION);
  5165. ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
  5166. ADD_AD_CONSTANT(INTERNAL_ERROR);
  5167. ADD_AD_CONSTANT(USER_CANCELLED);
  5168. ADD_AD_CONSTANT(NO_RENEGOTIATION);
  5169. /* Not all constants are in old OpenSSL versions */
  5170. #ifdef SSL_AD_UNSUPPORTED_EXTENSION
  5171. ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
  5172. #endif
  5173. #ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
  5174. ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
  5175. #endif
  5176. #ifdef SSL_AD_UNRECOGNIZED_NAME
  5177. ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
  5178. #endif
  5179. #ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
  5180. ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
  5181. #endif
  5182. #ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
  5183. ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
  5184. #endif
  5185. #ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
  5186. ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
  5187. #endif
  5188. #undef ADD_AD_CONSTANT
  5189. /* protocol versions */
  5190. #ifndef OPENSSL_NO_SSL3
  5191. PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
  5192. PY_SSL_VERSION_SSL3);
  5193. #endif
  5194. PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
  5195. PY_SSL_VERSION_TLS);
  5196. PyModule_AddIntConstant(m, "PROTOCOL_TLS",
  5197. PY_SSL_VERSION_TLS);
  5198. PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
  5199. PY_SSL_VERSION_TLS_CLIENT);
  5200. PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
  5201. PY_SSL_VERSION_TLS_SERVER);
  5202. PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
  5203. PY_SSL_VERSION_TLS1);
  5204. PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
  5205. PY_SSL_VERSION_TLS1_1);
  5206. PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
  5207. PY_SSL_VERSION_TLS1_2);
  5208. #define ADD_OPTION(NAME, VALUE) if (sslmodule_add_option(m, NAME, (VALUE)) < 0) return -1
  5209. /* protocol options */
  5210. ADD_OPTION("OP_ALL", SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
  5211. ADD_OPTION("OP_NO_SSLv2", SSL_OP_NO_SSLv2);
  5212. ADD_OPTION("OP_NO_SSLv3", SSL_OP_NO_SSLv3);
  5213. ADD_OPTION("OP_NO_TLSv1", SSL_OP_NO_TLSv1);
  5214. ADD_OPTION("OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
  5215. ADD_OPTION("OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
  5216. #ifdef SSL_OP_NO_TLSv1_3
  5217. ADD_OPTION("OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
  5218. #else
  5219. ADD_OPTION("OP_NO_TLSv1_3", 0);
  5220. #endif
  5221. ADD_OPTION("OP_CIPHER_SERVER_PREFERENCE",
  5222. SSL_OP_CIPHER_SERVER_PREFERENCE);
  5223. ADD_OPTION("OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
  5224. ADD_OPTION("OP_NO_TICKET", SSL_OP_NO_TICKET);
  5225. ADD_OPTION("OP_LEGACY_SERVER_CONNECT",
  5226. SSL_OP_LEGACY_SERVER_CONNECT);
  5227. #ifdef SSL_OP_SINGLE_ECDH_USE
  5228. ADD_OPTION("OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
  5229. #endif
  5230. #ifdef SSL_OP_NO_COMPRESSION
  5231. ADD_OPTION("OP_NO_COMPRESSION",
  5232. SSL_OP_NO_COMPRESSION);
  5233. #endif
  5234. #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
  5235. ADD_OPTION("OP_ENABLE_MIDDLEBOX_COMPAT",
  5236. SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
  5237. #endif
  5238. #ifdef SSL_OP_NO_RENEGOTIATION
  5239. ADD_OPTION("OP_NO_RENEGOTIATION",
  5240. SSL_OP_NO_RENEGOTIATION);
  5241. #endif
  5242. #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
  5243. ADD_OPTION("OP_IGNORE_UNEXPECTED_EOF",
  5244. SSL_OP_IGNORE_UNEXPECTED_EOF);
  5245. #endif
  5246. #ifdef SSL_OP_ENABLE_KTLS
  5247. ADD_OPTION("OP_ENABLE_KTLS", SSL_OP_ENABLE_KTLS);
  5248. #endif
  5249. #ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
  5250. PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
  5251. X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
  5252. #endif
  5253. #ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
  5254. PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
  5255. X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
  5256. #endif
  5257. #ifdef X509_CHECK_FLAG_NO_WILDCARDS
  5258. PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
  5259. X509_CHECK_FLAG_NO_WILDCARDS);
  5260. #endif
  5261. #ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
  5262. PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
  5263. X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
  5264. #endif
  5265. #ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
  5266. PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
  5267. X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
  5268. #endif
  5269. #ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
  5270. PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
  5271. X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
  5272. #endif
  5273. /* file types */
  5274. PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
  5275. PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
  5276. /* protocol versions */
  5277. PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
  5278. PY_PROTO_MINIMUM_SUPPORTED);
  5279. PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
  5280. PY_PROTO_MAXIMUM_SUPPORTED);
  5281. PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
  5282. PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
  5283. PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
  5284. PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
  5285. PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
  5286. #define addbool(m, key, value) \
  5287. do { \
  5288. PyObject *bool_obj = (value) ? Py_True : Py_False; \
  5289. PyModule_AddObject((m), (key), Py_NewRef(bool_obj)); \
  5290. } while (0)
  5291. addbool(m, "HAS_SNI", 1);
  5292. addbool(m, "HAS_TLS_UNIQUE", 1);
  5293. addbool(m, "HAS_ECDH", 1);
  5294. addbool(m, "HAS_NPN", 0);
  5295. addbool(m, "HAS_ALPN", 1);
  5296. addbool(m, "HAS_SSLv2", 0);
  5297. #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
  5298. addbool(m, "HAS_SSLv3", 1);
  5299. #else
  5300. addbool(m, "HAS_SSLv3", 0);
  5301. #endif
  5302. #if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
  5303. addbool(m, "HAS_TLSv1", 1);
  5304. #else
  5305. addbool(m, "HAS_TLSv1", 0);
  5306. #endif
  5307. #if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
  5308. addbool(m, "HAS_TLSv1_1", 1);
  5309. #else
  5310. addbool(m, "HAS_TLSv1_1", 0);
  5311. #endif
  5312. #if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
  5313. addbool(m, "HAS_TLSv1_2", 1);
  5314. #else
  5315. addbool(m, "HAS_TLSv1_2", 0);
  5316. #endif
  5317. #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
  5318. addbool(m, "HAS_TLSv1_3", 1);
  5319. #else
  5320. addbool(m, "HAS_TLSv1_3", 0);
  5321. #endif
  5322. return 0;
  5323. }
  5324. static int
  5325. sslmodule_init_errorcodes(PyObject *module)
  5326. {
  5327. _sslmodulestate *state = get_ssl_state(module);
  5328. struct py_ssl_error_code *errcode;
  5329. struct py_ssl_library_code *libcode;
  5330. /* Mappings for error codes */
  5331. state->err_codes_to_names = PyDict_New();
  5332. if (state->err_codes_to_names == NULL)
  5333. return -1;
  5334. state->lib_codes_to_names = PyDict_New();
  5335. if (state->lib_codes_to_names == NULL)
  5336. return -1;
  5337. errcode = error_codes;
  5338. while (errcode->mnemonic != NULL) {
  5339. PyObject *mnemo = PyUnicode_FromString(errcode->mnemonic);
  5340. if (mnemo == NULL) {
  5341. return -1;
  5342. }
  5343. PyObject *key = Py_BuildValue("ii", errcode->library, errcode->reason);
  5344. if (key == NULL) {
  5345. Py_DECREF(mnemo);
  5346. return -1;
  5347. }
  5348. int rc = PyDict_SetItem(state->err_codes_to_names, key, mnemo);
  5349. Py_DECREF(key);
  5350. Py_DECREF(mnemo);
  5351. if (rc < 0) {
  5352. return -1;
  5353. }
  5354. errcode++;
  5355. }
  5356. libcode = library_codes;
  5357. while (libcode->library != NULL) {
  5358. PyObject *mnemo, *key;
  5359. key = PyLong_FromLong(libcode->code);
  5360. mnemo = PyUnicode_FromString(libcode->library);
  5361. if (key == NULL || mnemo == NULL)
  5362. return -1;
  5363. if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
  5364. return -1;
  5365. Py_DECREF(key);
  5366. Py_DECREF(mnemo);
  5367. libcode++;
  5368. }
  5369. return 0;
  5370. }
  5371. static void
  5372. parse_openssl_version(unsigned long libver,
  5373. unsigned int *major, unsigned int *minor,
  5374. unsigned int *fix, unsigned int *patch,
  5375. unsigned int *status)
  5376. {
  5377. *status = libver & 0xF;
  5378. libver >>= 4;
  5379. *patch = libver & 0xFF;
  5380. libver >>= 8;
  5381. *fix = libver & 0xFF;
  5382. libver >>= 8;
  5383. *minor = libver & 0xFF;
  5384. libver >>= 8;
  5385. *major = libver & 0xFF;
  5386. }
  5387. static int
  5388. sslmodule_init_versioninfo(PyObject *m)
  5389. {
  5390. PyObject *r;
  5391. unsigned long libver;
  5392. unsigned int major, minor, fix, patch, status;
  5393. /* OpenSSL version */
  5394. /* SSLeay() gives us the version of the library linked against,
  5395. which could be different from the headers version.
  5396. */
  5397. libver = OpenSSL_version_num();
  5398. r = PyLong_FromUnsignedLong(libver);
  5399. if (_PyModule_Add(m, "OPENSSL_VERSION_NUMBER", r) < 0)
  5400. return -1;
  5401. parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
  5402. r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
  5403. if (_PyModule_Add(m, "OPENSSL_VERSION_INFO", r) < 0)
  5404. return -1;
  5405. r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
  5406. if (_PyModule_Add(m, "OPENSSL_VERSION", r) < 0)
  5407. return -1;
  5408. libver = OPENSSL_VERSION_NUMBER;
  5409. parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
  5410. r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
  5411. if (_PyModule_Add(m, "_OPENSSL_API_VERSION", r) < 0)
  5412. return -1;
  5413. return 0;
  5414. }
  5415. static int
  5416. sslmodule_init_types(PyObject *module)
  5417. {
  5418. _sslmodulestate *state = get_ssl_state(module);
  5419. state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
  5420. module, &PySSLContext_spec, NULL
  5421. );
  5422. if (state->PySSLContext_Type == NULL)
  5423. return -1;
  5424. state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
  5425. module, &PySSLSocket_spec, NULL
  5426. );
  5427. if (state->PySSLSocket_Type == NULL)
  5428. return -1;
  5429. state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
  5430. module, &PySSLMemoryBIO_spec, NULL
  5431. );
  5432. if (state->PySSLMemoryBIO_Type == NULL)
  5433. return -1;
  5434. state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
  5435. module, &PySSLSession_spec, NULL
  5436. );
  5437. if (state->PySSLSession_Type == NULL)
  5438. return -1;
  5439. state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
  5440. module, &PySSLCertificate_spec, NULL
  5441. );
  5442. if (state->PySSLCertificate_Type == NULL)
  5443. return -1;
  5444. if (PyModule_AddType(module, state->PySSLContext_Type))
  5445. return -1;
  5446. if (PyModule_AddType(module, state->PySSLSocket_Type))
  5447. return -1;
  5448. if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
  5449. return -1;
  5450. if (PyModule_AddType(module, state->PySSLSession_Type))
  5451. return -1;
  5452. if (PyModule_AddType(module, state->PySSLCertificate_Type))
  5453. return -1;
  5454. return 0;
  5455. }
  5456. static int
  5457. sslmodule_init_strings(PyObject *module)
  5458. {
  5459. _sslmodulestate *state = get_ssl_state(module);
  5460. state->str_library = PyUnicode_InternFromString("library");
  5461. if (state->str_library == NULL) {
  5462. return -1;
  5463. }
  5464. state->str_reason = PyUnicode_InternFromString("reason");
  5465. if (state->str_reason == NULL) {
  5466. return -1;
  5467. }
  5468. state->str_verify_message = PyUnicode_InternFromString("verify_message");
  5469. if (state->str_verify_message == NULL) {
  5470. return -1;
  5471. }
  5472. state->str_verify_code = PyUnicode_InternFromString("verify_code");
  5473. if (state->str_verify_code == NULL) {
  5474. return -1;
  5475. }
  5476. return 0;
  5477. }
  5478. static int
  5479. sslmodule_init_lock(PyObject *module)
  5480. {
  5481. _sslmodulestate *state = get_ssl_state(module);
  5482. state->keylog_lock = PyThread_allocate_lock();
  5483. if (state->keylog_lock == NULL) {
  5484. PyErr_NoMemory();
  5485. return -1;
  5486. }
  5487. return 0;
  5488. }
  5489. static PyModuleDef_Slot sslmodule_slots[] = {
  5490. {Py_mod_exec, sslmodule_init_types},
  5491. {Py_mod_exec, sslmodule_init_exceptions},
  5492. {Py_mod_exec, sslmodule_init_socketapi},
  5493. {Py_mod_exec, sslmodule_init_errorcodes},
  5494. {Py_mod_exec, sslmodule_init_constants},
  5495. {Py_mod_exec, sslmodule_init_versioninfo},
  5496. {Py_mod_exec, sslmodule_init_strings},
  5497. {Py_mod_exec, sslmodule_init_lock},
  5498. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  5499. {0, NULL}
  5500. };
  5501. static int
  5502. sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
  5503. {
  5504. _sslmodulestate *state = get_ssl_state(m);
  5505. Py_VISIT(state->PySSLContext_Type);
  5506. Py_VISIT(state->PySSLSocket_Type);
  5507. Py_VISIT(state->PySSLMemoryBIO_Type);
  5508. Py_VISIT(state->PySSLSession_Type);
  5509. Py_VISIT(state->PySSLCertificate_Type);
  5510. Py_VISIT(state->PySSLErrorObject);
  5511. Py_VISIT(state->PySSLCertVerificationErrorObject);
  5512. Py_VISIT(state->PySSLZeroReturnErrorObject);
  5513. Py_VISIT(state->PySSLWantReadErrorObject);
  5514. Py_VISIT(state->PySSLWantWriteErrorObject);
  5515. Py_VISIT(state->PySSLSyscallErrorObject);
  5516. Py_VISIT(state->PySSLEOFErrorObject);
  5517. Py_VISIT(state->err_codes_to_names);
  5518. Py_VISIT(state->lib_codes_to_names);
  5519. Py_VISIT(state->Sock_Type);
  5520. return 0;
  5521. }
  5522. static int
  5523. sslmodule_clear(PyObject *m)
  5524. {
  5525. _sslmodulestate *state = get_ssl_state(m);
  5526. Py_CLEAR(state->PySSLContext_Type);
  5527. Py_CLEAR(state->PySSLSocket_Type);
  5528. Py_CLEAR(state->PySSLMemoryBIO_Type);
  5529. Py_CLEAR(state->PySSLSession_Type);
  5530. Py_CLEAR(state->PySSLCertificate_Type);
  5531. Py_CLEAR(state->PySSLErrorObject);
  5532. Py_CLEAR(state->PySSLCertVerificationErrorObject);
  5533. Py_CLEAR(state->PySSLZeroReturnErrorObject);
  5534. Py_CLEAR(state->PySSLWantReadErrorObject);
  5535. Py_CLEAR(state->PySSLWantWriteErrorObject);
  5536. Py_CLEAR(state->PySSLSyscallErrorObject);
  5537. Py_CLEAR(state->PySSLEOFErrorObject);
  5538. Py_CLEAR(state->err_codes_to_names);
  5539. Py_CLEAR(state->lib_codes_to_names);
  5540. Py_CLEAR(state->Sock_Type);
  5541. Py_CLEAR(state->str_library);
  5542. Py_CLEAR(state->str_reason);
  5543. Py_CLEAR(state->str_verify_code);
  5544. Py_CLEAR(state->str_verify_message);
  5545. return 0;
  5546. }
  5547. static void
  5548. sslmodule_free(void *m)
  5549. {
  5550. sslmodule_clear((PyObject *)m);
  5551. _sslmodulestate *state = get_ssl_state(m);
  5552. PyThread_free_lock(state->keylog_lock);
  5553. }
  5554. static struct PyModuleDef _sslmodule_def = {
  5555. PyModuleDef_HEAD_INIT,
  5556. .m_name = "_ssl",
  5557. .m_doc = module_doc,
  5558. .m_size = sizeof(_sslmodulestate),
  5559. .m_methods = PySSL_methods,
  5560. .m_slots = sslmodule_slots,
  5561. .m_traverse = sslmodule_traverse,
  5562. .m_clear = sslmodule_clear,
  5563. .m_free = sslmodule_free
  5564. };
  5565. PyMODINIT_FUNC
  5566. PyInit__ssl(void)
  5567. {
  5568. return PyModuleDef_Init(&_sslmodule_def);
  5569. }