_ssl.c 187 KB

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