test_ssl.py 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245
  1. # Copyright (C) Jean-Paul Calderone
  2. # See LICENSE for details.
  3. """
  4. Unit tests for :mod:`OpenSSL.SSL`.
  5. """
  6. import datetime
  7. import gc
  8. import sys
  9. import uuid
  10. from gc import collect, get_referrers
  11. from errno import (
  12. EAFNOSUPPORT,
  13. ECONNREFUSED,
  14. EINPROGRESS,
  15. EWOULDBLOCK,
  16. EPIPE,
  17. ESHUTDOWN,
  18. )
  19. from sys import platform, getfilesystemencoding
  20. from socket import AF_INET, AF_INET6, MSG_PEEK, SHUT_RDWR, error, socket
  21. from os import makedirs
  22. from os.path import join
  23. from weakref import ref
  24. from warnings import simplefilter
  25. import flaky
  26. import pytest
  27. from pretend import raiser
  28. from six import PY2, text_type
  29. from cryptography import x509
  30. from cryptography.hazmat.backends import default_backend
  31. from cryptography.hazmat.primitives import hashes
  32. from cryptography.hazmat.primitives import serialization
  33. from cryptography.hazmat.primitives.asymmetric import rsa
  34. from cryptography.x509.oid import NameOID
  35. from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM
  36. from OpenSSL.crypto import PKey, X509, X509Extension, X509Store
  37. from OpenSSL.crypto import dump_privatekey, load_privatekey
  38. from OpenSSL.crypto import dump_certificate, load_certificate
  39. from OpenSSL.crypto import get_elliptic_curves
  40. from OpenSSL.SSL import (
  41. OPENSSL_VERSION_NUMBER,
  42. SSLEAY_VERSION,
  43. SSLEAY_CFLAGS,
  44. TLS_METHOD,
  45. TLS1_3_VERSION,
  46. TLS1_2_VERSION,
  47. TLS1_1_VERSION,
  48. )
  49. from OpenSSL.SSL import SSLEAY_PLATFORM, SSLEAY_DIR, SSLEAY_BUILT_ON
  50. from OpenSSL.SSL import SENT_SHUTDOWN, RECEIVED_SHUTDOWN
  51. from OpenSSL.SSL import (
  52. SSLv2_METHOD,
  53. SSLv3_METHOD,
  54. SSLv23_METHOD,
  55. TLSv1_METHOD,
  56. TLSv1_1_METHOD,
  57. TLSv1_2_METHOD,
  58. )
  59. from OpenSSL.SSL import OP_SINGLE_DH_USE, OP_NO_SSLv2, OP_NO_SSLv3
  60. from OpenSSL.SSL import (
  61. VERIFY_PEER,
  62. VERIFY_FAIL_IF_NO_PEER_CERT,
  63. VERIFY_CLIENT_ONCE,
  64. VERIFY_NONE,
  65. )
  66. from OpenSSL import SSL
  67. from OpenSSL.SSL import (
  68. SESS_CACHE_OFF,
  69. SESS_CACHE_CLIENT,
  70. SESS_CACHE_SERVER,
  71. SESS_CACHE_BOTH,
  72. SESS_CACHE_NO_AUTO_CLEAR,
  73. SESS_CACHE_NO_INTERNAL_LOOKUP,
  74. SESS_CACHE_NO_INTERNAL_STORE,
  75. SESS_CACHE_NO_INTERNAL,
  76. )
  77. from OpenSSL.SSL import (
  78. Error,
  79. SysCallError,
  80. WantReadError,
  81. WantWriteError,
  82. ZeroReturnError,
  83. )
  84. from OpenSSL.SSL import Context, Session, Connection, SSLeay_version
  85. from OpenSSL.SSL import _make_requires
  86. from OpenSSL._util import ffi as _ffi, lib as _lib
  87. from OpenSSL.SSL import (
  88. OP_NO_QUERY_MTU,
  89. OP_COOKIE_EXCHANGE,
  90. OP_NO_TICKET,
  91. OP_NO_COMPRESSION,
  92. MODE_RELEASE_BUFFERS,
  93. NO_OVERLAPPING_PROTOCOLS,
  94. )
  95. from OpenSSL.SSL import (
  96. SSL_ST_CONNECT,
  97. SSL_ST_ACCEPT,
  98. SSL_ST_MASK,
  99. SSL_CB_LOOP,
  100. SSL_CB_EXIT,
  101. SSL_CB_READ,
  102. SSL_CB_WRITE,
  103. SSL_CB_ALERT,
  104. SSL_CB_READ_ALERT,
  105. SSL_CB_WRITE_ALERT,
  106. SSL_CB_ACCEPT_LOOP,
  107. SSL_CB_ACCEPT_EXIT,
  108. SSL_CB_CONNECT_LOOP,
  109. SSL_CB_CONNECT_EXIT,
  110. SSL_CB_HANDSHAKE_START,
  111. SSL_CB_HANDSHAKE_DONE,
  112. )
  113. try:
  114. from OpenSSL.SSL import (
  115. SSL_ST_INIT,
  116. SSL_ST_BEFORE,
  117. SSL_ST_OK,
  118. SSL_ST_RENEGOTIATE,
  119. )
  120. except ImportError:
  121. SSL_ST_INIT = SSL_ST_BEFORE = SSL_ST_OK = SSL_ST_RENEGOTIATE = None
  122. try:
  123. from OpenSSL.SSL import OP_NO_TLSv1_3
  124. except ImportError:
  125. OP_NO_TLSv1_3 = None
  126. from .util import WARNING_TYPE_EXPECTED, NON_ASCII, is_consistent_type
  127. from .test_crypto import (
  128. client_cert_pem,
  129. client_key_pem,
  130. server_cert_pem,
  131. server_key_pem,
  132. root_cert_pem,
  133. root_key_pem,
  134. )
  135. # openssl dhparam 2048 -out dh-2048.pem
  136. dhparam = """\
  137. -----BEGIN DH PARAMETERS-----
  138. MIIBCAKCAQEA2F5e976d/GjsaCdKv5RMWL/YV7fq1UUWpPAer5fDXflLMVUuYXxE
  139. 3m3ayZob9lbpgEU0jlPAsXHfQPGxpKmvhv+xV26V/DEoukED8JeZUY/z4pigoptl
  140. +8+TYdNNE/rFSZQFXIp+v2D91IEgmHBnZlKFSbKR+p8i0KjExXGjU6ji3S5jkOku
  141. ogikc7df1Ui0hWNJCmTjExq07aXghk97PsdFSxjdawuG3+vos5bnNoUwPLYlFc/z
  142. ITYG0KXySiCLi4UDlXTZTz7u/+OYczPEgqa/JPUddbM/kfvaRAnjY38cfQ7qXf8Y
  143. i5s5yYK7a/0eWxxRr2qraYaUj8RwDpH9CwIBAg==
  144. -----END DH PARAMETERS-----
  145. """
  146. skip_if_py3 = pytest.mark.skipif(not PY2, reason="Python 2 only")
  147. def socket_any_family():
  148. try:
  149. return socket(AF_INET)
  150. except error as e:
  151. if e.errno == EAFNOSUPPORT:
  152. return socket(AF_INET6)
  153. raise
  154. def loopback_address(socket):
  155. if socket.family == AF_INET:
  156. return "127.0.0.1"
  157. else:
  158. assert socket.family == AF_INET6
  159. return "::1"
  160. def join_bytes_or_unicode(prefix, suffix):
  161. """
  162. Join two path components of either ``bytes`` or ``unicode``.
  163. The return type is the same as the type of ``prefix``.
  164. """
  165. # If the types are the same, nothing special is necessary.
  166. if type(prefix) == type(suffix):
  167. return join(prefix, suffix)
  168. # Otherwise, coerce suffix to the type of prefix.
  169. if isinstance(prefix, text_type):
  170. return join(prefix, suffix.decode(getfilesystemencoding()))
  171. else:
  172. return join(prefix, suffix.encode(getfilesystemencoding()))
  173. def verify_cb(conn, cert, errnum, depth, ok):
  174. return ok
  175. def socket_pair():
  176. """
  177. Establish and return a pair of network sockets connected to each other.
  178. """
  179. # Connect a pair of sockets
  180. port = socket_any_family()
  181. port.bind(("", 0))
  182. port.listen(1)
  183. client = socket(port.family)
  184. client.setblocking(False)
  185. client.connect_ex((loopback_address(port), port.getsockname()[1]))
  186. client.setblocking(True)
  187. server = port.accept()[0]
  188. # Let's pass some unencrypted data to make sure our socket connection is
  189. # fine. Just one byte, so we don't have to worry about buffers getting
  190. # filled up or fragmentation.
  191. server.send(b"x")
  192. assert client.recv(1024) == b"x"
  193. client.send(b"y")
  194. assert server.recv(1024) == b"y"
  195. # Most of our callers want non-blocking sockets, make it easy for them.
  196. server.setblocking(False)
  197. client.setblocking(False)
  198. return (server, client)
  199. def handshake(client, server):
  200. conns = [client, server]
  201. while conns:
  202. for conn in conns:
  203. try:
  204. conn.do_handshake()
  205. except WantReadError:
  206. pass
  207. else:
  208. conns.remove(conn)
  209. def _create_certificate_chain():
  210. """
  211. Construct and return a chain of certificates.
  212. 1. A new self-signed certificate authority certificate (cacert)
  213. 2. A new intermediate certificate signed by cacert (icert)
  214. 3. A new server certificate signed by icert (scert)
  215. """
  216. caext = X509Extension(b"basicConstraints", False, b"CA:true")
  217. not_after_date = datetime.date.today() + datetime.timedelta(days=365)
  218. not_after = not_after_date.strftime("%Y%m%d%H%M%SZ").encode("ascii")
  219. # Step 1
  220. cakey = PKey()
  221. cakey.generate_key(TYPE_RSA, 2048)
  222. cacert = X509()
  223. cacert.set_version(2)
  224. cacert.get_subject().commonName = "Authority Certificate"
  225. cacert.set_issuer(cacert.get_subject())
  226. cacert.set_pubkey(cakey)
  227. cacert.set_notBefore(b"20000101000000Z")
  228. cacert.set_notAfter(not_after)
  229. cacert.add_extensions([caext])
  230. cacert.set_serial_number(0)
  231. cacert.sign(cakey, "sha256")
  232. # Step 2
  233. ikey = PKey()
  234. ikey.generate_key(TYPE_RSA, 2048)
  235. icert = X509()
  236. icert.set_version(2)
  237. icert.get_subject().commonName = "Intermediate Certificate"
  238. icert.set_issuer(cacert.get_subject())
  239. icert.set_pubkey(ikey)
  240. icert.set_notBefore(b"20000101000000Z")
  241. icert.set_notAfter(not_after)
  242. icert.add_extensions([caext])
  243. icert.set_serial_number(0)
  244. icert.sign(cakey, "sha256")
  245. # Step 3
  246. skey = PKey()
  247. skey.generate_key(TYPE_RSA, 2048)
  248. scert = X509()
  249. scert.set_version(2)
  250. scert.get_subject().commonName = "Server Certificate"
  251. scert.set_issuer(icert.get_subject())
  252. scert.set_pubkey(skey)
  253. scert.set_notBefore(b"20000101000000Z")
  254. scert.set_notAfter(not_after)
  255. scert.add_extensions(
  256. [X509Extension(b"basicConstraints", True, b"CA:false")]
  257. )
  258. scert.set_serial_number(0)
  259. scert.sign(ikey, "sha256")
  260. return [(cakey, cacert), (ikey, icert), (skey, scert)]
  261. def loopback_client_factory(socket, version=SSLv23_METHOD):
  262. client = Connection(Context(version), socket)
  263. client.set_connect_state()
  264. return client
  265. def loopback_server_factory(socket, version=SSLv23_METHOD):
  266. ctx = Context(version)
  267. ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  268. ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
  269. server = Connection(ctx, socket)
  270. server.set_accept_state()
  271. return server
  272. def loopback(server_factory=None, client_factory=None):
  273. """
  274. Create a connected socket pair and force two connected SSL sockets
  275. to talk to each other via memory BIOs.
  276. """
  277. if server_factory is None:
  278. server_factory = loopback_server_factory
  279. if client_factory is None:
  280. client_factory = loopback_client_factory
  281. (server, client) = socket_pair()
  282. server = server_factory(server)
  283. client = client_factory(client)
  284. handshake(client, server)
  285. server.setblocking(True)
  286. client.setblocking(True)
  287. return server, client
  288. def interact_in_memory(client_conn, server_conn):
  289. """
  290. Try to read application bytes from each of the two `Connection` objects.
  291. Copy bytes back and forth between their send/receive buffers for as long
  292. as there is anything to copy. When there is nothing more to copy,
  293. return `None`. If one of them actually manages to deliver some application
  294. bytes, return a two-tuple of the connection from which the bytes were read
  295. and the bytes themselves.
  296. """
  297. wrote = True
  298. while wrote:
  299. # Loop until neither side has anything to say
  300. wrote = False
  301. # Copy stuff from each side's send buffer to the other side's
  302. # receive buffer.
  303. for (read, write) in [
  304. (client_conn, server_conn),
  305. (server_conn, client_conn),
  306. ]:
  307. # Give the side a chance to generate some more bytes, or succeed.
  308. try:
  309. data = read.recv(2 ** 16)
  310. except WantReadError:
  311. # It didn't succeed, so we'll hope it generated some output.
  312. pass
  313. else:
  314. # It did succeed, so we'll stop now and let the caller deal
  315. # with it.
  316. return (read, data)
  317. while True:
  318. # Keep copying as long as there's more stuff there.
  319. try:
  320. dirty = read.bio_read(4096)
  321. except WantReadError:
  322. # Okay, nothing more waiting to be sent. Stop
  323. # processing this send buffer.
  324. break
  325. else:
  326. # Keep track of the fact that someone generated some
  327. # output.
  328. wrote = True
  329. write.bio_write(dirty)
  330. def handshake_in_memory(client_conn, server_conn):
  331. """
  332. Perform the TLS handshake between two `Connection` instances connected to
  333. each other via memory BIOs.
  334. """
  335. client_conn.set_connect_state()
  336. server_conn.set_accept_state()
  337. for conn in [client_conn, server_conn]:
  338. try:
  339. conn.do_handshake()
  340. except WantReadError:
  341. pass
  342. interact_in_memory(client_conn, server_conn)
  343. class TestVersion(object):
  344. """
  345. Tests for version information exposed by `OpenSSL.SSL.SSLeay_version` and
  346. `OpenSSL.SSL.OPENSSL_VERSION_NUMBER`.
  347. """
  348. def test_OPENSSL_VERSION_NUMBER(self):
  349. """
  350. `OPENSSL_VERSION_NUMBER` is an integer with status in the low byte and
  351. the patch, fix, minor, and major versions in the nibbles above that.
  352. """
  353. assert isinstance(OPENSSL_VERSION_NUMBER, int)
  354. def test_SSLeay_version(self):
  355. """
  356. `SSLeay_version` takes a version type indicator and returns one of a
  357. number of version strings based on that indicator.
  358. """
  359. versions = {}
  360. for t in [
  361. SSLEAY_VERSION,
  362. SSLEAY_CFLAGS,
  363. SSLEAY_BUILT_ON,
  364. SSLEAY_PLATFORM,
  365. SSLEAY_DIR,
  366. ]:
  367. version = SSLeay_version(t)
  368. versions[version] = t
  369. assert isinstance(version, bytes)
  370. assert len(versions) == 5
  371. @pytest.fixture
  372. def ca_file(tmpdir):
  373. """
  374. Create a valid PEM file with CA certificates and return the path.
  375. """
  376. key = rsa.generate_private_key(
  377. public_exponent=65537, key_size=2048, backend=default_backend()
  378. )
  379. public_key = key.public_key()
  380. builder = x509.CertificateBuilder()
  381. builder = builder.subject_name(
  382. x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org")])
  383. )
  384. builder = builder.issuer_name(
  385. x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org")])
  386. )
  387. one_day = datetime.timedelta(1, 0, 0)
  388. builder = builder.not_valid_before(datetime.datetime.today() - one_day)
  389. builder = builder.not_valid_after(datetime.datetime.today() + one_day)
  390. builder = builder.serial_number(int(uuid.uuid4()))
  391. builder = builder.public_key(public_key)
  392. builder = builder.add_extension(
  393. x509.BasicConstraints(ca=True, path_length=None),
  394. critical=True,
  395. )
  396. certificate = builder.sign(
  397. private_key=key, algorithm=hashes.SHA256(), backend=default_backend()
  398. )
  399. ca_file = tmpdir.join("test.pem")
  400. ca_file.write_binary(
  401. certificate.public_bytes(
  402. encoding=serialization.Encoding.PEM,
  403. )
  404. )
  405. return str(ca_file).encode("ascii")
  406. @pytest.fixture
  407. def context():
  408. """
  409. A simple "best TLS you can get" context. TLS 1.2+ in any reasonable OpenSSL
  410. """
  411. return Context(SSLv23_METHOD)
  412. class TestContext(object):
  413. """
  414. Unit tests for `OpenSSL.SSL.Context`.
  415. """
  416. @pytest.mark.parametrize(
  417. "cipher_string",
  418. [b"hello world:AES128-SHA", u"hello world:AES128-SHA"],
  419. )
  420. def test_set_cipher_list(self, context, cipher_string):
  421. """
  422. `Context.set_cipher_list` accepts both byte and unicode strings
  423. for naming the ciphers which connections created with the context
  424. object will be able to choose from.
  425. """
  426. context.set_cipher_list(cipher_string)
  427. conn = Connection(context, None)
  428. assert "AES128-SHA" in conn.get_cipher_list()
  429. def test_set_cipher_list_wrong_type(self, context):
  430. """
  431. `Context.set_cipher_list` raises `TypeError` when passed a non-string
  432. argument.
  433. """
  434. with pytest.raises(TypeError):
  435. context.set_cipher_list(object())
  436. @flaky.flaky
  437. def test_set_cipher_list_no_cipher_match(self, context):
  438. """
  439. `Context.set_cipher_list` raises `OpenSSL.SSL.Error` with a
  440. `"no cipher match"` reason string regardless of the TLS
  441. version.
  442. """
  443. with pytest.raises(Error) as excinfo:
  444. context.set_cipher_list(b"imaginary-cipher")
  445. assert excinfo.value.args == (
  446. [
  447. (
  448. "SSL routines",
  449. "SSL_CTX_set_cipher_list",
  450. "no cipher match",
  451. )
  452. ],
  453. )
  454. def test_load_client_ca(self, context, ca_file):
  455. """
  456. `Context.load_client_ca` works as far as we can tell.
  457. """
  458. context.load_client_ca(ca_file)
  459. def test_load_client_ca_invalid(self, context, tmpdir):
  460. """
  461. `Context.load_client_ca` raises an Error if the ca file is invalid.
  462. """
  463. ca_file = tmpdir.join("test.pem")
  464. ca_file.write("")
  465. with pytest.raises(Error) as e:
  466. context.load_client_ca(str(ca_file).encode("ascii"))
  467. assert "PEM routines" == e.value.args[0][0][0]
  468. def test_load_client_ca_unicode(self, context, ca_file):
  469. """
  470. Passing the path as unicode raises a warning but works.
  471. """
  472. pytest.deprecated_call(context.load_client_ca, ca_file.decode("ascii"))
  473. def test_set_session_id(self, context):
  474. """
  475. `Context.set_session_id` works as far as we can tell.
  476. """
  477. context.set_session_id(b"abc")
  478. def test_set_session_id_fail(self, context):
  479. """
  480. `Context.set_session_id` errors are propagated.
  481. """
  482. with pytest.raises(Error) as e:
  483. context.set_session_id(b"abc" * 1000)
  484. assert [
  485. (
  486. "SSL routines",
  487. "SSL_CTX_set_session_id_context",
  488. "ssl session id context too long",
  489. )
  490. ] == e.value.args[0]
  491. def test_set_session_id_unicode(self, context):
  492. """
  493. `Context.set_session_id` raises a warning if a unicode string is
  494. passed.
  495. """
  496. pytest.deprecated_call(context.set_session_id, u"abc")
  497. def test_method(self):
  498. """
  499. `Context` can be instantiated with one of `SSLv2_METHOD`,
  500. `SSLv3_METHOD`, `SSLv23_METHOD`, `TLSv1_METHOD`, `TLSv1_1_METHOD`,
  501. or `TLSv1_2_METHOD`.
  502. """
  503. methods = [SSLv23_METHOD, TLSv1_METHOD]
  504. for meth in methods:
  505. Context(meth)
  506. maybe = [SSLv2_METHOD, SSLv3_METHOD, TLSv1_1_METHOD, TLSv1_2_METHOD]
  507. for meth in maybe:
  508. try:
  509. Context(meth)
  510. except (Error, ValueError):
  511. # Some versions of OpenSSL have SSLv2 / TLSv1.1 / TLSv1.2, some
  512. # don't. Difficult to say in advance.
  513. pass
  514. with pytest.raises(TypeError):
  515. Context("")
  516. with pytest.raises(ValueError):
  517. Context(10)
  518. def test_type(self):
  519. """
  520. `Context` can be used to create instances of that type.
  521. """
  522. assert is_consistent_type(Context, "Context", TLSv1_METHOD)
  523. def test_use_privatekey(self):
  524. """
  525. `Context.use_privatekey` takes an `OpenSSL.crypto.PKey` instance.
  526. """
  527. key = PKey()
  528. key.generate_key(TYPE_RSA, 1024)
  529. ctx = Context(SSLv23_METHOD)
  530. ctx.use_privatekey(key)
  531. with pytest.raises(TypeError):
  532. ctx.use_privatekey("")
  533. def test_use_privatekey_file_missing(self, tmpfile):
  534. """
  535. `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` when passed
  536. the name of a file which does not exist.
  537. """
  538. ctx = Context(SSLv23_METHOD)
  539. with pytest.raises(Error):
  540. ctx.use_privatekey_file(tmpfile)
  541. def _use_privatekey_file_test(self, pemfile, filetype):
  542. """
  543. Verify that calling ``Context.use_privatekey_file`` with the given
  544. arguments does not raise an exception.
  545. """
  546. key = PKey()
  547. key.generate_key(TYPE_RSA, 1024)
  548. with open(pemfile, "wt") as pem:
  549. pem.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
  550. ctx = Context(SSLv23_METHOD)
  551. ctx.use_privatekey_file(pemfile, filetype)
  552. @pytest.mark.parametrize("filetype", [object(), "", None, 1.0])
  553. def test_wrong_privatekey_file_wrong_args(self, tmpfile, filetype):
  554. """
  555. `Context.use_privatekey_file` raises `TypeError` when called with
  556. a `filetype` which is not a valid file encoding.
  557. """
  558. ctx = Context(SSLv23_METHOD)
  559. with pytest.raises(TypeError):
  560. ctx.use_privatekey_file(tmpfile, filetype)
  561. def test_use_privatekey_file_bytes(self, tmpfile):
  562. """
  563. A private key can be specified from a file by passing a ``bytes``
  564. instance giving the file name to ``Context.use_privatekey_file``.
  565. """
  566. self._use_privatekey_file_test(
  567. tmpfile + NON_ASCII.encode(getfilesystemencoding()),
  568. FILETYPE_PEM,
  569. )
  570. def test_use_privatekey_file_unicode(self, tmpfile):
  571. """
  572. A private key can be specified from a file by passing a ``unicode``
  573. instance giving the file name to ``Context.use_privatekey_file``.
  574. """
  575. self._use_privatekey_file_test(
  576. tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
  577. FILETYPE_PEM,
  578. )
  579. def test_use_certificate_wrong_args(self):
  580. """
  581. `Context.use_certificate_wrong_args` raises `TypeError` when not passed
  582. exactly one `OpenSSL.crypto.X509` instance as an argument.
  583. """
  584. ctx = Context(SSLv23_METHOD)
  585. with pytest.raises(TypeError):
  586. ctx.use_certificate("hello, world")
  587. def test_use_certificate_uninitialized(self):
  588. """
  589. `Context.use_certificate` raises `OpenSSL.SSL.Error` when passed a
  590. `OpenSSL.crypto.X509` instance which has not been initialized
  591. (ie, which does not actually have any certificate data).
  592. """
  593. ctx = Context(SSLv23_METHOD)
  594. with pytest.raises(Error):
  595. ctx.use_certificate(X509())
  596. def test_use_certificate(self):
  597. """
  598. `Context.use_certificate` sets the certificate which will be
  599. used to identify connections created using the context.
  600. """
  601. # TODO
  602. # Hard to assert anything. But we could set a privatekey then ask
  603. # OpenSSL if the cert and key agree using check_privatekey. Then as
  604. # long as check_privatekey works right we're good...
  605. ctx = Context(SSLv23_METHOD)
  606. ctx.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
  607. def test_use_certificate_file_wrong_args(self):
  608. """
  609. `Context.use_certificate_file` raises `TypeError` if the first
  610. argument is not a byte string or the second argument is not an integer.
  611. """
  612. ctx = Context(SSLv23_METHOD)
  613. with pytest.raises(TypeError):
  614. ctx.use_certificate_file(object(), FILETYPE_PEM)
  615. with pytest.raises(TypeError):
  616. ctx.use_certificate_file(b"somefile", object())
  617. with pytest.raises(TypeError):
  618. ctx.use_certificate_file(object(), FILETYPE_PEM)
  619. def test_use_certificate_file_missing(self, tmpfile):
  620. """
  621. `Context.use_certificate_file` raises `OpenSSL.SSL.Error` if passed
  622. the name of a file which does not exist.
  623. """
  624. ctx = Context(SSLv23_METHOD)
  625. with pytest.raises(Error):
  626. ctx.use_certificate_file(tmpfile)
  627. def _use_certificate_file_test(self, certificate_file):
  628. """
  629. Verify that calling ``Context.use_certificate_file`` with the given
  630. filename doesn't raise an exception.
  631. """
  632. # TODO
  633. # Hard to assert anything. But we could set a privatekey then ask
  634. # OpenSSL if the cert and key agree using check_privatekey. Then as
  635. # long as check_privatekey works right we're good...
  636. with open(certificate_file, "wb") as pem_file:
  637. pem_file.write(root_cert_pem)
  638. ctx = Context(SSLv23_METHOD)
  639. ctx.use_certificate_file(certificate_file)
  640. def test_use_certificate_file_bytes(self, tmpfile):
  641. """
  642. `Context.use_certificate_file` sets the certificate (given as a
  643. `bytes` filename) which will be used to identify connections created
  644. using the context.
  645. """
  646. filename = tmpfile + NON_ASCII.encode(getfilesystemencoding())
  647. self._use_certificate_file_test(filename)
  648. def test_use_certificate_file_unicode(self, tmpfile):
  649. """
  650. `Context.use_certificate_file` sets the certificate (given as a
  651. `bytes` filename) which will be used to identify connections created
  652. using the context.
  653. """
  654. filename = tmpfile.decode(getfilesystemencoding()) + NON_ASCII
  655. self._use_certificate_file_test(filename)
  656. def test_check_privatekey_valid(self):
  657. """
  658. `Context.check_privatekey` returns `None` if the `Context` instance
  659. has been configured to use a matched key and certificate pair.
  660. """
  661. key = load_privatekey(FILETYPE_PEM, client_key_pem)
  662. cert = load_certificate(FILETYPE_PEM, client_cert_pem)
  663. context = Context(SSLv23_METHOD)
  664. context.use_privatekey(key)
  665. context.use_certificate(cert)
  666. assert None is context.check_privatekey()
  667. def test_check_privatekey_invalid(self):
  668. """
  669. `Context.check_privatekey` raises `Error` if the `Context` instance
  670. has been configured to use a key and certificate pair which don't
  671. relate to each other.
  672. """
  673. key = load_privatekey(FILETYPE_PEM, client_key_pem)
  674. cert = load_certificate(FILETYPE_PEM, server_cert_pem)
  675. context = Context(SSLv23_METHOD)
  676. context.use_privatekey(key)
  677. context.use_certificate(cert)
  678. with pytest.raises(Error):
  679. context.check_privatekey()
  680. def test_app_data(self):
  681. """
  682. `Context.set_app_data` stores an object for later retrieval
  683. using `Context.get_app_data`.
  684. """
  685. app_data = object()
  686. context = Context(SSLv23_METHOD)
  687. context.set_app_data(app_data)
  688. assert context.get_app_data() is app_data
  689. def test_set_options_wrong_args(self):
  690. """
  691. `Context.set_options` raises `TypeError` if called with
  692. a non-`int` argument.
  693. """
  694. context = Context(SSLv23_METHOD)
  695. with pytest.raises(TypeError):
  696. context.set_options(None)
  697. def test_set_options(self):
  698. """
  699. `Context.set_options` returns the new options value.
  700. """
  701. context = Context(SSLv23_METHOD)
  702. options = context.set_options(OP_NO_SSLv2)
  703. assert options & OP_NO_SSLv2 == OP_NO_SSLv2
  704. def test_set_mode_wrong_args(self):
  705. """
  706. `Context.set_mode` raises `TypeError` if called with
  707. a non-`int` argument.
  708. """
  709. context = Context(SSLv23_METHOD)
  710. with pytest.raises(TypeError):
  711. context.set_mode(None)
  712. def test_set_mode(self):
  713. """
  714. `Context.set_mode` accepts a mode bitvector and returns the
  715. newly set mode.
  716. """
  717. context = Context(SSLv23_METHOD)
  718. assert MODE_RELEASE_BUFFERS & context.set_mode(MODE_RELEASE_BUFFERS)
  719. def test_set_timeout_wrong_args(self):
  720. """
  721. `Context.set_timeout` raises `TypeError` if called with
  722. a non-`int` argument.
  723. """
  724. context = Context(SSLv23_METHOD)
  725. with pytest.raises(TypeError):
  726. context.set_timeout(None)
  727. def test_timeout(self):
  728. """
  729. `Context.set_timeout` sets the session timeout for all connections
  730. created using the context object. `Context.get_timeout` retrieves
  731. this value.
  732. """
  733. context = Context(SSLv23_METHOD)
  734. context.set_timeout(1234)
  735. assert context.get_timeout() == 1234
  736. def test_set_verify_depth_wrong_args(self):
  737. """
  738. `Context.set_verify_depth` raises `TypeError` if called with a
  739. non-`int` argument.
  740. """
  741. context = Context(SSLv23_METHOD)
  742. with pytest.raises(TypeError):
  743. context.set_verify_depth(None)
  744. def test_verify_depth(self):
  745. """
  746. `Context.set_verify_depth` sets the number of certificates in
  747. a chain to follow before giving up. The value can be retrieved with
  748. `Context.get_verify_depth`.
  749. """
  750. context = Context(SSLv23_METHOD)
  751. context.set_verify_depth(11)
  752. assert context.get_verify_depth() == 11
  753. def _write_encrypted_pem(self, passphrase, tmpfile):
  754. """
  755. Write a new private key out to a new file, encrypted using the given
  756. passphrase. Return the path to the new file.
  757. """
  758. key = PKey()
  759. key.generate_key(TYPE_RSA, 1024)
  760. pem = dump_privatekey(FILETYPE_PEM, key, "blowfish", passphrase)
  761. with open(tmpfile, "w") as fObj:
  762. fObj.write(pem.decode("ascii"))
  763. return tmpfile
  764. def test_set_passwd_cb_wrong_args(self):
  765. """
  766. `Context.set_passwd_cb` raises `TypeError` if called with a
  767. non-callable first argument.
  768. """
  769. context = Context(SSLv23_METHOD)
  770. with pytest.raises(TypeError):
  771. context.set_passwd_cb(None)
  772. def test_set_passwd_cb(self, tmpfile):
  773. """
  774. `Context.set_passwd_cb` accepts a callable which will be invoked when
  775. a private key is loaded from an encrypted PEM.
  776. """
  777. passphrase = b"foobar"
  778. pemFile = self._write_encrypted_pem(passphrase, tmpfile)
  779. calledWith = []
  780. def passphraseCallback(maxlen, verify, extra):
  781. calledWith.append((maxlen, verify, extra))
  782. return passphrase
  783. context = Context(SSLv23_METHOD)
  784. context.set_passwd_cb(passphraseCallback)
  785. context.use_privatekey_file(pemFile)
  786. assert len(calledWith) == 1
  787. assert isinstance(calledWith[0][0], int)
  788. assert isinstance(calledWith[0][1], int)
  789. assert calledWith[0][2] is None
  790. def test_passwd_callback_exception(self, tmpfile):
  791. """
  792. `Context.use_privatekey_file` propagates any exception raised
  793. by the passphrase callback.
  794. """
  795. pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
  796. def passphraseCallback(maxlen, verify, extra):
  797. raise RuntimeError("Sorry, I am a fail.")
  798. context = Context(SSLv23_METHOD)
  799. context.set_passwd_cb(passphraseCallback)
  800. with pytest.raises(RuntimeError):
  801. context.use_privatekey_file(pemFile)
  802. def test_passwd_callback_false(self, tmpfile):
  803. """
  804. `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
  805. passphrase callback returns a false value.
  806. """
  807. pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
  808. def passphraseCallback(maxlen, verify, extra):
  809. return b""
  810. context = Context(SSLv23_METHOD)
  811. context.set_passwd_cb(passphraseCallback)
  812. with pytest.raises(Error):
  813. context.use_privatekey_file(pemFile)
  814. def test_passwd_callback_non_string(self, tmpfile):
  815. """
  816. `Context.use_privatekey_file` raises `OpenSSL.SSL.Error` if the
  817. passphrase callback returns a true non-string value.
  818. """
  819. pemFile = self._write_encrypted_pem(b"monkeys are nice", tmpfile)
  820. def passphraseCallback(maxlen, verify, extra):
  821. return 10
  822. context = Context(SSLv23_METHOD)
  823. context.set_passwd_cb(passphraseCallback)
  824. # TODO: Surely this is the wrong error?
  825. with pytest.raises(ValueError):
  826. context.use_privatekey_file(pemFile)
  827. def test_passwd_callback_too_long(self, tmpfile):
  828. """
  829. If the passphrase returned by the passphrase callback returns a string
  830. longer than the indicated maximum length, it is truncated.
  831. """
  832. # A priori knowledge!
  833. passphrase = b"x" * 1024
  834. pemFile = self._write_encrypted_pem(passphrase, tmpfile)
  835. def passphraseCallback(maxlen, verify, extra):
  836. assert maxlen == 1024
  837. return passphrase + b"y"
  838. context = Context(SSLv23_METHOD)
  839. context.set_passwd_cb(passphraseCallback)
  840. # This shall succeed because the truncated result is the correct
  841. # passphrase.
  842. context.use_privatekey_file(pemFile)
  843. def test_set_info_callback(self):
  844. """
  845. `Context.set_info_callback` accepts a callable which will be
  846. invoked when certain information about an SSL connection is available.
  847. """
  848. (server, client) = socket_pair()
  849. clientSSL = Connection(Context(SSLv23_METHOD), client)
  850. clientSSL.set_connect_state()
  851. called = []
  852. def info(conn, where, ret):
  853. called.append((conn, where, ret))
  854. context = Context(SSLv23_METHOD)
  855. context.set_info_callback(info)
  856. context.use_certificate(load_certificate(FILETYPE_PEM, root_cert_pem))
  857. context.use_privatekey(load_privatekey(FILETYPE_PEM, root_key_pem))
  858. serverSSL = Connection(context, server)
  859. serverSSL.set_accept_state()
  860. handshake(clientSSL, serverSSL)
  861. # The callback must always be called with a Connection instance as the
  862. # first argument. It would probably be better to split this into
  863. # separate tests for client and server side info callbacks so we could
  864. # assert it is called with the right Connection instance. It would
  865. # also be good to assert *something* about `where` and `ret`.
  866. notConnections = [
  867. conn
  868. for (conn, where, ret) in called
  869. if not isinstance(conn, Connection)
  870. ]
  871. assert (
  872. [] == notConnections
  873. ), "Some info callback arguments were not Connection instances."
  874. @pytest.mark.skipif(
  875. not getattr(_lib, "Cryptography_HAS_KEYLOG", None),
  876. reason="SSL_CTX_set_keylog_callback unavailable",
  877. )
  878. def test_set_keylog_callback(self):
  879. """
  880. `Context.set_keylog_callback` accepts a callable which will be
  881. invoked when key material is generated or received.
  882. """
  883. called = []
  884. def keylog(conn, line):
  885. called.append((conn, line))
  886. server_context = Context(TLSv1_2_METHOD)
  887. server_context.set_keylog_callback(keylog)
  888. server_context.use_certificate(
  889. load_certificate(FILETYPE_PEM, root_cert_pem)
  890. )
  891. server_context.use_privatekey(
  892. load_privatekey(FILETYPE_PEM, root_key_pem)
  893. )
  894. client_context = Context(SSLv23_METHOD)
  895. self._handshake_test(server_context, client_context)
  896. assert called
  897. assert all(isinstance(conn, Connection) for conn, line in called)
  898. assert all(b"CLIENT_RANDOM" in line for conn, line in called)
  899. def test_set_proto_version(self):
  900. if OP_NO_TLSv1_3 is None:
  901. high_version = TLS1_2_VERSION
  902. low_version = TLS1_1_VERSION
  903. else:
  904. high_version = TLS1_3_VERSION
  905. low_version = TLS1_2_VERSION
  906. server_context = Context(TLS_METHOD)
  907. server_context.use_certificate(
  908. load_certificate(FILETYPE_PEM, root_cert_pem)
  909. )
  910. server_context.use_privatekey(
  911. load_privatekey(FILETYPE_PEM, root_key_pem)
  912. )
  913. server_context.set_min_proto_version(high_version)
  914. client_context = Context(TLS_METHOD)
  915. client_context.set_max_proto_version(low_version)
  916. with pytest.raises(Error, match="unsupported protocol"):
  917. self._handshake_test(server_context, client_context)
  918. client_context.set_max_proto_version(0)
  919. self._handshake_test(server_context, client_context)
  920. def _load_verify_locations_test(self, *args):
  921. """
  922. Create a client context which will verify the peer certificate and call
  923. its `load_verify_locations` method with the given arguments.
  924. Then connect it to a server and ensure that the handshake succeeds.
  925. """
  926. (server, client) = socket_pair()
  927. clientContext = Context(SSLv23_METHOD)
  928. clientContext.load_verify_locations(*args)
  929. # Require that the server certificate verify properly or the
  930. # connection will fail.
  931. clientContext.set_verify(
  932. VERIFY_PEER,
  933. lambda conn, cert, errno, depth, preverify_ok: preverify_ok,
  934. )
  935. clientSSL = Connection(clientContext, client)
  936. clientSSL.set_connect_state()
  937. serverContext = Context(SSLv23_METHOD)
  938. serverContext.use_certificate(
  939. load_certificate(FILETYPE_PEM, root_cert_pem)
  940. )
  941. serverContext.use_privatekey(
  942. load_privatekey(FILETYPE_PEM, root_key_pem)
  943. )
  944. serverSSL = Connection(serverContext, server)
  945. serverSSL.set_accept_state()
  946. # Without load_verify_locations above, the handshake
  947. # will fail:
  948. # Error: [('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE',
  949. # 'certificate verify failed')]
  950. handshake(clientSSL, serverSSL)
  951. cert = clientSSL.get_peer_certificate()
  952. assert cert.get_subject().CN == "Testing Root CA"
  953. def _load_verify_cafile(self, cafile):
  954. """
  955. Verify that if path to a file containing a certificate is passed to
  956. `Context.load_verify_locations` for the ``cafile`` parameter, that
  957. certificate is used as a trust root for the purposes of verifying
  958. connections created using that `Context`.
  959. """
  960. with open(cafile, "w") as fObj:
  961. fObj.write(root_cert_pem.decode("ascii"))
  962. self._load_verify_locations_test(cafile)
  963. def test_load_verify_bytes_cafile(self, tmpfile):
  964. """
  965. `Context.load_verify_locations` accepts a file name as a `bytes`
  966. instance and uses the certificates within for verification purposes.
  967. """
  968. cafile = tmpfile + NON_ASCII.encode(getfilesystemencoding())
  969. self._load_verify_cafile(cafile)
  970. def test_load_verify_unicode_cafile(self, tmpfile):
  971. """
  972. `Context.load_verify_locations` accepts a file name as a `unicode`
  973. instance and uses the certificates within for verification purposes.
  974. """
  975. self._load_verify_cafile(
  976. tmpfile.decode(getfilesystemencoding()) + NON_ASCII
  977. )
  978. def test_load_verify_invalid_file(self, tmpfile):
  979. """
  980. `Context.load_verify_locations` raises `Error` when passed a
  981. non-existent cafile.
  982. """
  983. clientContext = Context(SSLv23_METHOD)
  984. with pytest.raises(Error):
  985. clientContext.load_verify_locations(tmpfile)
  986. def _load_verify_directory_locations_capath(self, capath):
  987. """
  988. Verify that if path to a directory containing certificate files is
  989. passed to ``Context.load_verify_locations`` for the ``capath``
  990. parameter, those certificates are used as trust roots for the purposes
  991. of verifying connections created using that ``Context``.
  992. """
  993. makedirs(capath)
  994. # Hash values computed manually with c_rehash to avoid depending on
  995. # c_rehash in the test suite. One is from OpenSSL 0.9.8, the other
  996. # from OpenSSL 1.0.0.
  997. for name in [b"c7adac82.0", b"c3705638.0"]:
  998. cafile = join_bytes_or_unicode(capath, name)
  999. with open(cafile, "w") as fObj:
  1000. fObj.write(root_cert_pem.decode("ascii"))
  1001. self._load_verify_locations_test(None, capath)
  1002. def test_load_verify_directory_bytes_capath(self, tmpfile):
  1003. """
  1004. `Context.load_verify_locations` accepts a directory name as a `bytes`
  1005. instance and uses the certificates within for verification purposes.
  1006. """
  1007. self._load_verify_directory_locations_capath(
  1008. tmpfile + NON_ASCII.encode(getfilesystemencoding())
  1009. )
  1010. def test_load_verify_directory_unicode_capath(self, tmpfile):
  1011. """
  1012. `Context.load_verify_locations` accepts a directory name as a `unicode`
  1013. instance and uses the certificates within for verification purposes.
  1014. """
  1015. self._load_verify_directory_locations_capath(
  1016. tmpfile.decode(getfilesystemencoding()) + NON_ASCII
  1017. )
  1018. def test_load_verify_locations_wrong_args(self):
  1019. """
  1020. `Context.load_verify_locations` raises `TypeError` if with non-`str`
  1021. arguments.
  1022. """
  1023. context = Context(SSLv23_METHOD)
  1024. with pytest.raises(TypeError):
  1025. context.load_verify_locations(object())
  1026. with pytest.raises(TypeError):
  1027. context.load_verify_locations(object(), object())
  1028. @pytest.mark.skipif(
  1029. not platform.startswith("linux"),
  1030. reason="Loading fallback paths is a linux-specific behavior to "
  1031. "accommodate pyca/cryptography manylinux1 wheels",
  1032. )
  1033. def test_fallback_default_verify_paths(self, monkeypatch):
  1034. """
  1035. Test that we load certificates successfully on linux from the fallback
  1036. path. To do this we set the _CRYPTOGRAPHY_MANYLINUX1_CA_FILE and
  1037. _CRYPTOGRAPHY_MANYLINUX1_CA_DIR vars to be equal to whatever the
  1038. current OpenSSL default is and we disable
  1039. SSL_CTX_SET_default_verify_paths so that it can't find certs unless
  1040. it loads via fallback.
  1041. """
  1042. context = Context(SSLv23_METHOD)
  1043. monkeypatch.setattr(
  1044. _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
  1045. )
  1046. monkeypatch.setattr(
  1047. SSL,
  1048. "_CRYPTOGRAPHY_MANYLINUX1_CA_FILE",
  1049. _ffi.string(_lib.X509_get_default_cert_file()),
  1050. )
  1051. monkeypatch.setattr(
  1052. SSL,
  1053. "_CRYPTOGRAPHY_MANYLINUX1_CA_DIR",
  1054. _ffi.string(_lib.X509_get_default_cert_dir()),
  1055. )
  1056. context.set_default_verify_paths()
  1057. store = context.get_cert_store()
  1058. sk_obj = _lib.X509_STORE_get0_objects(store._store)
  1059. assert sk_obj != _ffi.NULL
  1060. num = _lib.sk_X509_OBJECT_num(sk_obj)
  1061. assert num != 0
  1062. def test_check_env_vars(self, monkeypatch):
  1063. """
  1064. Test that we return True/False appropriately if the env vars are set.
  1065. """
  1066. context = Context(SSLv23_METHOD)
  1067. dir_var = "CUSTOM_DIR_VAR"
  1068. file_var = "CUSTOM_FILE_VAR"
  1069. assert context._check_env_vars_set(dir_var, file_var) is False
  1070. monkeypatch.setenv(dir_var, "value")
  1071. monkeypatch.setenv(file_var, "value")
  1072. assert context._check_env_vars_set(dir_var, file_var) is True
  1073. assert context._check_env_vars_set(dir_var, file_var) is True
  1074. def test_verify_no_fallback_if_env_vars_set(self, monkeypatch):
  1075. """
  1076. Test that we don't use the fallback path if env vars are set.
  1077. """
  1078. context = Context(SSLv23_METHOD)
  1079. monkeypatch.setattr(
  1080. _lib, "SSL_CTX_set_default_verify_paths", lambda x: 1
  1081. )
  1082. dir_env_var = _ffi.string(_lib.X509_get_default_cert_dir_env()).decode(
  1083. "ascii"
  1084. )
  1085. file_env_var = _ffi.string(
  1086. _lib.X509_get_default_cert_file_env()
  1087. ).decode("ascii")
  1088. monkeypatch.setenv(dir_env_var, "value")
  1089. monkeypatch.setenv(file_env_var, "value")
  1090. context.set_default_verify_paths()
  1091. monkeypatch.setattr(
  1092. context, "_fallback_default_verify_paths", raiser(SystemError)
  1093. )
  1094. context.set_default_verify_paths()
  1095. @pytest.mark.skipif(
  1096. platform == "win32",
  1097. reason="set_default_verify_paths appears not to work on Windows. "
  1098. "See LP#404343 and LP#404344.",
  1099. )
  1100. def _test_set_default_verify_paths(self):
  1101. """
  1102. `Context.set_default_verify_paths` causes the platform-specific CA
  1103. certificate locations to be used for verification purposes.
  1104. """
  1105. # Testing this requires a server with a certificate signed by one
  1106. # of the CAs in the platform CA location. Getting one of those
  1107. # costs money. Fortunately (or unfortunately, depending on your
  1108. # perspective), it's easy to think of a public server on the
  1109. # internet which has such a certificate. Connecting to the network
  1110. # in a unit test is bad, but it's the only way I can think of to
  1111. # really test this. -exarkun
  1112. context = Context(SSLv23_METHOD)
  1113. context.set_default_verify_paths()
  1114. context.set_verify(
  1115. VERIFY_PEER,
  1116. lambda conn, cert, errno, depth, preverify_ok: preverify_ok,
  1117. )
  1118. client = socket_any_family()
  1119. client.connect(("encrypted.google.com", 443))
  1120. clientSSL = Connection(context, client)
  1121. clientSSL.set_connect_state()
  1122. clientSSL.set_tlsext_host_name(b"encrypted.google.com")
  1123. clientSSL.do_handshake()
  1124. clientSSL.send(b"GET / HTTP/1.0\r\n\r\n")
  1125. assert clientSSL.recv(1024)
  1126. def test_fallback_path_is_not_file_or_dir(self):
  1127. """
  1128. Test that when passed empty arrays or paths that do not exist no
  1129. errors are raised.
  1130. """
  1131. context = Context(SSLv23_METHOD)
  1132. context._fallback_default_verify_paths([], [])
  1133. context._fallback_default_verify_paths(["/not/a/file"], ["/not/a/dir"])
  1134. def test_add_extra_chain_cert_invalid_cert(self):
  1135. """
  1136. `Context.add_extra_chain_cert` raises `TypeError` if called with an
  1137. object which is not an instance of `X509`.
  1138. """
  1139. context = Context(SSLv23_METHOD)
  1140. with pytest.raises(TypeError):
  1141. context.add_extra_chain_cert(object())
  1142. def _handshake_test(self, serverContext, clientContext):
  1143. """
  1144. Verify that a client and server created with the given contexts can
  1145. successfully handshake and communicate.
  1146. """
  1147. serverSocket, clientSocket = socket_pair()
  1148. server = Connection(serverContext, serverSocket)
  1149. server.set_accept_state()
  1150. client = Connection(clientContext, clientSocket)
  1151. client.set_connect_state()
  1152. # Make them talk to each other.
  1153. # interact_in_memory(client, server)
  1154. for _ in range(3):
  1155. for s in [client, server]:
  1156. try:
  1157. s.do_handshake()
  1158. except WantReadError:
  1159. pass
  1160. def test_set_verify_callback_connection_argument(self):
  1161. """
  1162. The first argument passed to the verify callback is the
  1163. `Connection` instance for which verification is taking place.
  1164. """
  1165. serverContext = Context(SSLv23_METHOD)
  1166. serverContext.use_privatekey(
  1167. load_privatekey(FILETYPE_PEM, root_key_pem)
  1168. )
  1169. serverContext.use_certificate(
  1170. load_certificate(FILETYPE_PEM, root_cert_pem)
  1171. )
  1172. serverConnection = Connection(serverContext, None)
  1173. class VerifyCallback(object):
  1174. def callback(self, connection, *args):
  1175. self.connection = connection
  1176. return 1
  1177. verify = VerifyCallback()
  1178. clientContext = Context(SSLv23_METHOD)
  1179. clientContext.set_verify(VERIFY_PEER, verify.callback)
  1180. clientConnection = Connection(clientContext, None)
  1181. clientConnection.set_connect_state()
  1182. handshake_in_memory(clientConnection, serverConnection)
  1183. assert verify.connection is clientConnection
  1184. def test_x509_in_verify_works(self):
  1185. """
  1186. We had a bug where the X509 cert instantiated in the callback wrapper
  1187. didn't __init__ so it was missing objects needed when calling
  1188. get_subject. This test sets up a handshake where we call get_subject
  1189. on the cert provided to the verify callback.
  1190. """
  1191. serverContext = Context(SSLv23_METHOD)
  1192. serverContext.use_privatekey(
  1193. load_privatekey(FILETYPE_PEM, root_key_pem)
  1194. )
  1195. serverContext.use_certificate(
  1196. load_certificate(FILETYPE_PEM, root_cert_pem)
  1197. )
  1198. serverConnection = Connection(serverContext, None)
  1199. def verify_cb_get_subject(conn, cert, errnum, depth, ok):
  1200. assert cert.get_subject()
  1201. return 1
  1202. clientContext = Context(SSLv23_METHOD)
  1203. clientContext.set_verify(VERIFY_PEER, verify_cb_get_subject)
  1204. clientConnection = Connection(clientContext, None)
  1205. clientConnection.set_connect_state()
  1206. handshake_in_memory(clientConnection, serverConnection)
  1207. def test_set_verify_callback_exception(self):
  1208. """
  1209. If the verify callback passed to `Context.set_verify` raises an
  1210. exception, verification fails and the exception is propagated to the
  1211. caller of `Connection.do_handshake`.
  1212. """
  1213. serverContext = Context(TLSv1_2_METHOD)
  1214. serverContext.use_privatekey(
  1215. load_privatekey(FILETYPE_PEM, root_key_pem)
  1216. )
  1217. serverContext.use_certificate(
  1218. load_certificate(FILETYPE_PEM, root_cert_pem)
  1219. )
  1220. clientContext = Context(TLSv1_2_METHOD)
  1221. def verify_callback(*args):
  1222. raise Exception("silly verify failure")
  1223. clientContext.set_verify(VERIFY_PEER, verify_callback)
  1224. with pytest.raises(Exception) as exc:
  1225. self._handshake_test(serverContext, clientContext)
  1226. assert "silly verify failure" == str(exc.value)
  1227. def test_set_verify_callback_reference(self):
  1228. """
  1229. If the verify callback passed to `Context.set_verify` is set multiple
  1230. times, the pointers to the old call functions should not be dangling
  1231. and trigger a segfault.
  1232. """
  1233. serverContext = Context(TLSv1_2_METHOD)
  1234. serverContext.use_privatekey(
  1235. load_privatekey(FILETYPE_PEM, root_key_pem)
  1236. )
  1237. serverContext.use_certificate(
  1238. load_certificate(FILETYPE_PEM, root_cert_pem)
  1239. )
  1240. clientContext = Context(TLSv1_2_METHOD)
  1241. clients = []
  1242. for i in range(5):
  1243. def verify_callback(*args):
  1244. return True
  1245. serverSocket, clientSocket = socket_pair()
  1246. client = Connection(clientContext, clientSocket)
  1247. clients.append((serverSocket, client))
  1248. clientContext.set_verify(VERIFY_PEER, verify_callback)
  1249. gc.collect()
  1250. # Make them talk to each other.
  1251. for serverSocket, client in clients:
  1252. server = Connection(serverContext, serverSocket)
  1253. server.set_accept_state()
  1254. client.set_connect_state()
  1255. for _ in range(5):
  1256. for s in [client, server]:
  1257. try:
  1258. s.do_handshake()
  1259. except WantReadError:
  1260. pass
  1261. @pytest.mark.parametrize("mode", [SSL.VERIFY_PEER, SSL.VERIFY_NONE])
  1262. def test_set_verify_default_callback(self, mode):
  1263. """
  1264. If the verify callback is omitted, the preverify value is used.
  1265. """
  1266. serverContext = Context(TLSv1_2_METHOD)
  1267. serverContext.use_privatekey(
  1268. load_privatekey(FILETYPE_PEM, root_key_pem)
  1269. )
  1270. serverContext.use_certificate(
  1271. load_certificate(FILETYPE_PEM, root_cert_pem)
  1272. )
  1273. clientContext = Context(TLSv1_2_METHOD)
  1274. clientContext.set_verify(mode, None)
  1275. if mode == SSL.VERIFY_PEER:
  1276. with pytest.raises(Exception) as exc:
  1277. self._handshake_test(serverContext, clientContext)
  1278. assert "certificate verify failed" in str(exc.value)
  1279. else:
  1280. self._handshake_test(serverContext, clientContext)
  1281. def test_add_extra_chain_cert(self, tmpdir):
  1282. """
  1283. `Context.add_extra_chain_cert` accepts an `X509`
  1284. instance to add to the certificate chain.
  1285. See `_create_certificate_chain` for the details of the
  1286. certificate chain tested.
  1287. The chain is tested by starting a server with scert and connecting
  1288. to it with a client which trusts cacert and requires verification to
  1289. succeed.
  1290. """
  1291. chain = _create_certificate_chain()
  1292. [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
  1293. # Dump the CA certificate to a file because that's the only way to load
  1294. # it as a trusted CA in the client context.
  1295. for cert, name in [
  1296. (cacert, "ca.pem"),
  1297. (icert, "i.pem"),
  1298. (scert, "s.pem"),
  1299. ]:
  1300. with tmpdir.join(name).open("w") as f:
  1301. f.write(dump_certificate(FILETYPE_PEM, cert).decode("ascii"))
  1302. for key, name in [(cakey, "ca.key"), (ikey, "i.key"), (skey, "s.key")]:
  1303. with tmpdir.join(name).open("w") as f:
  1304. f.write(dump_privatekey(FILETYPE_PEM, key).decode("ascii"))
  1305. # Create the server context
  1306. serverContext = Context(SSLv23_METHOD)
  1307. serverContext.use_privatekey(skey)
  1308. serverContext.use_certificate(scert)
  1309. # The client already has cacert, we only need to give them icert.
  1310. serverContext.add_extra_chain_cert(icert)
  1311. # Create the client
  1312. clientContext = Context(SSLv23_METHOD)
  1313. clientContext.set_verify(
  1314. VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb
  1315. )
  1316. clientContext.load_verify_locations(str(tmpdir.join("ca.pem")))
  1317. # Try it out.
  1318. self._handshake_test(serverContext, clientContext)
  1319. def _use_certificate_chain_file_test(self, certdir):
  1320. """
  1321. Verify that `Context.use_certificate_chain_file` reads a
  1322. certificate chain from a specified file.
  1323. The chain is tested by starting a server with scert and connecting to
  1324. it with a client which trusts cacert and requires verification to
  1325. succeed.
  1326. """
  1327. chain = _create_certificate_chain()
  1328. [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
  1329. makedirs(certdir)
  1330. chainFile = join_bytes_or_unicode(certdir, "chain.pem")
  1331. caFile = join_bytes_or_unicode(certdir, "ca.pem")
  1332. # Write out the chain file.
  1333. with open(chainFile, "wb") as fObj:
  1334. # Most specific to least general.
  1335. fObj.write(dump_certificate(FILETYPE_PEM, scert))
  1336. fObj.write(dump_certificate(FILETYPE_PEM, icert))
  1337. fObj.write(dump_certificate(FILETYPE_PEM, cacert))
  1338. with open(caFile, "w") as fObj:
  1339. fObj.write(dump_certificate(FILETYPE_PEM, cacert).decode("ascii"))
  1340. serverContext = Context(SSLv23_METHOD)
  1341. serverContext.use_certificate_chain_file(chainFile)
  1342. serverContext.use_privatekey(skey)
  1343. clientContext = Context(SSLv23_METHOD)
  1344. clientContext.set_verify(
  1345. VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb
  1346. )
  1347. clientContext.load_verify_locations(caFile)
  1348. self._handshake_test(serverContext, clientContext)
  1349. def test_use_certificate_chain_file_bytes(self, tmpfile):
  1350. """
  1351. ``Context.use_certificate_chain_file`` accepts the name of a file (as
  1352. an instance of ``bytes``) to specify additional certificates to use to
  1353. construct and verify a trust chain.
  1354. """
  1355. self._use_certificate_chain_file_test(
  1356. tmpfile + NON_ASCII.encode(getfilesystemencoding())
  1357. )
  1358. def test_use_certificate_chain_file_unicode(self, tmpfile):
  1359. """
  1360. ``Context.use_certificate_chain_file`` accepts the name of a file (as
  1361. an instance of ``unicode``) to specify additional certificates to use
  1362. to construct and verify a trust chain.
  1363. """
  1364. self._use_certificate_chain_file_test(
  1365. tmpfile.decode(getfilesystemencoding()) + NON_ASCII
  1366. )
  1367. def test_use_certificate_chain_file_wrong_args(self):
  1368. """
  1369. `Context.use_certificate_chain_file` raises `TypeError` if passed a
  1370. non-byte string single argument.
  1371. """
  1372. context = Context(SSLv23_METHOD)
  1373. with pytest.raises(TypeError):
  1374. context.use_certificate_chain_file(object())
  1375. def test_use_certificate_chain_file_missing_file(self, tmpfile):
  1376. """
  1377. `Context.use_certificate_chain_file` raises `OpenSSL.SSL.Error` when
  1378. passed a bad chain file name (for example, the name of a file which
  1379. does not exist).
  1380. """
  1381. context = Context(SSLv23_METHOD)
  1382. with pytest.raises(Error):
  1383. context.use_certificate_chain_file(tmpfile)
  1384. def test_set_verify_mode(self):
  1385. """
  1386. `Context.get_verify_mode` returns the verify mode flags previously
  1387. passed to `Context.set_verify`.
  1388. """
  1389. context = Context(SSLv23_METHOD)
  1390. assert context.get_verify_mode() == 0
  1391. context.set_verify(VERIFY_PEER | VERIFY_CLIENT_ONCE)
  1392. assert context.get_verify_mode() == (VERIFY_PEER | VERIFY_CLIENT_ONCE)
  1393. @pytest.mark.parametrize("mode", [None, 1.0, object(), "mode"])
  1394. def test_set_verify_wrong_mode_arg(self, mode):
  1395. """
  1396. `Context.set_verify` raises `TypeError` if the first argument is
  1397. not an integer.
  1398. """
  1399. context = Context(SSLv23_METHOD)
  1400. with pytest.raises(TypeError):
  1401. context.set_verify(mode=mode)
  1402. @pytest.mark.parametrize("callback", [1.0, "mode", ("foo", "bar")])
  1403. def test_set_verify_wrong_callable_arg(self, callback):
  1404. """
  1405. `Context.set_verify` raises `TypeError` if the second argument
  1406. is not callable.
  1407. """
  1408. context = Context(SSLv23_METHOD)
  1409. with pytest.raises(TypeError):
  1410. context.set_verify(mode=VERIFY_PEER, callback=callback)
  1411. def test_load_tmp_dh_wrong_args(self):
  1412. """
  1413. `Context.load_tmp_dh` raises `TypeError` if called with a
  1414. non-`str` argument.
  1415. """
  1416. context = Context(SSLv23_METHOD)
  1417. with pytest.raises(TypeError):
  1418. context.load_tmp_dh(object())
  1419. def test_load_tmp_dh_missing_file(self):
  1420. """
  1421. `Context.load_tmp_dh` raises `OpenSSL.SSL.Error` if the
  1422. specified file does not exist.
  1423. """
  1424. context = Context(SSLv23_METHOD)
  1425. with pytest.raises(Error):
  1426. context.load_tmp_dh(b"hello")
  1427. def _load_tmp_dh_test(self, dhfilename):
  1428. """
  1429. Verify that calling ``Context.load_tmp_dh`` with the given filename
  1430. does not raise an exception.
  1431. """
  1432. context = Context(SSLv23_METHOD)
  1433. with open(dhfilename, "w") as dhfile:
  1434. dhfile.write(dhparam)
  1435. context.load_tmp_dh(dhfilename)
  1436. def test_load_tmp_dh_bytes(self, tmpfile):
  1437. """
  1438. `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
  1439. specified file (given as ``bytes``).
  1440. """
  1441. self._load_tmp_dh_test(
  1442. tmpfile + NON_ASCII.encode(getfilesystemencoding()),
  1443. )
  1444. def test_load_tmp_dh_unicode(self, tmpfile):
  1445. """
  1446. `Context.load_tmp_dh` loads Diffie-Hellman parameters from the
  1447. specified file (given as ``unicode``).
  1448. """
  1449. self._load_tmp_dh_test(
  1450. tmpfile.decode(getfilesystemencoding()) + NON_ASCII,
  1451. )
  1452. def test_set_tmp_ecdh(self):
  1453. """
  1454. `Context.set_tmp_ecdh` sets the elliptic curve for Diffie-Hellman to
  1455. the specified curve.
  1456. """
  1457. context = Context(SSLv23_METHOD)
  1458. for curve in get_elliptic_curves():
  1459. if curve.name.startswith(u"Oakley-"):
  1460. # Setting Oakley-EC2N-4 and Oakley-EC2N-3 adds
  1461. # ('bignum routines', 'BN_mod_inverse', 'no inverse') to the
  1462. # error queue on OpenSSL 1.0.2.
  1463. continue
  1464. # The only easily "assertable" thing is that it does not raise an
  1465. # exception.
  1466. context.set_tmp_ecdh(curve)
  1467. def test_set_session_cache_mode_wrong_args(self):
  1468. """
  1469. `Context.set_session_cache_mode` raises `TypeError` if called with
  1470. a non-integer argument.
  1471. called with other than one integer argument.
  1472. """
  1473. context = Context(SSLv23_METHOD)
  1474. with pytest.raises(TypeError):
  1475. context.set_session_cache_mode(object())
  1476. def test_session_cache_mode(self):
  1477. """
  1478. `Context.set_session_cache_mode` specifies how sessions are cached.
  1479. The setting can be retrieved via `Context.get_session_cache_mode`.
  1480. """
  1481. context = Context(SSLv23_METHOD)
  1482. context.set_session_cache_mode(SESS_CACHE_OFF)
  1483. off = context.set_session_cache_mode(SESS_CACHE_BOTH)
  1484. assert SESS_CACHE_OFF == off
  1485. assert SESS_CACHE_BOTH == context.get_session_cache_mode()
  1486. def test_get_cert_store(self):
  1487. """
  1488. `Context.get_cert_store` returns a `X509Store` instance.
  1489. """
  1490. context = Context(SSLv23_METHOD)
  1491. store = context.get_cert_store()
  1492. assert isinstance(store, X509Store)
  1493. def test_set_tlsext_use_srtp_not_bytes(self):
  1494. """
  1495. `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
  1496. It raises a TypeError if the list of profiles is not a byte string.
  1497. """
  1498. context = Context(SSLv23_METHOD)
  1499. with pytest.raises(TypeError):
  1500. context.set_tlsext_use_srtp(text_type("SRTP_AES128_CM_SHA1_80"))
  1501. def test_set_tlsext_use_srtp_invalid_profile(self):
  1502. """
  1503. `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
  1504. It raises an Error if the call to OpenSSL fails.
  1505. """
  1506. context = Context(SSLv23_METHOD)
  1507. with pytest.raises(Error):
  1508. context.set_tlsext_use_srtp(b"SRTP_BOGUS")
  1509. def test_set_tlsext_use_srtp_valid(self):
  1510. """
  1511. `Context.set_tlsext_use_srtp' enables negotiating SRTP keying material.
  1512. It does not return anything.
  1513. """
  1514. context = Context(SSLv23_METHOD)
  1515. assert context.set_tlsext_use_srtp(b"SRTP_AES128_CM_SHA1_80") is None
  1516. class TestServerNameCallback(object):
  1517. """
  1518. Tests for `Context.set_tlsext_servername_callback` and its
  1519. interaction with `Connection`.
  1520. """
  1521. def test_old_callback_forgotten(self):
  1522. """
  1523. If `Context.set_tlsext_servername_callback` is used to specify
  1524. a new callback, the one it replaces is dereferenced.
  1525. """
  1526. def callback(connection): # pragma: no cover
  1527. pass
  1528. def replacement(connection): # pragma: no cover
  1529. pass
  1530. context = Context(SSLv23_METHOD)
  1531. context.set_tlsext_servername_callback(callback)
  1532. tracker = ref(callback)
  1533. del callback
  1534. context.set_tlsext_servername_callback(replacement)
  1535. # One run of the garbage collector happens to work on CPython. PyPy
  1536. # doesn't collect the underlying object until a second run for whatever
  1537. # reason. That's fine, it still demonstrates our code has properly
  1538. # dropped the reference.
  1539. collect()
  1540. collect()
  1541. callback = tracker()
  1542. if callback is not None:
  1543. referrers = get_referrers(callback)
  1544. if len(referrers) > 1: # pragma: nocover
  1545. pytest.fail("Some references remain: %r" % (referrers,))
  1546. def test_no_servername(self):
  1547. """
  1548. When a client specifies no server name, the callback passed to
  1549. `Context.set_tlsext_servername_callback` is invoked and the
  1550. result of `Connection.get_servername` is `None`.
  1551. """
  1552. args = []
  1553. def servername(conn):
  1554. args.append((conn, conn.get_servername()))
  1555. context = Context(SSLv23_METHOD)
  1556. context.set_tlsext_servername_callback(servername)
  1557. # Lose our reference to it. The Context is responsible for keeping it
  1558. # alive now.
  1559. del servername
  1560. collect()
  1561. # Necessary to actually accept the connection
  1562. context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  1563. context.use_certificate(
  1564. load_certificate(FILETYPE_PEM, server_cert_pem)
  1565. )
  1566. # Do a little connection to trigger the logic
  1567. server = Connection(context, None)
  1568. server.set_accept_state()
  1569. client = Connection(Context(SSLv23_METHOD), None)
  1570. client.set_connect_state()
  1571. interact_in_memory(server, client)
  1572. assert args == [(server, None)]
  1573. def test_servername(self):
  1574. """
  1575. When a client specifies a server name in its hello message, the
  1576. callback passed to `Contexts.set_tlsext_servername_callback` is
  1577. invoked and the result of `Connection.get_servername` is that
  1578. server name.
  1579. """
  1580. args = []
  1581. def servername(conn):
  1582. args.append((conn, conn.get_servername()))
  1583. context = Context(SSLv23_METHOD)
  1584. context.set_tlsext_servername_callback(servername)
  1585. # Necessary to actually accept the connection
  1586. context.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  1587. context.use_certificate(
  1588. load_certificate(FILETYPE_PEM, server_cert_pem)
  1589. )
  1590. # Do a little connection to trigger the logic
  1591. server = Connection(context, None)
  1592. server.set_accept_state()
  1593. client = Connection(Context(SSLv23_METHOD), None)
  1594. client.set_connect_state()
  1595. client.set_tlsext_host_name(b"foo1.example.com")
  1596. interact_in_memory(server, client)
  1597. assert args == [(server, b"foo1.example.com")]
  1598. class TestApplicationLayerProtoNegotiation(object):
  1599. """
  1600. Tests for ALPN in PyOpenSSL.
  1601. """
  1602. def test_alpn_success(self):
  1603. """
  1604. Clients and servers that agree on the negotiated ALPN protocol can
  1605. correct establish a connection, and the agreed protocol is reported
  1606. by the connections.
  1607. """
  1608. select_args = []
  1609. def select(conn, options):
  1610. select_args.append((conn, options))
  1611. return b"spdy/2"
  1612. client_context = Context(SSLv23_METHOD)
  1613. client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1614. server_context = Context(SSLv23_METHOD)
  1615. server_context.set_alpn_select_callback(select)
  1616. # Necessary to actually accept the connection
  1617. server_context.use_privatekey(
  1618. load_privatekey(FILETYPE_PEM, server_key_pem)
  1619. )
  1620. server_context.use_certificate(
  1621. load_certificate(FILETYPE_PEM, server_cert_pem)
  1622. )
  1623. # Do a little connection to trigger the logic
  1624. server = Connection(server_context, None)
  1625. server.set_accept_state()
  1626. client = Connection(client_context, None)
  1627. client.set_connect_state()
  1628. interact_in_memory(server, client)
  1629. assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
  1630. assert server.get_alpn_proto_negotiated() == b"spdy/2"
  1631. assert client.get_alpn_proto_negotiated() == b"spdy/2"
  1632. @pytest.mark.xfail(reason='https://github.com/pyca/pyopenssl/issues/1043')
  1633. def test_alpn_call_failure(self):
  1634. """
  1635. SSL_CTX_set_alpn_protos does not like to be called with an empty
  1636. protocols list. Ensure that we produce a user-visible error.
  1637. """
  1638. context = Context(SSLv23_METHOD)
  1639. with pytest.raises(Error):
  1640. context.set_alpn_protos([])
  1641. def test_alpn_set_on_connection(self):
  1642. """
  1643. The same as test_alpn_success, but setting the ALPN protocols on
  1644. the connection rather than the context.
  1645. """
  1646. select_args = []
  1647. def select(conn, options):
  1648. select_args.append((conn, options))
  1649. return b"spdy/2"
  1650. # Setup the client context but don't set any ALPN protocols.
  1651. client_context = Context(SSLv23_METHOD)
  1652. server_context = Context(SSLv23_METHOD)
  1653. server_context.set_alpn_select_callback(select)
  1654. # Necessary to actually accept the connection
  1655. server_context.use_privatekey(
  1656. load_privatekey(FILETYPE_PEM, server_key_pem)
  1657. )
  1658. server_context.use_certificate(
  1659. load_certificate(FILETYPE_PEM, server_cert_pem)
  1660. )
  1661. # Do a little connection to trigger the logic
  1662. server = Connection(server_context, None)
  1663. server.set_accept_state()
  1664. # Set the ALPN protocols on the client connection.
  1665. client = Connection(client_context, None)
  1666. client.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1667. client.set_connect_state()
  1668. interact_in_memory(server, client)
  1669. assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
  1670. assert server.get_alpn_proto_negotiated() == b"spdy/2"
  1671. assert client.get_alpn_proto_negotiated() == b"spdy/2"
  1672. def test_alpn_server_fail(self):
  1673. """
  1674. When clients and servers cannot agree on what protocol to use next
  1675. the TLS connection does not get established.
  1676. """
  1677. select_args = []
  1678. def select(conn, options):
  1679. select_args.append((conn, options))
  1680. return b""
  1681. client_context = Context(SSLv23_METHOD)
  1682. client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1683. server_context = Context(SSLv23_METHOD)
  1684. server_context.set_alpn_select_callback(select)
  1685. # Necessary to actually accept the connection
  1686. server_context.use_privatekey(
  1687. load_privatekey(FILETYPE_PEM, server_key_pem)
  1688. )
  1689. server_context.use_certificate(
  1690. load_certificate(FILETYPE_PEM, server_cert_pem)
  1691. )
  1692. # Do a little connection to trigger the logic
  1693. server = Connection(server_context, None)
  1694. server.set_accept_state()
  1695. client = Connection(client_context, None)
  1696. client.set_connect_state()
  1697. # If the client doesn't return anything, the connection will fail.
  1698. with pytest.raises(Error):
  1699. interact_in_memory(server, client)
  1700. assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
  1701. def test_alpn_no_server_overlap(self):
  1702. """
  1703. A server can allow a TLS handshake to complete without
  1704. agreeing to an application protocol by returning
  1705. ``NO_OVERLAPPING_PROTOCOLS``.
  1706. """
  1707. refusal_args = []
  1708. def refusal(conn, options):
  1709. refusal_args.append((conn, options))
  1710. return NO_OVERLAPPING_PROTOCOLS
  1711. client_context = Context(SSLv23_METHOD)
  1712. client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1713. server_context = Context(SSLv23_METHOD)
  1714. server_context.set_alpn_select_callback(refusal)
  1715. # Necessary to actually accept the connection
  1716. server_context.use_privatekey(
  1717. load_privatekey(FILETYPE_PEM, server_key_pem)
  1718. )
  1719. server_context.use_certificate(
  1720. load_certificate(FILETYPE_PEM, server_cert_pem)
  1721. )
  1722. # Do a little connection to trigger the logic
  1723. server = Connection(server_context, None)
  1724. server.set_accept_state()
  1725. client = Connection(client_context, None)
  1726. client.set_connect_state()
  1727. # Do the dance.
  1728. interact_in_memory(server, client)
  1729. assert refusal_args == [(server, [b"http/1.1", b"spdy/2"])]
  1730. assert client.get_alpn_proto_negotiated() == b""
  1731. def test_alpn_select_cb_returns_invalid_value(self):
  1732. """
  1733. If the ALPN selection callback returns anything other than
  1734. a bytestring or ``NO_OVERLAPPING_PROTOCOLS``, a
  1735. :py:exc:`TypeError` is raised.
  1736. """
  1737. invalid_cb_args = []
  1738. def invalid_cb(conn, options):
  1739. invalid_cb_args.append((conn, options))
  1740. return u"can't return unicode"
  1741. client_context = Context(SSLv23_METHOD)
  1742. client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1743. server_context = Context(SSLv23_METHOD)
  1744. server_context.set_alpn_select_callback(invalid_cb)
  1745. # Necessary to actually accept the connection
  1746. server_context.use_privatekey(
  1747. load_privatekey(FILETYPE_PEM, server_key_pem)
  1748. )
  1749. server_context.use_certificate(
  1750. load_certificate(FILETYPE_PEM, server_cert_pem)
  1751. )
  1752. # Do a little connection to trigger the logic
  1753. server = Connection(server_context, None)
  1754. server.set_accept_state()
  1755. client = Connection(client_context, None)
  1756. client.set_connect_state()
  1757. # Do the dance.
  1758. with pytest.raises(TypeError):
  1759. interact_in_memory(server, client)
  1760. assert invalid_cb_args == [(server, [b"http/1.1", b"spdy/2"])]
  1761. assert client.get_alpn_proto_negotiated() == b""
  1762. def test_alpn_no_server(self):
  1763. """
  1764. When clients and servers cannot agree on what protocol to use next
  1765. because the server doesn't offer ALPN, no protocol is negotiated.
  1766. """
  1767. client_context = Context(SSLv23_METHOD)
  1768. client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1769. server_context = Context(SSLv23_METHOD)
  1770. # Necessary to actually accept the connection
  1771. server_context.use_privatekey(
  1772. load_privatekey(FILETYPE_PEM, server_key_pem)
  1773. )
  1774. server_context.use_certificate(
  1775. load_certificate(FILETYPE_PEM, server_cert_pem)
  1776. )
  1777. # Do a little connection to trigger the logic
  1778. server = Connection(server_context, None)
  1779. server.set_accept_state()
  1780. client = Connection(client_context, None)
  1781. client.set_connect_state()
  1782. # Do the dance.
  1783. interact_in_memory(server, client)
  1784. assert client.get_alpn_proto_negotiated() == b""
  1785. def test_alpn_callback_exception(self):
  1786. """
  1787. We can handle exceptions in the ALPN select callback.
  1788. """
  1789. select_args = []
  1790. def select(conn, options):
  1791. select_args.append((conn, options))
  1792. raise TypeError()
  1793. client_context = Context(SSLv23_METHOD)
  1794. client_context.set_alpn_protos([b"http/1.1", b"spdy/2"])
  1795. server_context = Context(SSLv23_METHOD)
  1796. server_context.set_alpn_select_callback(select)
  1797. # Necessary to actually accept the connection
  1798. server_context.use_privatekey(
  1799. load_privatekey(FILETYPE_PEM, server_key_pem)
  1800. )
  1801. server_context.use_certificate(
  1802. load_certificate(FILETYPE_PEM, server_cert_pem)
  1803. )
  1804. # Do a little connection to trigger the logic
  1805. server = Connection(server_context, None)
  1806. server.set_accept_state()
  1807. client = Connection(client_context, None)
  1808. client.set_connect_state()
  1809. with pytest.raises(TypeError):
  1810. interact_in_memory(server, client)
  1811. assert select_args == [(server, [b"http/1.1", b"spdy/2"])]
  1812. class TestSession(object):
  1813. """
  1814. Unit tests for :py:obj:`OpenSSL.SSL.Session`.
  1815. """
  1816. def test_construction(self):
  1817. """
  1818. :py:class:`Session` can be constructed with no arguments, creating
  1819. a new instance of that type.
  1820. """
  1821. new_session = Session()
  1822. assert isinstance(new_session, Session)
  1823. class TestConnection(object):
  1824. """
  1825. Unit tests for `OpenSSL.SSL.Connection`.
  1826. """
  1827. # XXX get_peer_certificate -> None
  1828. # XXX sock_shutdown
  1829. # XXX master_key -> TypeError
  1830. # XXX server_random -> TypeError
  1831. # XXX connect -> TypeError
  1832. # XXX connect_ex -> TypeError
  1833. # XXX set_connect_state -> TypeError
  1834. # XXX set_accept_state -> TypeError
  1835. # XXX do_handshake -> TypeError
  1836. # XXX bio_read -> TypeError
  1837. # XXX recv -> TypeError
  1838. # XXX send -> TypeError
  1839. # XXX bio_write -> TypeError
  1840. def test_type(self):
  1841. """
  1842. `Connection` can be used to create instances of that type.
  1843. """
  1844. ctx = Context(SSLv23_METHOD)
  1845. assert is_consistent_type(Connection, "Connection", ctx, None)
  1846. @pytest.mark.parametrize("bad_context", [object(), "context", None, 1])
  1847. def test_wrong_args(self, bad_context):
  1848. """
  1849. `Connection.__init__` raises `TypeError` if called with a non-`Context`
  1850. instance argument.
  1851. """
  1852. with pytest.raises(TypeError):
  1853. Connection(bad_context)
  1854. @pytest.mark.parametrize("bad_bio", [object(), None, 1, [1, 2, 3]])
  1855. def test_bio_write_wrong_args(self, bad_bio):
  1856. """
  1857. `Connection.bio_write` raises `TypeError` if called with a non-bytes
  1858. (or text) argument.
  1859. """
  1860. context = Context(SSLv23_METHOD)
  1861. connection = Connection(context, None)
  1862. with pytest.raises(TypeError):
  1863. connection.bio_write(bad_bio)
  1864. def test_bio_write(self):
  1865. """
  1866. `Connection.bio_write` does not raise if called with bytes or
  1867. bytearray, warns if called with text.
  1868. """
  1869. context = Context(SSLv23_METHOD)
  1870. connection = Connection(context, None)
  1871. connection.bio_write(b"xy")
  1872. connection.bio_write(bytearray(b"za"))
  1873. with pytest.warns(DeprecationWarning):
  1874. connection.bio_write(u"deprecated")
  1875. def test_get_context(self):
  1876. """
  1877. `Connection.get_context` returns the `Context` instance used to
  1878. construct the `Connection` instance.
  1879. """
  1880. context = Context(SSLv23_METHOD)
  1881. connection = Connection(context, None)
  1882. assert connection.get_context() is context
  1883. def test_set_context_wrong_args(self):
  1884. """
  1885. `Connection.set_context` raises `TypeError` if called with a
  1886. non-`Context` instance argument.
  1887. """
  1888. ctx = Context(SSLv23_METHOD)
  1889. connection = Connection(ctx, None)
  1890. with pytest.raises(TypeError):
  1891. connection.set_context(object())
  1892. with pytest.raises(TypeError):
  1893. connection.set_context("hello")
  1894. with pytest.raises(TypeError):
  1895. connection.set_context(1)
  1896. assert ctx is connection.get_context()
  1897. def test_set_context(self):
  1898. """
  1899. `Connection.set_context` specifies a new `Context` instance to be
  1900. used for the connection.
  1901. """
  1902. original = Context(SSLv23_METHOD)
  1903. replacement = Context(SSLv23_METHOD)
  1904. connection = Connection(original, None)
  1905. connection.set_context(replacement)
  1906. assert replacement is connection.get_context()
  1907. # Lose our references to the contexts, just in case the Connection
  1908. # isn't properly managing its own contributions to their reference
  1909. # counts.
  1910. del original, replacement
  1911. collect()
  1912. def test_set_tlsext_host_name_wrong_args(self):
  1913. """
  1914. If `Connection.set_tlsext_host_name` is called with a non-byte string
  1915. argument or a byte string with an embedded NUL, `TypeError` is raised.
  1916. """
  1917. conn = Connection(Context(SSLv23_METHOD), None)
  1918. with pytest.raises(TypeError):
  1919. conn.set_tlsext_host_name(object())
  1920. with pytest.raises(TypeError):
  1921. conn.set_tlsext_host_name(b"with\0null")
  1922. if not PY2:
  1923. # On Python 3.x, don't accidentally implicitly convert from text.
  1924. with pytest.raises(TypeError):
  1925. conn.set_tlsext_host_name(b"example.com".decode("ascii"))
  1926. def test_pending(self):
  1927. """
  1928. `Connection.pending` returns the number of bytes available for
  1929. immediate read.
  1930. """
  1931. connection = Connection(Context(SSLv23_METHOD), None)
  1932. assert connection.pending() == 0
  1933. def test_peek(self):
  1934. """
  1935. `Connection.recv` peeks into the connection if `socket.MSG_PEEK` is
  1936. passed.
  1937. """
  1938. server, client = loopback()
  1939. server.send(b"xy")
  1940. assert client.recv(2, MSG_PEEK) == b"xy"
  1941. assert client.recv(2, MSG_PEEK) == b"xy"
  1942. assert client.recv(2) == b"xy"
  1943. def test_connect_wrong_args(self):
  1944. """
  1945. `Connection.connect` raises `TypeError` if called with a non-address
  1946. argument.
  1947. """
  1948. connection = Connection(Context(SSLv23_METHOD), socket_any_family())
  1949. with pytest.raises(TypeError):
  1950. connection.connect(None)
  1951. def test_connect_refused(self):
  1952. """
  1953. `Connection.connect` raises `socket.error` if the underlying socket
  1954. connect method raises it.
  1955. """
  1956. client = socket_any_family()
  1957. context = Context(SSLv23_METHOD)
  1958. clientSSL = Connection(context, client)
  1959. # pytest.raises here doesn't work because of a bug in py.test on Python
  1960. # 2.6: https://github.com/pytest-dev/pytest/issues/988
  1961. try:
  1962. clientSSL.connect((loopback_address(client), 1))
  1963. except error as e:
  1964. exc = e
  1965. assert exc.args[0] == ECONNREFUSED
  1966. def test_connect(self):
  1967. """
  1968. `Connection.connect` establishes a connection to the specified address.
  1969. """
  1970. port = socket_any_family()
  1971. port.bind(("", 0))
  1972. port.listen(3)
  1973. clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
  1974. clientSSL.connect((loopback_address(port), port.getsockname()[1]))
  1975. # XXX An assertion? Or something?
  1976. @pytest.mark.skipif(
  1977. platform == "darwin",
  1978. reason="connect_ex sometimes causes a kernel panic on OS X 10.6.4",
  1979. )
  1980. def test_connect_ex(self):
  1981. """
  1982. If there is a connection error, `Connection.connect_ex` returns the
  1983. errno instead of raising an exception.
  1984. """
  1985. port = socket_any_family()
  1986. port.bind(("", 0))
  1987. port.listen(3)
  1988. clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
  1989. clientSSL.setblocking(False)
  1990. result = clientSSL.connect_ex(port.getsockname())
  1991. expected = (EINPROGRESS, EWOULDBLOCK)
  1992. assert result in expected
  1993. def test_accept(self):
  1994. """
  1995. `Connection.accept` accepts a pending connection attempt and returns a
  1996. tuple of a new `Connection` (the accepted client) and the address the
  1997. connection originated from.
  1998. """
  1999. ctx = Context(SSLv23_METHOD)
  2000. ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  2001. ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
  2002. port = socket_any_family()
  2003. portSSL = Connection(ctx, port)
  2004. portSSL.bind(("", 0))
  2005. portSSL.listen(3)
  2006. clientSSL = Connection(Context(SSLv23_METHOD), socket(port.family))
  2007. # Calling portSSL.getsockname() here to get the server IP address
  2008. # sounds great, but frequently fails on Windows.
  2009. clientSSL.connect((loopback_address(port), portSSL.getsockname()[1]))
  2010. serverSSL, address = portSSL.accept()
  2011. assert isinstance(serverSSL, Connection)
  2012. assert serverSSL.get_context() is ctx
  2013. assert address == clientSSL.getsockname()
  2014. def test_shutdown_wrong_args(self):
  2015. """
  2016. `Connection.set_shutdown` raises `TypeError` if called with arguments
  2017. other than integers.
  2018. """
  2019. connection = Connection(Context(SSLv23_METHOD), None)
  2020. with pytest.raises(TypeError):
  2021. connection.set_shutdown(None)
  2022. def test_shutdown(self):
  2023. """
  2024. `Connection.shutdown` performs an SSL-level connection shutdown.
  2025. """
  2026. server, client = loopback()
  2027. assert not server.shutdown()
  2028. assert server.get_shutdown() == SENT_SHUTDOWN
  2029. with pytest.raises(ZeroReturnError):
  2030. client.recv(1024)
  2031. assert client.get_shutdown() == RECEIVED_SHUTDOWN
  2032. client.shutdown()
  2033. assert client.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
  2034. with pytest.raises(ZeroReturnError):
  2035. server.recv(1024)
  2036. assert server.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)
  2037. def test_shutdown_closed(self):
  2038. """
  2039. If the underlying socket is closed, `Connection.shutdown` propagates
  2040. the write error from the low level write call.
  2041. """
  2042. server, client = loopback()
  2043. server.sock_shutdown(2)
  2044. with pytest.raises(SysCallError) as exc:
  2045. server.shutdown()
  2046. if platform == "win32":
  2047. assert exc.value.args[0] == ESHUTDOWN
  2048. else:
  2049. assert exc.value.args[0] == EPIPE
  2050. def test_shutdown_truncated(self):
  2051. """
  2052. If the underlying connection is truncated, `Connection.shutdown`
  2053. raises an `Error`.
  2054. """
  2055. server_ctx = Context(SSLv23_METHOD)
  2056. client_ctx = Context(SSLv23_METHOD)
  2057. server_ctx.use_privatekey(
  2058. load_privatekey(FILETYPE_PEM, server_key_pem)
  2059. )
  2060. server_ctx.use_certificate(
  2061. load_certificate(FILETYPE_PEM, server_cert_pem)
  2062. )
  2063. server = Connection(server_ctx, None)
  2064. client = Connection(client_ctx, None)
  2065. handshake_in_memory(client, server)
  2066. assert not server.shutdown()
  2067. with pytest.raises(WantReadError):
  2068. server.shutdown()
  2069. server.bio_shutdown()
  2070. with pytest.raises(Error):
  2071. server.shutdown()
  2072. def test_set_shutdown(self):
  2073. """
  2074. `Connection.set_shutdown` sets the state of the SSL connection
  2075. shutdown process.
  2076. """
  2077. connection = Connection(Context(SSLv23_METHOD), socket_any_family())
  2078. connection.set_shutdown(RECEIVED_SHUTDOWN)
  2079. assert connection.get_shutdown() == RECEIVED_SHUTDOWN
  2080. def test_state_string(self):
  2081. """
  2082. `Connection.state_string` verbosely describes the current state of
  2083. the `Connection`.
  2084. """
  2085. server, client = socket_pair()
  2086. server = loopback_server_factory(server)
  2087. client = loopback_client_factory(client)
  2088. assert server.get_state_string() in [
  2089. b"before/accept initialization",
  2090. b"before SSL initialization",
  2091. ]
  2092. assert client.get_state_string() in [
  2093. b"before/connect initialization",
  2094. b"before SSL initialization",
  2095. ]
  2096. def test_app_data(self):
  2097. """
  2098. Any object can be set as app data by passing it to
  2099. `Connection.set_app_data` and later retrieved with
  2100. `Connection.get_app_data`.
  2101. """
  2102. conn = Connection(Context(SSLv23_METHOD), None)
  2103. assert None is conn.get_app_data()
  2104. app_data = object()
  2105. conn.set_app_data(app_data)
  2106. assert conn.get_app_data() is app_data
  2107. def test_makefile(self):
  2108. """
  2109. `Connection.makefile` is not implemented and calling that
  2110. method raises `NotImplementedError`.
  2111. """
  2112. conn = Connection(Context(SSLv23_METHOD), None)
  2113. with pytest.raises(NotImplementedError):
  2114. conn.makefile()
  2115. def test_get_certificate(self):
  2116. """
  2117. `Connection.get_certificate` returns the local certificate.
  2118. """
  2119. chain = _create_certificate_chain()
  2120. [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
  2121. context = Context(SSLv23_METHOD)
  2122. context.use_certificate(scert)
  2123. client = Connection(context, None)
  2124. cert = client.get_certificate()
  2125. assert cert is not None
  2126. assert "Server Certificate" == cert.get_subject().CN
  2127. def test_get_certificate_none(self):
  2128. """
  2129. `Connection.get_certificate` returns the local certificate.
  2130. If there is no certificate, it returns None.
  2131. """
  2132. context = Context(SSLv23_METHOD)
  2133. client = Connection(context, None)
  2134. cert = client.get_certificate()
  2135. assert cert is None
  2136. def test_get_peer_cert_chain(self):
  2137. """
  2138. `Connection.get_peer_cert_chain` returns a list of certificates
  2139. which the connected server returned for the certification verification.
  2140. """
  2141. chain = _create_certificate_chain()
  2142. [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
  2143. serverContext = Context(SSLv23_METHOD)
  2144. serverContext.use_privatekey(skey)
  2145. serverContext.use_certificate(scert)
  2146. serverContext.add_extra_chain_cert(icert)
  2147. serverContext.add_extra_chain_cert(cacert)
  2148. server = Connection(serverContext, None)
  2149. server.set_accept_state()
  2150. # Create the client
  2151. clientContext = Context(SSLv23_METHOD)
  2152. clientContext.set_verify(VERIFY_NONE, verify_cb)
  2153. client = Connection(clientContext, None)
  2154. client.set_connect_state()
  2155. interact_in_memory(client, server)
  2156. chain = client.get_peer_cert_chain()
  2157. assert len(chain) == 3
  2158. assert "Server Certificate" == chain[0].get_subject().CN
  2159. assert "Intermediate Certificate" == chain[1].get_subject().CN
  2160. assert "Authority Certificate" == chain[2].get_subject().CN
  2161. def test_get_peer_cert_chain_none(self):
  2162. """
  2163. `Connection.get_peer_cert_chain` returns `None` if the peer sends
  2164. no certificate chain.
  2165. """
  2166. ctx = Context(SSLv23_METHOD)
  2167. ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  2168. ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
  2169. server = Connection(ctx, None)
  2170. server.set_accept_state()
  2171. client = Connection(Context(SSLv23_METHOD), None)
  2172. client.set_connect_state()
  2173. interact_in_memory(client, server)
  2174. assert None is server.get_peer_cert_chain()
  2175. def test_get_verified_chain(self):
  2176. """
  2177. `Connection.get_verified_chain` returns a list of certificates
  2178. which the connected server returned for the certification verification.
  2179. """
  2180. chain = _create_certificate_chain()
  2181. [(cakey, cacert), (ikey, icert), (skey, scert)] = chain
  2182. serverContext = Context(SSLv23_METHOD)
  2183. serverContext.use_privatekey(skey)
  2184. serverContext.use_certificate(scert)
  2185. serverContext.add_extra_chain_cert(icert)
  2186. serverContext.add_extra_chain_cert(cacert)
  2187. server = Connection(serverContext, None)
  2188. server.set_accept_state()
  2189. # Create the client
  2190. clientContext = Context(SSLv23_METHOD)
  2191. # cacert is self-signed so the client must trust it for verification
  2192. # to succeed.
  2193. clientContext.get_cert_store().add_cert(cacert)
  2194. clientContext.set_verify(VERIFY_PEER, verify_cb)
  2195. client = Connection(clientContext, None)
  2196. client.set_connect_state()
  2197. interact_in_memory(client, server)
  2198. chain = client.get_verified_chain()
  2199. assert len(chain) == 3
  2200. assert "Server Certificate" == chain[0].get_subject().CN
  2201. assert "Intermediate Certificate" == chain[1].get_subject().CN
  2202. assert "Authority Certificate" == chain[2].get_subject().CN
  2203. def test_get_verified_chain_none(self):
  2204. """
  2205. `Connection.get_verified_chain` returns `None` if the peer sends
  2206. no certificate chain.
  2207. """
  2208. ctx = Context(SSLv23_METHOD)
  2209. ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  2210. ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
  2211. server = Connection(ctx, None)
  2212. server.set_accept_state()
  2213. client = Connection(Context(SSLv23_METHOD), None)
  2214. client.set_connect_state()
  2215. interact_in_memory(client, server)
  2216. assert None is server.get_verified_chain()
  2217. def test_get_verified_chain_unconnected(self):
  2218. """
  2219. `Connection.get_verified_chain` returns `None` when used with an object
  2220. which has not been connected.
  2221. """
  2222. ctx = Context(SSLv23_METHOD)
  2223. server = Connection(ctx, None)
  2224. assert None is server.get_verified_chain()
  2225. def test_get_session_unconnected(self):
  2226. """
  2227. `Connection.get_session` returns `None` when used with an object
  2228. which has not been connected.
  2229. """
  2230. ctx = Context(SSLv23_METHOD)
  2231. server = Connection(ctx, None)
  2232. session = server.get_session()
  2233. assert None is session
  2234. def test_server_get_session(self):
  2235. """
  2236. On the server side of a connection, `Connection.get_session` returns a
  2237. `Session` instance representing the SSL session for that connection.
  2238. """
  2239. server, client = loopback()
  2240. session = server.get_session()
  2241. assert isinstance(session, Session)
  2242. def test_client_get_session(self):
  2243. """
  2244. On the client side of a connection, `Connection.get_session`
  2245. returns a `Session` instance representing the SSL session for
  2246. that connection.
  2247. """
  2248. server, client = loopback()
  2249. session = client.get_session()
  2250. assert isinstance(session, Session)
  2251. def test_set_session_wrong_args(self):
  2252. """
  2253. `Connection.set_session` raises `TypeError` if called with an object
  2254. that is not an instance of `Session`.
  2255. """
  2256. ctx = Context(SSLv23_METHOD)
  2257. connection = Connection(ctx, None)
  2258. with pytest.raises(TypeError):
  2259. connection.set_session(123)
  2260. with pytest.raises(TypeError):
  2261. connection.set_session("hello")
  2262. with pytest.raises(TypeError):
  2263. connection.set_session(object())
  2264. def test_client_set_session(self):
  2265. """
  2266. `Connection.set_session`, when used prior to a connection being
  2267. established, accepts a `Session` instance and causes an attempt to
  2268. re-use the session it represents when the SSL handshake is performed.
  2269. """
  2270. key = load_privatekey(FILETYPE_PEM, server_key_pem)
  2271. cert = load_certificate(FILETYPE_PEM, server_cert_pem)
  2272. ctx = Context(TLSv1_2_METHOD)
  2273. ctx.use_privatekey(key)
  2274. ctx.use_certificate(cert)
  2275. ctx.set_session_id("unity-test")
  2276. def makeServer(socket):
  2277. server = Connection(ctx, socket)
  2278. server.set_accept_state()
  2279. return server
  2280. originalServer, originalClient = loopback(server_factory=makeServer)
  2281. originalSession = originalClient.get_session()
  2282. def makeClient(socket):
  2283. client = loopback_client_factory(socket)
  2284. client.set_session(originalSession)
  2285. return client
  2286. resumedServer, resumedClient = loopback(
  2287. server_factory=makeServer, client_factory=makeClient
  2288. )
  2289. # This is a proxy: in general, we have no access to any unique
  2290. # identifier for the session (new enough versions of OpenSSL expose
  2291. # a hash which could be usable, but "new enough" is very, very new).
  2292. # Instead, exploit the fact that the master key is re-used if the
  2293. # session is re-used. As long as the master key for the two
  2294. # connections is the same, the session was re-used!
  2295. assert originalServer.master_key() == resumedServer.master_key()
  2296. def test_set_session_wrong_method(self):
  2297. """
  2298. If `Connection.set_session` is passed a `Session` instance associated
  2299. with a context using a different SSL method than the `Connection`
  2300. is using, a `OpenSSL.SSL.Error` is raised.
  2301. """
  2302. v1 = TLSv1_2_METHOD
  2303. v2 = TLSv1_METHOD
  2304. key = load_privatekey(FILETYPE_PEM, server_key_pem)
  2305. cert = load_certificate(FILETYPE_PEM, server_cert_pem)
  2306. ctx = Context(v1)
  2307. ctx.use_privatekey(key)
  2308. ctx.use_certificate(cert)
  2309. ctx.set_session_id(b"unity-test")
  2310. def makeServer(socket):
  2311. server = Connection(ctx, socket)
  2312. server.set_accept_state()
  2313. return server
  2314. def makeOriginalClient(socket):
  2315. client = Connection(Context(v1), socket)
  2316. client.set_connect_state()
  2317. return client
  2318. originalServer, originalClient = loopback(
  2319. server_factory=makeServer, client_factory=makeOriginalClient
  2320. )
  2321. originalSession = originalClient.get_session()
  2322. def makeClient(socket):
  2323. # Intentionally use a different, incompatible method here.
  2324. client = Connection(Context(v2), socket)
  2325. client.set_connect_state()
  2326. client.set_session(originalSession)
  2327. return client
  2328. with pytest.raises(Error):
  2329. loopback(client_factory=makeClient, server_factory=makeServer)
  2330. def test_wantWriteError(self):
  2331. """
  2332. `Connection` methods which generate output raise
  2333. `OpenSSL.SSL.WantWriteError` if writing to the connection's BIO
  2334. fail indicating a should-write state.
  2335. """
  2336. client_socket, server_socket = socket_pair()
  2337. # Fill up the client's send buffer so Connection won't be able to write
  2338. # anything. Only write a single byte at a time so we can be sure we
  2339. # completely fill the buffer. Even though the socket API is allowed to
  2340. # signal a short write via its return value it seems this doesn't
  2341. # always happen on all platforms (FreeBSD and OS X particular) for the
  2342. # very last bit of available buffer space.
  2343. msg = b"x"
  2344. for i in range(1024 * 1024 * 64):
  2345. try:
  2346. client_socket.send(msg)
  2347. except error as e:
  2348. if e.errno == EWOULDBLOCK:
  2349. break
  2350. raise
  2351. else:
  2352. pytest.fail(
  2353. "Failed to fill socket buffer, cannot test BIO want write"
  2354. )
  2355. ctx = Context(SSLv23_METHOD)
  2356. conn = Connection(ctx, client_socket)
  2357. # Client's speak first, so make it an SSL client
  2358. conn.set_connect_state()
  2359. with pytest.raises(WantWriteError):
  2360. conn.do_handshake()
  2361. # XXX want_read
  2362. def test_get_finished_before_connect(self):
  2363. """
  2364. `Connection.get_finished` returns `None` before TLS handshake
  2365. is completed.
  2366. """
  2367. ctx = Context(SSLv23_METHOD)
  2368. connection = Connection(ctx, None)
  2369. assert connection.get_finished() is None
  2370. def test_get_peer_finished_before_connect(self):
  2371. """
  2372. `Connection.get_peer_finished` returns `None` before TLS handshake
  2373. is completed.
  2374. """
  2375. ctx = Context(SSLv23_METHOD)
  2376. connection = Connection(ctx, None)
  2377. assert connection.get_peer_finished() is None
  2378. def test_get_finished(self):
  2379. """
  2380. `Connection.get_finished` method returns the TLS Finished message send
  2381. from client, or server. Finished messages are send during
  2382. TLS handshake.
  2383. """
  2384. server, client = loopback()
  2385. assert server.get_finished() is not None
  2386. assert len(server.get_finished()) > 0
  2387. def test_get_peer_finished(self):
  2388. """
  2389. `Connection.get_peer_finished` method returns the TLS Finished
  2390. message received from client, or server. Finished messages are send
  2391. during TLS handshake.
  2392. """
  2393. server, client = loopback()
  2394. assert server.get_peer_finished() is not None
  2395. assert len(server.get_peer_finished()) > 0
  2396. def test_tls_finished_message_symmetry(self):
  2397. """
  2398. The TLS Finished message send by server must be the TLS Finished
  2399. message received by client.
  2400. The TLS Finished message send by client must be the TLS Finished
  2401. message received by server.
  2402. """
  2403. server, client = loopback()
  2404. assert server.get_finished() == client.get_peer_finished()
  2405. assert client.get_finished() == server.get_peer_finished()
  2406. def test_get_cipher_name_before_connect(self):
  2407. """
  2408. `Connection.get_cipher_name` returns `None` if no connection
  2409. has been established.
  2410. """
  2411. ctx = Context(SSLv23_METHOD)
  2412. conn = Connection(ctx, None)
  2413. assert conn.get_cipher_name() is None
  2414. def test_get_cipher_name(self):
  2415. """
  2416. `Connection.get_cipher_name` returns a `unicode` string giving the
  2417. name of the currently used cipher.
  2418. """
  2419. server, client = loopback()
  2420. server_cipher_name, client_cipher_name = (
  2421. server.get_cipher_name(),
  2422. client.get_cipher_name(),
  2423. )
  2424. assert isinstance(server_cipher_name, text_type)
  2425. assert isinstance(client_cipher_name, text_type)
  2426. assert server_cipher_name == client_cipher_name
  2427. def test_get_cipher_version_before_connect(self):
  2428. """
  2429. `Connection.get_cipher_version` returns `None` if no connection
  2430. has been established.
  2431. """
  2432. ctx = Context(SSLv23_METHOD)
  2433. conn = Connection(ctx, None)
  2434. assert conn.get_cipher_version() is None
  2435. def test_get_cipher_version(self):
  2436. """
  2437. `Connection.get_cipher_version` returns a `unicode` string giving
  2438. the protocol name of the currently used cipher.
  2439. """
  2440. server, client = loopback()
  2441. server_cipher_version, client_cipher_version = (
  2442. server.get_cipher_version(),
  2443. client.get_cipher_version(),
  2444. )
  2445. assert isinstance(server_cipher_version, text_type)
  2446. assert isinstance(client_cipher_version, text_type)
  2447. assert server_cipher_version == client_cipher_version
  2448. def test_get_cipher_bits_before_connect(self):
  2449. """
  2450. `Connection.get_cipher_bits` returns `None` if no connection has
  2451. been established.
  2452. """
  2453. ctx = Context(SSLv23_METHOD)
  2454. conn = Connection(ctx, None)
  2455. assert conn.get_cipher_bits() is None
  2456. def test_get_cipher_bits(self):
  2457. """
  2458. `Connection.get_cipher_bits` returns the number of secret bits
  2459. of the currently used cipher.
  2460. """
  2461. server, client = loopback()
  2462. server_cipher_bits, client_cipher_bits = (
  2463. server.get_cipher_bits(),
  2464. client.get_cipher_bits(),
  2465. )
  2466. assert isinstance(server_cipher_bits, int)
  2467. assert isinstance(client_cipher_bits, int)
  2468. assert server_cipher_bits == client_cipher_bits
  2469. def test_get_protocol_version_name(self):
  2470. """
  2471. `Connection.get_protocol_version_name()` returns a string giving the
  2472. protocol version of the current connection.
  2473. """
  2474. server, client = loopback()
  2475. client_protocol_version_name = client.get_protocol_version_name()
  2476. server_protocol_version_name = server.get_protocol_version_name()
  2477. assert isinstance(server_protocol_version_name, text_type)
  2478. assert isinstance(client_protocol_version_name, text_type)
  2479. assert server_protocol_version_name == client_protocol_version_name
  2480. def test_get_protocol_version(self):
  2481. """
  2482. `Connection.get_protocol_version()` returns an integer
  2483. giving the protocol version of the current connection.
  2484. """
  2485. server, client = loopback()
  2486. client_protocol_version = client.get_protocol_version()
  2487. server_protocol_version = server.get_protocol_version()
  2488. assert isinstance(server_protocol_version, int)
  2489. assert isinstance(client_protocol_version, int)
  2490. assert server_protocol_version == client_protocol_version
  2491. def test_wantReadError(self):
  2492. """
  2493. `Connection.bio_read` raises `OpenSSL.SSL.WantReadError` if there are
  2494. no bytes available to be read from the BIO.
  2495. """
  2496. ctx = Context(SSLv23_METHOD)
  2497. conn = Connection(ctx, None)
  2498. with pytest.raises(WantReadError):
  2499. conn.bio_read(1024)
  2500. @pytest.mark.parametrize("bufsize", [1.0, None, object(), "bufsize"])
  2501. def test_bio_read_wrong_args(self, bufsize):
  2502. """
  2503. `Connection.bio_read` raises `TypeError` if passed a non-integer
  2504. argument.
  2505. """
  2506. ctx = Context(SSLv23_METHOD)
  2507. conn = Connection(ctx, None)
  2508. with pytest.raises(TypeError):
  2509. conn.bio_read(bufsize)
  2510. def test_buffer_size(self):
  2511. """
  2512. `Connection.bio_read` accepts an integer giving the maximum number
  2513. of bytes to read and return.
  2514. """
  2515. ctx = Context(SSLv23_METHOD)
  2516. conn = Connection(ctx, None)
  2517. conn.set_connect_state()
  2518. try:
  2519. conn.do_handshake()
  2520. except WantReadError:
  2521. pass
  2522. data = conn.bio_read(2)
  2523. assert 2 == len(data)
  2524. class TestConnectionGetCipherList(object):
  2525. """
  2526. Tests for `Connection.get_cipher_list`.
  2527. """
  2528. def test_result(self):
  2529. """
  2530. `Connection.get_cipher_list` returns a list of `bytes` giving the
  2531. names of the ciphers which might be used.
  2532. """
  2533. connection = Connection(Context(SSLv23_METHOD), None)
  2534. ciphers = connection.get_cipher_list()
  2535. assert isinstance(ciphers, list)
  2536. for cipher in ciphers:
  2537. assert isinstance(cipher, str)
  2538. class VeryLarge(bytes):
  2539. """
  2540. Mock object so that we don't have to allocate 2**31 bytes
  2541. """
  2542. def __len__(self):
  2543. return 2 ** 31
  2544. class TestConnectionSend(object):
  2545. """
  2546. Tests for `Connection.send`.
  2547. """
  2548. def test_wrong_args(self):
  2549. """
  2550. When called with arguments other than string argument for its first
  2551. parameter, `Connection.send` raises `TypeError`.
  2552. """
  2553. connection = Connection(Context(SSLv23_METHOD), None)
  2554. with pytest.raises(TypeError):
  2555. connection.send(object())
  2556. with pytest.raises(TypeError):
  2557. connection.send([1, 2, 3])
  2558. def test_short_bytes(self):
  2559. """
  2560. When passed a short byte string, `Connection.send` transmits all of it
  2561. and returns the number of bytes sent.
  2562. """
  2563. server, client = loopback()
  2564. count = server.send(b"xy")
  2565. assert count == 2
  2566. assert client.recv(2) == b"xy"
  2567. def test_text(self):
  2568. """
  2569. When passed a text, `Connection.send` transmits all of it and
  2570. returns the number of bytes sent. It also raises a DeprecationWarning.
  2571. """
  2572. server, client = loopback()
  2573. with pytest.warns(DeprecationWarning) as w:
  2574. simplefilter("always")
  2575. count = server.send(b"xy".decode("ascii"))
  2576. assert "{0} for buf is no longer accepted, use bytes".format(
  2577. WARNING_TYPE_EXPECTED
  2578. ) == str(w[-1].message)
  2579. assert count == 2
  2580. assert client.recv(2) == b"xy"
  2581. def test_short_memoryview(self):
  2582. """
  2583. When passed a memoryview onto a small number of bytes,
  2584. `Connection.send` transmits all of them and returns the number
  2585. of bytes sent.
  2586. """
  2587. server, client = loopback()
  2588. count = server.send(memoryview(b"xy"))
  2589. assert count == 2
  2590. assert client.recv(2) == b"xy"
  2591. def test_short_bytearray(self):
  2592. """
  2593. When passed a short bytearray, `Connection.send` transmits all of
  2594. it and returns the number of bytes sent.
  2595. """
  2596. server, client = loopback()
  2597. count = server.send(bytearray(b"xy"))
  2598. assert count == 2
  2599. assert client.recv(2) == b"xy"
  2600. @skip_if_py3
  2601. def test_short_buffer(self):
  2602. """
  2603. When passed a buffer containing a small number of bytes,
  2604. `Connection.send` transmits all of them and returns the number
  2605. of bytes sent.
  2606. """
  2607. server, client = loopback()
  2608. count = server.send(buffer(b"xy")) # noqa: F821
  2609. assert count == 2
  2610. assert client.recv(2) == b"xy"
  2611. @pytest.mark.skipif(
  2612. sys.maxsize < 2 ** 31,
  2613. reason="sys.maxsize < 2**31 - test requires 64 bit",
  2614. )
  2615. def test_buf_too_large(self):
  2616. """
  2617. When passed a buffer containing >= 2**31 bytes,
  2618. `Connection.send` bails out as SSL_write only
  2619. accepts an int for the buffer length.
  2620. """
  2621. connection = Connection(Context(SSLv23_METHOD), None)
  2622. with pytest.raises(ValueError) as exc_info:
  2623. connection.send(VeryLarge())
  2624. exc_info.match(r"Cannot send more than .+ bytes at once")
  2625. def _make_memoryview(size):
  2626. """
  2627. Create a new ``memoryview`` wrapped around a ``bytearray`` of the given
  2628. size.
  2629. """
  2630. return memoryview(bytearray(size))
  2631. class TestConnectionRecvInto(object):
  2632. """
  2633. Tests for `Connection.recv_into`.
  2634. """
  2635. def _no_length_test(self, factory):
  2636. """
  2637. Assert that when the given buffer is passed to `Connection.recv_into`,
  2638. whatever bytes are available to be received that fit into that buffer
  2639. are written into that buffer.
  2640. """
  2641. output_buffer = factory(5)
  2642. server, client = loopback()
  2643. server.send(b"xy")
  2644. assert client.recv_into(output_buffer) == 2
  2645. assert output_buffer == bytearray(b"xy\x00\x00\x00")
  2646. def test_bytearray_no_length(self):
  2647. """
  2648. `Connection.recv_into` can be passed a `bytearray` instance and data
  2649. in the receive buffer is written to it.
  2650. """
  2651. self._no_length_test(bytearray)
  2652. def _respects_length_test(self, factory):
  2653. """
  2654. Assert that when the given buffer is passed to `Connection.recv_into`
  2655. along with a value for `nbytes` that is less than the size of that
  2656. buffer, only `nbytes` bytes are written into the buffer.
  2657. """
  2658. output_buffer = factory(10)
  2659. server, client = loopback()
  2660. server.send(b"abcdefghij")
  2661. assert client.recv_into(output_buffer, 5) == 5
  2662. assert output_buffer == bytearray(b"abcde\x00\x00\x00\x00\x00")
  2663. def test_bytearray_respects_length(self):
  2664. """
  2665. When called with a `bytearray` instance, `Connection.recv_into`
  2666. respects the `nbytes` parameter and doesn't copy in more than that
  2667. number of bytes.
  2668. """
  2669. self._respects_length_test(bytearray)
  2670. def _doesnt_overfill_test(self, factory):
  2671. """
  2672. Assert that if there are more bytes available to be read from the
  2673. receive buffer than would fit into the buffer passed to
  2674. `Connection.recv_into`, only as many as fit are written into it.
  2675. """
  2676. output_buffer = factory(5)
  2677. server, client = loopback()
  2678. server.send(b"abcdefghij")
  2679. assert client.recv_into(output_buffer) == 5
  2680. assert output_buffer == bytearray(b"abcde")
  2681. rest = client.recv(5)
  2682. assert b"fghij" == rest
  2683. def test_bytearray_doesnt_overfill(self):
  2684. """
  2685. When called with a `bytearray` instance, `Connection.recv_into`
  2686. respects the size of the array and doesn't write more bytes into it
  2687. than will fit.
  2688. """
  2689. self._doesnt_overfill_test(bytearray)
  2690. def test_bytearray_really_doesnt_overfill(self):
  2691. """
  2692. When called with a `bytearray` instance and an `nbytes` value that is
  2693. too large, `Connection.recv_into` respects the size of the array and
  2694. not the `nbytes` value and doesn't write more bytes into the buffer
  2695. than will fit.
  2696. """
  2697. self._doesnt_overfill_test(bytearray)
  2698. def test_peek(self):
  2699. server, client = loopback()
  2700. server.send(b"xy")
  2701. for _ in range(2):
  2702. output_buffer = bytearray(5)
  2703. assert client.recv_into(output_buffer, flags=MSG_PEEK) == 2
  2704. assert output_buffer == bytearray(b"xy\x00\x00\x00")
  2705. def test_memoryview_no_length(self):
  2706. """
  2707. `Connection.recv_into` can be passed a `memoryview` instance and data
  2708. in the receive buffer is written to it.
  2709. """
  2710. self._no_length_test(_make_memoryview)
  2711. def test_memoryview_respects_length(self):
  2712. """
  2713. When called with a `memoryview` instance, `Connection.recv_into`
  2714. respects the ``nbytes`` parameter and doesn't copy more than that
  2715. number of bytes in.
  2716. """
  2717. self._respects_length_test(_make_memoryview)
  2718. def test_memoryview_doesnt_overfill(self):
  2719. """
  2720. When called with a `memoryview` instance, `Connection.recv_into`
  2721. respects the size of the array and doesn't write more bytes into it
  2722. than will fit.
  2723. """
  2724. self._doesnt_overfill_test(_make_memoryview)
  2725. def test_memoryview_really_doesnt_overfill(self):
  2726. """
  2727. When called with a `memoryview` instance and an `nbytes` value that is
  2728. too large, `Connection.recv_into` respects the size of the array and
  2729. not the `nbytes` value and doesn't write more bytes into the buffer
  2730. than will fit.
  2731. """
  2732. self._doesnt_overfill_test(_make_memoryview)
  2733. class TestConnectionSendall(object):
  2734. """
  2735. Tests for `Connection.sendall`.
  2736. """
  2737. def test_wrong_args(self):
  2738. """
  2739. When called with arguments other than a string argument for its first
  2740. parameter, `Connection.sendall` raises `TypeError`.
  2741. """
  2742. connection = Connection(Context(SSLv23_METHOD), None)
  2743. with pytest.raises(TypeError):
  2744. connection.sendall(object())
  2745. with pytest.raises(TypeError):
  2746. connection.sendall([1, 2, 3])
  2747. def test_short(self):
  2748. """
  2749. `Connection.sendall` transmits all of the bytes in the string
  2750. passed to it.
  2751. """
  2752. server, client = loopback()
  2753. server.sendall(b"x")
  2754. assert client.recv(1) == b"x"
  2755. def test_text(self):
  2756. """
  2757. `Connection.sendall` transmits all the content in the string passed
  2758. to it, raising a DeprecationWarning in case of this being a text.
  2759. """
  2760. server, client = loopback()
  2761. with pytest.warns(DeprecationWarning) as w:
  2762. simplefilter("always")
  2763. server.sendall(b"x".decode("ascii"))
  2764. assert "{0} for buf is no longer accepted, use bytes".format(
  2765. WARNING_TYPE_EXPECTED
  2766. ) == str(w[-1].message)
  2767. assert client.recv(1) == b"x"
  2768. def test_short_memoryview(self):
  2769. """
  2770. When passed a memoryview onto a small number of bytes,
  2771. `Connection.sendall` transmits all of them.
  2772. """
  2773. server, client = loopback()
  2774. server.sendall(memoryview(b"x"))
  2775. assert client.recv(1) == b"x"
  2776. @skip_if_py3
  2777. def test_short_buffers(self):
  2778. """
  2779. When passed a buffer containing a small number of bytes,
  2780. `Connection.sendall` transmits all of them.
  2781. """
  2782. server, client = loopback()
  2783. count = server.sendall(buffer(b"xy")) # noqa: F821
  2784. assert count == 2
  2785. assert client.recv(2) == b"xy"
  2786. def test_long(self):
  2787. """
  2788. `Connection.sendall` transmits all the bytes in the string passed to it
  2789. even if this requires multiple calls of an underlying write function.
  2790. """
  2791. server, client = loopback()
  2792. # Should be enough, underlying SSL_write should only do 16k at a time.
  2793. # On Windows, after 32k of bytes the write will block (forever
  2794. # - because no one is yet reading).
  2795. message = b"x" * (1024 * 32 - 1) + b"y"
  2796. server.sendall(message)
  2797. accum = []
  2798. received = 0
  2799. while received < len(message):
  2800. data = client.recv(1024)
  2801. accum.append(data)
  2802. received += len(data)
  2803. assert message == b"".join(accum)
  2804. def test_closed(self):
  2805. """
  2806. If the underlying socket is closed, `Connection.sendall` propagates the
  2807. write error from the low level write call.
  2808. """
  2809. server, client = loopback()
  2810. server.sock_shutdown(2)
  2811. with pytest.raises(SysCallError) as err:
  2812. server.sendall(b"hello, world")
  2813. if platform == "win32":
  2814. assert err.value.args[0] == ESHUTDOWN
  2815. else:
  2816. assert err.value.args[0] == EPIPE
  2817. class TestConnectionRenegotiate(object):
  2818. """
  2819. Tests for SSL renegotiation APIs.
  2820. """
  2821. def test_total_renegotiations(self):
  2822. """
  2823. `Connection.total_renegotiations` returns `0` before any renegotiations
  2824. have happened.
  2825. """
  2826. connection = Connection(Context(SSLv23_METHOD), None)
  2827. assert connection.total_renegotiations() == 0
  2828. def test_renegotiate(self):
  2829. """
  2830. Go through a complete renegotiation cycle.
  2831. """
  2832. server, client = loopback(
  2833. lambda s: loopback_server_factory(s, TLSv1_2_METHOD),
  2834. lambda s: loopback_client_factory(s, TLSv1_2_METHOD),
  2835. )
  2836. server.send(b"hello world")
  2837. assert b"hello world" == client.recv(len(b"hello world"))
  2838. assert 0 == server.total_renegotiations()
  2839. assert False is server.renegotiate_pending()
  2840. assert True is server.renegotiate()
  2841. assert True is server.renegotiate_pending()
  2842. server.setblocking(False)
  2843. client.setblocking(False)
  2844. client.do_handshake()
  2845. server.do_handshake()
  2846. assert 1 == server.total_renegotiations()
  2847. while False is server.renegotiate_pending():
  2848. pass
  2849. class TestError(object):
  2850. """
  2851. Unit tests for `OpenSSL.SSL.Error`.
  2852. """
  2853. def test_type(self):
  2854. """
  2855. `Error` is an exception type.
  2856. """
  2857. assert issubclass(Error, Exception)
  2858. assert Error.__name__ == "Error"
  2859. class TestConstants(object):
  2860. """
  2861. Tests for the values of constants exposed in `OpenSSL.SSL`.
  2862. These are values defined by OpenSSL intended only to be used as flags to
  2863. OpenSSL APIs. The only assertions it seems can be made about them is
  2864. their values.
  2865. """
  2866. @pytest.mark.skipif(
  2867. OP_NO_QUERY_MTU is None,
  2868. reason="OP_NO_QUERY_MTU unavailable - OpenSSL version may be too old",
  2869. )
  2870. def test_op_no_query_mtu(self):
  2871. """
  2872. The value of `OpenSSL.SSL.OP_NO_QUERY_MTU` is 0x1000, the value
  2873. of `SSL_OP_NO_QUERY_MTU` defined by `openssl/ssl.h`.
  2874. """
  2875. assert OP_NO_QUERY_MTU == 0x1000
  2876. @pytest.mark.skipif(
  2877. OP_COOKIE_EXCHANGE is None,
  2878. reason="OP_COOKIE_EXCHANGE unavailable - "
  2879. "OpenSSL version may be too old",
  2880. )
  2881. def test_op_cookie_exchange(self):
  2882. """
  2883. The value of `OpenSSL.SSL.OP_COOKIE_EXCHANGE` is 0x2000, the
  2884. value of `SSL_OP_COOKIE_EXCHANGE` defined by `openssl/ssl.h`.
  2885. """
  2886. assert OP_COOKIE_EXCHANGE == 0x2000
  2887. @pytest.mark.skipif(
  2888. OP_NO_TICKET is None,
  2889. reason="OP_NO_TICKET unavailable - OpenSSL version may be too old",
  2890. )
  2891. def test_op_no_ticket(self):
  2892. """
  2893. The value of `OpenSSL.SSL.OP_NO_TICKET` is 0x4000, the value of
  2894. `SSL_OP_NO_TICKET` defined by `openssl/ssl.h`.
  2895. """
  2896. assert OP_NO_TICKET == 0x4000
  2897. @pytest.mark.skipif(
  2898. OP_NO_COMPRESSION is None,
  2899. reason=(
  2900. "OP_NO_COMPRESSION unavailable - OpenSSL version may be too old"
  2901. ),
  2902. )
  2903. def test_op_no_compression(self):
  2904. """
  2905. The value of `OpenSSL.SSL.OP_NO_COMPRESSION` is 0x20000, the
  2906. value of `SSL_OP_NO_COMPRESSION` defined by `openssl/ssl.h`.
  2907. """
  2908. assert OP_NO_COMPRESSION == 0x20000
  2909. def test_sess_cache_off(self):
  2910. """
  2911. The value of `OpenSSL.SSL.SESS_CACHE_OFF` 0x0, the value of
  2912. `SSL_SESS_CACHE_OFF` defined by `openssl/ssl.h`.
  2913. """
  2914. assert 0x0 == SESS_CACHE_OFF
  2915. def test_sess_cache_client(self):
  2916. """
  2917. The value of `OpenSSL.SSL.SESS_CACHE_CLIENT` 0x1, the value of
  2918. `SSL_SESS_CACHE_CLIENT` defined by `openssl/ssl.h`.
  2919. """
  2920. assert 0x1 == SESS_CACHE_CLIENT
  2921. def test_sess_cache_server(self):
  2922. """
  2923. The value of `OpenSSL.SSL.SESS_CACHE_SERVER` 0x2, the value of
  2924. `SSL_SESS_CACHE_SERVER` defined by `openssl/ssl.h`.
  2925. """
  2926. assert 0x2 == SESS_CACHE_SERVER
  2927. def test_sess_cache_both(self):
  2928. """
  2929. The value of `OpenSSL.SSL.SESS_CACHE_BOTH` 0x3, the value of
  2930. `SSL_SESS_CACHE_BOTH` defined by `openssl/ssl.h`.
  2931. """
  2932. assert 0x3 == SESS_CACHE_BOTH
  2933. def test_sess_cache_no_auto_clear(self):
  2934. """
  2935. The value of `OpenSSL.SSL.SESS_CACHE_NO_AUTO_CLEAR` 0x80, the
  2936. value of `SSL_SESS_CACHE_NO_AUTO_CLEAR` defined by
  2937. `openssl/ssl.h`.
  2938. """
  2939. assert 0x80 == SESS_CACHE_NO_AUTO_CLEAR
  2940. def test_sess_cache_no_internal_lookup(self):
  2941. """
  2942. The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_LOOKUP` 0x100,
  2943. the value of `SSL_SESS_CACHE_NO_INTERNAL_LOOKUP` defined by
  2944. `openssl/ssl.h`.
  2945. """
  2946. assert 0x100 == SESS_CACHE_NO_INTERNAL_LOOKUP
  2947. def test_sess_cache_no_internal_store(self):
  2948. """
  2949. The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL_STORE` 0x200,
  2950. the value of `SSL_SESS_CACHE_NO_INTERNAL_STORE` defined by
  2951. `openssl/ssl.h`.
  2952. """
  2953. assert 0x200 == SESS_CACHE_NO_INTERNAL_STORE
  2954. def test_sess_cache_no_internal(self):
  2955. """
  2956. The value of `OpenSSL.SSL.SESS_CACHE_NO_INTERNAL` 0x300, the
  2957. value of `SSL_SESS_CACHE_NO_INTERNAL` defined by
  2958. `openssl/ssl.h`.
  2959. """
  2960. assert 0x300 == SESS_CACHE_NO_INTERNAL
  2961. class TestMemoryBIO(object):
  2962. """
  2963. Tests for `OpenSSL.SSL.Connection` using a memory BIO.
  2964. """
  2965. def _server(self, sock):
  2966. """
  2967. Create a new server-side SSL `Connection` object wrapped around `sock`.
  2968. """
  2969. # Create the server side Connection. This is mostly setup boilerplate
  2970. # - use TLSv1, use a particular certificate, etc.
  2971. server_ctx = Context(SSLv23_METHOD)
  2972. server_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
  2973. server_ctx.set_verify(
  2974. VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
  2975. verify_cb,
  2976. )
  2977. server_store = server_ctx.get_cert_store()
  2978. server_ctx.use_privatekey(
  2979. load_privatekey(FILETYPE_PEM, server_key_pem)
  2980. )
  2981. server_ctx.use_certificate(
  2982. load_certificate(FILETYPE_PEM, server_cert_pem)
  2983. )
  2984. server_ctx.check_privatekey()
  2985. server_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
  2986. # Here the Connection is actually created. If None is passed as the
  2987. # 2nd parameter, it indicates a memory BIO should be created.
  2988. server_conn = Connection(server_ctx, sock)
  2989. server_conn.set_accept_state()
  2990. return server_conn
  2991. def _client(self, sock):
  2992. """
  2993. Create a new client-side SSL `Connection` object wrapped around `sock`.
  2994. """
  2995. # Now create the client side Connection. Similar boilerplate to the
  2996. # above.
  2997. client_ctx = Context(SSLv23_METHOD)
  2998. client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE)
  2999. client_ctx.set_verify(
  3000. VERIFY_PEER | VERIFY_FAIL_IF_NO_PEER_CERT | VERIFY_CLIENT_ONCE,
  3001. verify_cb,
  3002. )
  3003. client_store = client_ctx.get_cert_store()
  3004. client_ctx.use_privatekey(
  3005. load_privatekey(FILETYPE_PEM, client_key_pem)
  3006. )
  3007. client_ctx.use_certificate(
  3008. load_certificate(FILETYPE_PEM, client_cert_pem)
  3009. )
  3010. client_ctx.check_privatekey()
  3011. client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem))
  3012. client_conn = Connection(client_ctx, sock)
  3013. client_conn.set_connect_state()
  3014. return client_conn
  3015. def test_memory_connect(self):
  3016. """
  3017. Two `Connection`s which use memory BIOs can be manually connected by
  3018. reading from the output of each and writing those bytes to the input of
  3019. the other and in this way establish a connection and exchange
  3020. application-level bytes with each other.
  3021. """
  3022. server_conn = self._server(None)
  3023. client_conn = self._client(None)
  3024. # There should be no key or nonces yet.
  3025. assert server_conn.master_key() is None
  3026. assert server_conn.client_random() is None
  3027. assert server_conn.server_random() is None
  3028. # First, the handshake needs to happen. We'll deliver bytes back and
  3029. # forth between the client and server until neither of them feels like
  3030. # speaking any more.
  3031. assert interact_in_memory(client_conn, server_conn) is None
  3032. # Now that the handshake is done, there should be a key and nonces.
  3033. assert server_conn.master_key() is not None
  3034. assert server_conn.client_random() is not None
  3035. assert server_conn.server_random() is not None
  3036. assert server_conn.client_random() == client_conn.client_random()
  3037. assert server_conn.server_random() == client_conn.server_random()
  3038. assert server_conn.client_random() != server_conn.server_random()
  3039. assert client_conn.client_random() != client_conn.server_random()
  3040. # Export key material for other uses.
  3041. cekm = client_conn.export_keying_material(b"LABEL", 32)
  3042. sekm = server_conn.export_keying_material(b"LABEL", 32)
  3043. assert cekm is not None
  3044. assert sekm is not None
  3045. assert cekm == sekm
  3046. assert len(sekm) == 32
  3047. # Export key material for other uses with additional context.
  3048. cekmc = client_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
  3049. sekmc = server_conn.export_keying_material(b"LABEL", 32, b"CONTEXT")
  3050. assert cekmc is not None
  3051. assert sekmc is not None
  3052. assert cekmc == sekmc
  3053. assert cekmc != cekm
  3054. assert sekmc != sekm
  3055. # Export with alternate label
  3056. cekmt = client_conn.export_keying_material(b"test", 32, b"CONTEXT")
  3057. sekmt = server_conn.export_keying_material(b"test", 32, b"CONTEXT")
  3058. assert cekmc != cekmt
  3059. assert sekmc != sekmt
  3060. # Here are the bytes we'll try to send.
  3061. important_message = b"One if by land, two if by sea."
  3062. server_conn.write(important_message)
  3063. assert interact_in_memory(client_conn, server_conn) == (
  3064. client_conn,
  3065. important_message,
  3066. )
  3067. client_conn.write(important_message[::-1])
  3068. assert interact_in_memory(client_conn, server_conn) == (
  3069. server_conn,
  3070. important_message[::-1],
  3071. )
  3072. def test_socket_connect(self):
  3073. """
  3074. Just like `test_memory_connect` but with an actual socket.
  3075. This is primarily to rule out the memory BIO code as the source of any
  3076. problems encountered while passing data over a `Connection` (if
  3077. this test fails, there must be a problem outside the memory BIO code,
  3078. as no memory BIO is involved here). Even though this isn't a memory
  3079. BIO test, it's convenient to have it here.
  3080. """
  3081. server_conn, client_conn = loopback()
  3082. important_message = b"Help me Obi Wan Kenobi, you're my only hope."
  3083. client_conn.send(important_message)
  3084. msg = server_conn.recv(1024)
  3085. assert msg == important_message
  3086. # Again in the other direction, just for fun.
  3087. important_message = important_message[::-1]
  3088. server_conn.send(important_message)
  3089. msg = client_conn.recv(1024)
  3090. assert msg == important_message
  3091. def test_socket_overrides_memory(self):
  3092. """
  3093. Test that `OpenSSL.SSL.bio_read` and `OpenSSL.SSL.bio_write` don't
  3094. work on `OpenSSL.SSL.Connection`() that use sockets.
  3095. """
  3096. context = Context(SSLv23_METHOD)
  3097. client = socket_any_family()
  3098. clientSSL = Connection(context, client)
  3099. with pytest.raises(TypeError):
  3100. clientSSL.bio_read(100)
  3101. with pytest.raises(TypeError):
  3102. clientSSL.bio_write(b"foo")
  3103. with pytest.raises(TypeError):
  3104. clientSSL.bio_shutdown()
  3105. def test_outgoing_overflow(self):
  3106. """
  3107. If more bytes than can be written to the memory BIO are passed to
  3108. `Connection.send` at once, the number of bytes which were written is
  3109. returned and that many bytes from the beginning of the input can be
  3110. read from the other end of the connection.
  3111. """
  3112. server = self._server(None)
  3113. client = self._client(None)
  3114. interact_in_memory(client, server)
  3115. size = 2 ** 15
  3116. sent = client.send(b"x" * size)
  3117. # Sanity check. We're trying to test what happens when the entire
  3118. # input can't be sent. If the entire input was sent, this test is
  3119. # meaningless.
  3120. assert sent < size
  3121. receiver, received = interact_in_memory(client, server)
  3122. assert receiver is server
  3123. # We can rely on all of these bytes being received at once because
  3124. # loopback passes 2 ** 16 to recv - more than 2 ** 15.
  3125. assert len(received) == sent
  3126. def test_shutdown(self):
  3127. """
  3128. `Connection.bio_shutdown` signals the end of the data stream
  3129. from which the `Connection` reads.
  3130. """
  3131. server = self._server(None)
  3132. server.bio_shutdown()
  3133. with pytest.raises(Error) as err:
  3134. server.recv(1024)
  3135. # We don't want WantReadError or ZeroReturnError or anything - it's a
  3136. # handshake failure.
  3137. assert type(err.value) in [Error, SysCallError]
  3138. def test_unexpected_EOF(self):
  3139. """
  3140. If the connection is lost before an orderly SSL shutdown occurs,
  3141. `OpenSSL.SSL.SysCallError` is raised with a message of
  3142. "Unexpected EOF".
  3143. """
  3144. server_conn, client_conn = loopback()
  3145. client_conn.sock_shutdown(SHUT_RDWR)
  3146. with pytest.raises(SysCallError) as err:
  3147. server_conn.recv(1024)
  3148. assert err.value.args == (-1, "Unexpected EOF")
  3149. def _check_client_ca_list(self, func):
  3150. """
  3151. Verify the return value of the `get_client_ca_list` method for
  3152. server and client connections.
  3153. :param func: A function which will be called with the server context
  3154. before the client and server are connected to each other. This
  3155. function should specify a list of CAs for the server to send to the
  3156. client and return that same list. The list will be used to verify
  3157. that `get_client_ca_list` returns the proper value at
  3158. various times.
  3159. """
  3160. server = self._server(None)
  3161. client = self._client(None)
  3162. assert client.get_client_ca_list() == []
  3163. assert server.get_client_ca_list() == []
  3164. ctx = server.get_context()
  3165. expected = func(ctx)
  3166. assert client.get_client_ca_list() == []
  3167. assert server.get_client_ca_list() == expected
  3168. interact_in_memory(client, server)
  3169. assert client.get_client_ca_list() == expected
  3170. assert server.get_client_ca_list() == expected
  3171. def test_set_client_ca_list_errors(self):
  3172. """
  3173. `Context.set_client_ca_list` raises a `TypeError` if called with a
  3174. non-list or a list that contains objects other than X509Names.
  3175. """
  3176. ctx = Context(SSLv23_METHOD)
  3177. with pytest.raises(TypeError):
  3178. ctx.set_client_ca_list("spam")
  3179. with pytest.raises(TypeError):
  3180. ctx.set_client_ca_list(["spam"])
  3181. def test_set_empty_ca_list(self):
  3182. """
  3183. If passed an empty list, `Context.set_client_ca_list` configures the
  3184. context to send no CA names to the client and, on both the server and
  3185. client sides, `Connection.get_client_ca_list` returns an empty list
  3186. after the connection is set up.
  3187. """
  3188. def no_ca(ctx):
  3189. ctx.set_client_ca_list([])
  3190. return []
  3191. self._check_client_ca_list(no_ca)
  3192. def test_set_one_ca_list(self):
  3193. """
  3194. If passed a list containing a single X509Name,
  3195. `Context.set_client_ca_list` configures the context to send
  3196. that CA name to the client and, on both the server and client sides,
  3197. `Connection.get_client_ca_list` returns a list containing that
  3198. X509Name after the connection is set up.
  3199. """
  3200. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3201. cadesc = cacert.get_subject()
  3202. def single_ca(ctx):
  3203. ctx.set_client_ca_list([cadesc])
  3204. return [cadesc]
  3205. self._check_client_ca_list(single_ca)
  3206. def test_set_multiple_ca_list(self):
  3207. """
  3208. If passed a list containing multiple X509Name objects,
  3209. `Context.set_client_ca_list` configures the context to send
  3210. those CA names to the client and, on both the server and client sides,
  3211. `Connection.get_client_ca_list` returns a list containing those
  3212. X509Names after the connection is set up.
  3213. """
  3214. secert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3215. clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3216. sedesc = secert.get_subject()
  3217. cldesc = clcert.get_subject()
  3218. def multiple_ca(ctx):
  3219. L = [sedesc, cldesc]
  3220. ctx.set_client_ca_list(L)
  3221. return L
  3222. self._check_client_ca_list(multiple_ca)
  3223. def test_reset_ca_list(self):
  3224. """
  3225. If called multiple times, only the X509Names passed to the final call
  3226. of `Context.set_client_ca_list` are used to configure the CA
  3227. names sent to the client.
  3228. """
  3229. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3230. secert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3231. clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3232. cadesc = cacert.get_subject()
  3233. sedesc = secert.get_subject()
  3234. cldesc = clcert.get_subject()
  3235. def changed_ca(ctx):
  3236. ctx.set_client_ca_list([sedesc, cldesc])
  3237. ctx.set_client_ca_list([cadesc])
  3238. return [cadesc]
  3239. self._check_client_ca_list(changed_ca)
  3240. def test_mutated_ca_list(self):
  3241. """
  3242. If the list passed to `Context.set_client_ca_list` is mutated
  3243. afterwards, this does not affect the list of CA names sent to the
  3244. client.
  3245. """
  3246. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3247. secert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3248. cadesc = cacert.get_subject()
  3249. sedesc = secert.get_subject()
  3250. def mutated_ca(ctx):
  3251. L = [cadesc]
  3252. ctx.set_client_ca_list([cadesc])
  3253. L.append(sedesc)
  3254. return [cadesc]
  3255. self._check_client_ca_list(mutated_ca)
  3256. def test_add_client_ca_wrong_args(self):
  3257. """
  3258. `Context.add_client_ca` raises `TypeError` if called with
  3259. a non-X509 object.
  3260. """
  3261. ctx = Context(SSLv23_METHOD)
  3262. with pytest.raises(TypeError):
  3263. ctx.add_client_ca("spam")
  3264. def test_one_add_client_ca(self):
  3265. """
  3266. A certificate's subject can be added as a CA to be sent to the client
  3267. with `Context.add_client_ca`.
  3268. """
  3269. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3270. cadesc = cacert.get_subject()
  3271. def single_ca(ctx):
  3272. ctx.add_client_ca(cacert)
  3273. return [cadesc]
  3274. self._check_client_ca_list(single_ca)
  3275. def test_multiple_add_client_ca(self):
  3276. """
  3277. Multiple CA names can be sent to the client by calling
  3278. `Context.add_client_ca` with multiple X509 objects.
  3279. """
  3280. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3281. secert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3282. cadesc = cacert.get_subject()
  3283. sedesc = secert.get_subject()
  3284. def multiple_ca(ctx):
  3285. ctx.add_client_ca(cacert)
  3286. ctx.add_client_ca(secert)
  3287. return [cadesc, sedesc]
  3288. self._check_client_ca_list(multiple_ca)
  3289. def test_set_and_add_client_ca(self):
  3290. """
  3291. A call to `Context.set_client_ca_list` followed by a call to
  3292. `Context.add_client_ca` results in using the CA names from the
  3293. first call and the CA name from the second call.
  3294. """
  3295. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3296. secert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3297. clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3298. cadesc = cacert.get_subject()
  3299. sedesc = secert.get_subject()
  3300. cldesc = clcert.get_subject()
  3301. def mixed_set_add_ca(ctx):
  3302. ctx.set_client_ca_list([cadesc, sedesc])
  3303. ctx.add_client_ca(clcert)
  3304. return [cadesc, sedesc, cldesc]
  3305. self._check_client_ca_list(mixed_set_add_ca)
  3306. def test_set_after_add_client_ca(self):
  3307. """
  3308. A call to `Context.set_client_ca_list` after a call to
  3309. `Context.add_client_ca` replaces the CA name specified by the
  3310. former call with the names specified by the latter call.
  3311. """
  3312. cacert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3313. secert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3314. clcert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3315. cadesc = cacert.get_subject()
  3316. sedesc = secert.get_subject()
  3317. def set_replaces_add_ca(ctx):
  3318. ctx.add_client_ca(clcert)
  3319. ctx.set_client_ca_list([cadesc])
  3320. ctx.add_client_ca(secert)
  3321. return [cadesc, sedesc]
  3322. self._check_client_ca_list(set_replaces_add_ca)
  3323. class TestInfoConstants(object):
  3324. """
  3325. Tests for assorted constants exposed for use in info callbacks.
  3326. """
  3327. def test_integers(self):
  3328. """
  3329. All of the info constants are integers.
  3330. This is a very weak test. It would be nice to have one that actually
  3331. verifies that as certain info events happen, the value passed to the
  3332. info callback matches up with the constant exposed by OpenSSL.SSL.
  3333. """
  3334. for const in [
  3335. SSL_ST_CONNECT,
  3336. SSL_ST_ACCEPT,
  3337. SSL_ST_MASK,
  3338. SSL_CB_LOOP,
  3339. SSL_CB_EXIT,
  3340. SSL_CB_READ,
  3341. SSL_CB_WRITE,
  3342. SSL_CB_ALERT,
  3343. SSL_CB_READ_ALERT,
  3344. SSL_CB_WRITE_ALERT,
  3345. SSL_CB_ACCEPT_LOOP,
  3346. SSL_CB_ACCEPT_EXIT,
  3347. SSL_CB_CONNECT_LOOP,
  3348. SSL_CB_CONNECT_EXIT,
  3349. SSL_CB_HANDSHAKE_START,
  3350. SSL_CB_HANDSHAKE_DONE,
  3351. ]:
  3352. assert isinstance(const, int)
  3353. # These constants don't exist on OpenSSL 1.1.0
  3354. for const in [
  3355. SSL_ST_INIT,
  3356. SSL_ST_BEFORE,
  3357. SSL_ST_OK,
  3358. SSL_ST_RENEGOTIATE,
  3359. ]:
  3360. assert const is None or isinstance(const, int)
  3361. class TestRequires(object):
  3362. """
  3363. Tests for the decorator factory used to conditionally raise
  3364. NotImplementedError when older OpenSSLs are used.
  3365. """
  3366. def test_available(self):
  3367. """
  3368. When the OpenSSL functionality is available the decorated functions
  3369. work appropriately.
  3370. """
  3371. feature_guard = _make_requires(True, "Error text")
  3372. results = []
  3373. @feature_guard
  3374. def inner():
  3375. results.append(True)
  3376. return True
  3377. assert inner() is True
  3378. assert [True] == results
  3379. def test_unavailable(self):
  3380. """
  3381. When the OpenSSL functionality is not available the decorated function
  3382. does not execute and NotImplementedError is raised.
  3383. """
  3384. feature_guard = _make_requires(False, "Error text")
  3385. @feature_guard
  3386. def inner(): # pragma: nocover
  3387. pytest.fail("Should not be called")
  3388. with pytest.raises(NotImplementedError) as e:
  3389. inner()
  3390. assert "Error text" in str(e.value)
  3391. class TestOCSP(object):
  3392. """
  3393. Tests for PyOpenSSL's OCSP stapling support.
  3394. """
  3395. sample_ocsp_data = b"this is totally ocsp data"
  3396. def _client_connection(self, callback, data, request_ocsp=True):
  3397. """
  3398. Builds a client connection suitable for using OCSP.
  3399. :param callback: The callback to register for OCSP.
  3400. :param data: The opaque data object that will be handed to the
  3401. OCSP callback.
  3402. :param request_ocsp: Whether the client will actually ask for OCSP
  3403. stapling. Useful for testing only.
  3404. """
  3405. ctx = Context(SSLv23_METHOD)
  3406. ctx.set_ocsp_client_callback(callback, data)
  3407. client = Connection(ctx)
  3408. if request_ocsp:
  3409. client.request_ocsp()
  3410. client.set_connect_state()
  3411. return client
  3412. def _server_connection(self, callback, data):
  3413. """
  3414. Builds a server connection suitable for using OCSP.
  3415. :param callback: The callback to register for OCSP.
  3416. :param data: The opaque data object that will be handed to the
  3417. OCSP callback.
  3418. """
  3419. ctx = Context(SSLv23_METHOD)
  3420. ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  3421. ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
  3422. ctx.set_ocsp_server_callback(callback, data)
  3423. server = Connection(ctx)
  3424. server.set_accept_state()
  3425. return server
  3426. def test_callbacks_arent_called_by_default(self):
  3427. """
  3428. If both the client and the server have registered OCSP callbacks, but
  3429. the client does not send the OCSP request, neither callback gets
  3430. called.
  3431. """
  3432. def ocsp_callback(*args, **kwargs): # pragma: nocover
  3433. pytest.fail("Should not be called")
  3434. client = self._client_connection(
  3435. callback=ocsp_callback, data=None, request_ocsp=False
  3436. )
  3437. server = self._server_connection(callback=ocsp_callback, data=None)
  3438. handshake_in_memory(client, server)
  3439. def test_client_negotiates_without_server(self):
  3440. """
  3441. If the client wants to do OCSP but the server does not, the handshake
  3442. succeeds, and the client callback fires with an empty byte string.
  3443. """
  3444. called = []
  3445. def ocsp_callback(conn, ocsp_data, ignored):
  3446. called.append(ocsp_data)
  3447. return True
  3448. client = self._client_connection(callback=ocsp_callback, data=None)
  3449. server = loopback_server_factory(socket=None)
  3450. handshake_in_memory(client, server)
  3451. assert len(called) == 1
  3452. assert called[0] == b""
  3453. def test_client_receives_servers_data(self):
  3454. """
  3455. The data the server sends in its callback is received by the client.
  3456. """
  3457. calls = []
  3458. def server_callback(*args, **kwargs):
  3459. return self.sample_ocsp_data
  3460. def client_callback(conn, ocsp_data, ignored):
  3461. calls.append(ocsp_data)
  3462. return True
  3463. client = self._client_connection(callback=client_callback, data=None)
  3464. server = self._server_connection(callback=server_callback, data=None)
  3465. handshake_in_memory(client, server)
  3466. assert len(calls) == 1
  3467. assert calls[0] == self.sample_ocsp_data
  3468. def test_callbacks_are_invoked_with_connections(self):
  3469. """
  3470. The first arguments to both callbacks are their respective connections.
  3471. """
  3472. client_calls = []
  3473. server_calls = []
  3474. def client_callback(conn, *args, **kwargs):
  3475. client_calls.append(conn)
  3476. return True
  3477. def server_callback(conn, *args, **kwargs):
  3478. server_calls.append(conn)
  3479. return self.sample_ocsp_data
  3480. client = self._client_connection(callback=client_callback, data=None)
  3481. server = self._server_connection(callback=server_callback, data=None)
  3482. handshake_in_memory(client, server)
  3483. assert len(client_calls) == 1
  3484. assert len(server_calls) == 1
  3485. assert client_calls[0] is client
  3486. assert server_calls[0] is server
  3487. def test_opaque_data_is_passed_through(self):
  3488. """
  3489. Both callbacks receive an opaque, user-provided piece of data in their
  3490. callbacks as the final argument.
  3491. """
  3492. calls = []
  3493. def server_callback(*args):
  3494. calls.append(args)
  3495. return self.sample_ocsp_data
  3496. def client_callback(*args):
  3497. calls.append(args)
  3498. return True
  3499. sentinel = object()
  3500. client = self._client_connection(
  3501. callback=client_callback, data=sentinel
  3502. )
  3503. server = self._server_connection(
  3504. callback=server_callback, data=sentinel
  3505. )
  3506. handshake_in_memory(client, server)
  3507. assert len(calls) == 2
  3508. assert calls[0][-1] is sentinel
  3509. assert calls[1][-1] is sentinel
  3510. def test_server_returns_empty_string(self):
  3511. """
  3512. If the server returns an empty bytestring from its callback, the
  3513. client callback is called with the empty bytestring.
  3514. """
  3515. client_calls = []
  3516. def server_callback(*args):
  3517. return b""
  3518. def client_callback(conn, ocsp_data, ignored):
  3519. client_calls.append(ocsp_data)
  3520. return True
  3521. client = self._client_connection(callback=client_callback, data=None)
  3522. server = self._server_connection(callback=server_callback, data=None)
  3523. handshake_in_memory(client, server)
  3524. assert len(client_calls) == 1
  3525. assert client_calls[0] == b""
  3526. def test_client_returns_false_terminates_handshake(self):
  3527. """
  3528. If the client returns False from its callback, the handshake fails.
  3529. """
  3530. def server_callback(*args):
  3531. return self.sample_ocsp_data
  3532. def client_callback(*args):
  3533. return False
  3534. client = self._client_connection(callback=client_callback, data=None)
  3535. server = self._server_connection(callback=server_callback, data=None)
  3536. with pytest.raises(Error):
  3537. handshake_in_memory(client, server)
  3538. def test_exceptions_in_client_bubble_up(self):
  3539. """
  3540. The callbacks thrown in the client callback bubble up to the caller.
  3541. """
  3542. class SentinelException(Exception):
  3543. pass
  3544. def server_callback(*args):
  3545. return self.sample_ocsp_data
  3546. def client_callback(*args):
  3547. raise SentinelException()
  3548. client = self._client_connection(callback=client_callback, data=None)
  3549. server = self._server_connection(callback=server_callback, data=None)
  3550. with pytest.raises(SentinelException):
  3551. handshake_in_memory(client, server)
  3552. def test_exceptions_in_server_bubble_up(self):
  3553. """
  3554. The callbacks thrown in the server callback bubble up to the caller.
  3555. """
  3556. class SentinelException(Exception):
  3557. pass
  3558. def server_callback(*args):
  3559. raise SentinelException()
  3560. def client_callback(*args): # pragma: nocover
  3561. pytest.fail("Should not be called")
  3562. client = self._client_connection(callback=client_callback, data=None)
  3563. server = self._server_connection(callback=server_callback, data=None)
  3564. with pytest.raises(SentinelException):
  3565. handshake_in_memory(client, server)
  3566. def test_server_must_return_bytes(self):
  3567. """
  3568. The server callback must return a bytestring, or a TypeError is thrown.
  3569. """
  3570. def server_callback(*args):
  3571. return self.sample_ocsp_data.decode("ascii")
  3572. def client_callback(*args): # pragma: nocover
  3573. pytest.fail("Should not be called")
  3574. client = self._client_connection(callback=client_callback, data=None)
  3575. server = self._server_connection(callback=server_callback, data=None)
  3576. with pytest.raises(TypeError):
  3577. handshake_in_memory(client, server)