test_crypto.py 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466
  1. # Copyright (c) Jean-Paul Calderone
  2. # See LICENSE file for details.
  3. """
  4. Unit tests for :py:mod:`OpenSSL.crypto`.
  5. """
  6. from warnings import simplefilter
  7. import base64
  8. from subprocess import PIPE, Popen
  9. from datetime import datetime, timedelta
  10. import sys
  11. import pytest
  12. from cryptography import x509
  13. from cryptography.hazmat.backends.openssl.backend import backend
  14. from cryptography.hazmat.primitives import serialization
  15. from cryptography.hazmat.primitives.asymmetric import rsa
  16. import flaky
  17. from OpenSSL.crypto import TYPE_RSA, TYPE_DSA, Error, PKey
  18. from OpenSSL.crypto import X509, X509Name
  19. from OpenSSL.crypto import (
  20. X509Store,
  21. X509StoreFlags,
  22. X509StoreContext,
  23. X509StoreContextError,
  24. )
  25. from OpenSSL.crypto import X509Req
  26. from OpenSSL.crypto import X509Extension
  27. from OpenSSL.crypto import load_certificate, load_privatekey
  28. from OpenSSL.crypto import load_publickey, dump_publickey
  29. from OpenSSL.crypto import FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT
  30. from OpenSSL.crypto import dump_certificate, load_certificate_request
  31. from OpenSSL.crypto import dump_certificate_request, dump_privatekey
  32. from OpenSSL.crypto import PKCS7, load_pkcs7_data
  33. from OpenSSL.crypto import PKCS12, load_pkcs12
  34. from OpenSSL.crypto import CRL, Revoked, dump_crl, load_crl
  35. from OpenSSL.crypto import NetscapeSPKI
  36. from OpenSSL.crypto import (
  37. sign,
  38. verify,
  39. get_elliptic_curve,
  40. get_elliptic_curves,
  41. )
  42. from OpenSSL._util import ffi as _ffi, lib as _lib
  43. from .util import (
  44. EqualityTestsMixin,
  45. is_consistent_type,
  46. WARNING_TYPE_EXPECTED,
  47. NON_ASCII,
  48. )
  49. def normalize_privatekey_pem(pem):
  50. return dump_privatekey(FILETYPE_PEM, load_privatekey(FILETYPE_PEM, pem))
  51. GOOD_CIPHER = "blowfish"
  52. BAD_CIPHER = "zippers"
  53. GOOD_DIGEST = "SHA1"
  54. BAD_DIGEST = "monkeys"
  55. old_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
  56. MIIC7TCCAlagAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQEFBQAwWDELMAkGA1UE
  57. BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
  58. ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwIhgPMjAwOTAzMjUxMjM2
  59. NThaGA8yMDE3MDYxMTEyMzY1OFowWDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklM
  60. MRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9U
  61. ZXN0aW5nIFJvb3QgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPmaQumL
  62. urpE527uSEHdL1pqcDRmWzu+98Y6YHzT/J7KWEamyMCNZ6fRW1JCR782UQ8a07fy
  63. 2xXsKy4WdKaxyG8CcatwmXvpvRQ44dSANMihHELpANTdyVp6DCysED6wkQFurHlF
  64. 1dshEaJw8b/ypDhmbVIo6Ci1xvCJqivbLFnbAgMBAAGjgbswgbgwHQYDVR0OBBYE
  65. FINVdy1eIfFJDAkk51QJEo3IfgSuMIGIBgNVHSMEgYAwfoAUg1V3LV4h8UkMCSTn
  66. VAkSjch+BK6hXKRaMFgxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJJTDEQMA4GA1UE
  67. BxMHQ2hpY2FnbzEQMA4GA1UEChMHVGVzdGluZzEYMBYGA1UEAxMPVGVzdGluZyBS
  68. b290IENBggg9DMTgxt659DAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GB
  69. AGGCDazMJGoWNBpc03u6+smc95dEead2KlZXBATOdFT1VesY3+nUOqZhEhTGlDMi
  70. hkgaZnzoIq/Uamidegk4hirsCT/R+6vsKAAxNTcBjUeZjlykCJWy5ojShGftXIKY
  71. w/njVbKMXrvc83qmTdGl3TAM0fxQIpqgcglFLveEBgzn
  72. -----END CERTIFICATE-----
  73. """
  74. root_cert_pem = b"""-----BEGIN CERTIFICATE-----
  75. MIIE7jCCA1agAwIBAgIIPQzE4MbeufQwDQYJKoZIhvcNAQELBQAwWDELMAkGA1UE
  76. BhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAwDgYDVQQKEwdU
  77. ZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMjAwODAyMTcxMTE5
  78. WhcNNDcxMjIwMTcxMTE5WjBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMCSUwxEDAO
  79. BgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMTD1Rlc3Rp
  80. bmcgUm9vdCBDQTCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBALpY5jb+
  81. S7AUbx9gzN06wkqUeb+eNLTjCOKofiMTn8Y0TqCA2ZyY3XMcNBMaIS7hdFTgmmqt
  82. fFntYobxLAl/twfbz9AnRaVDh2HyUvHvMBxKn1HSDLALLtqdF0pcXIjP04S7NKPQ
  83. Umgkv2H0KwcUpYlgjTFtXRiP+7wDSiQeP1YVSriEoE0TXK14F8np6ZKK0oQ+u16d
  84. Wn3MGQwFzS+Ipgoz0jbi5D2KzmK2dzHdxY8M2Dktkz/W3DUfUwaTohYed2DG39LP
  85. NUFOxekgXdIZ3vQbDfsEQt27TUzOztbo/BqK7YkRLzzOQFz+dKAxH6Hy6Bu9op7e
  86. DWS9TfD/+UmDxr3IeoLMpmUBKxmzTC4qpej+W1UuCE12dMo4LoadlkG+/l1oABqd
  87. Ucf45WgaFk3xpyEuGnDxjs6rqYPoEapIichxN2fgN+jkgH9ed44r0yOoVeG2pmwD
  88. YFCCxzkmiuzLADlfM1LUzqUNKVFcOakD3iujHEalnDIJsc/znYsqaRvCkQIDAQAB
  89. o4G7MIG4MB0GA1UdDgQWBBSDVXctXiHxSQwJJOdUCRKNyH4ErjCBiAYDVR0jBIGA
  90. MH6AFINVdy1eIfFJDAkk51QJEo3IfgSuoVykWjBYMQswCQYDVQQGEwJVUzELMAkG
  91. A1UECBMCSUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAW
  92. BgNVBAMTD1Rlc3RpbmcgUm9vdCBDQYIIPQzE4MbeufQwDAYDVR0TBAUwAwEB/zAN
  93. BgkqhkiG9w0BAQsFAAOCAYEAFIMFxLHaVDY/nsbYzI7+zxe4GJeUqRIj2g4XK/nF
  94. 6lHLRFL2YP5yJ+Jm4JDkoZqKq/tcEQLIssQS++s6tBSdvFwdY6imfpEZgFPuodrZ
  95. KbYm4Xuouw09EQCEjPxBOQ1NEcPuwuDtvD6/BOfm3SRFRTq/gQwxKlZ7C/4l8b1+
  96. OQPIUryqdlFBpyE/M95GzaNdmkQx41PevEih2nqWnbTsXLeiSXLGoubMTxKEK4T+
  97. J7Ci2KTRJ3SYMgTNU6MNcl7b9Tpw9/KVG80IbpzNQ1LDh3ZtkOfqoou1lmBTeNPu
  98. g2C/oiW6lVAmZx1TL9gbUtkJ0Q2iW4D9TF+zuYi2qpbVU3RvoqK25x3AuIWf4JOL
  99. 3cTNjJ/3zmGSORRJvcGyvVnL30R+vwpaxvyuqMjz3kBjkK2Z2pvElZMJiZhbGG7k
  100. MHZQ5A26v0/iQVno6FRv3cQb9EeAZtNHcIEgsNhPZ53XVnwZ58ByvATMLKNN8dWF
  101. Q+8Bbr7QFxeWvQfHYX2yaQZ/
  102. -----END CERTIFICATE-----
  103. """
  104. root_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
  105. MIIG5AIBAAKCAYEAuljmNv5LsBRvH2DM3TrCSpR5v540tOMI4qh+IxOfxjROoIDZ
  106. nJjdcxw0ExohLuF0VOCaaq18We1ihvEsCX+3B9vP0CdFpUOHYfJS8e8wHEqfUdIM
  107. sAsu2p0XSlxciM/ThLs0o9BSaCS/YfQrBxSliWCNMW1dGI/7vANKJB4/VhVKuISg
  108. TRNcrXgXyenpkorShD67Xp1afcwZDAXNL4imCjPSNuLkPYrOYrZ3Md3FjwzYOS2T
  109. P9bcNR9TBpOiFh53YMbf0s81QU7F6SBd0hne9BsN+wRC3btNTM7O1uj8GortiREv
  110. PM5AXP50oDEfofLoG72int4NZL1N8P/5SYPGvch6gsymZQErGbNMLiql6P5bVS4I
  111. TXZ0yjguhp2WQb7+XWgAGp1Rx/jlaBoWTfGnIS4acPGOzqupg+gRqkiJyHE3Z+A3
  112. 6OSAf153jivTI6hV4bambANgUILHOSaK7MsAOV8zUtTOpQ0pUVw5qQPeK6McRqWc
  113. Mgmxz/OdiyppG8KRAgMBAAECggGAGi6Tafagu8SjOE1pe0veMIxb7shTr3aWsQHr
  114. dxIyyK5gvbxc1tvDgYDc8DIjp2qV5bcI+yQU7K2lwj/waAVBuiDwOdbKukWap/Bc
  115. JxHsOI1jhSN2FOX9V0nrE8+WUMKifWuwIbQLYAaJvUGJKh2EhKDENcWf5uuT+v6b
  116. VCfLzlR/gx1fSHUH+Hd/ICd1YdmPanVF7i09oZ8jhcTq51rTuWs+heerGdp+1O++
  117. H4uBTnAHkUEOB1Iw7mXQTIRBqcntzob/TJrDKycdbFHEeRR0L1hALGEVftq7zI6F
  118. BA9caO1W7HkcVmeT6HATIEIGG5H7QAwSfZflJ/82ZXtDemqhBRVwQ2Fx/99wW3r9
  119. puUvJyLbba7NCwL1+P9w8ebr00kFyYoy6rE1JjqlE+9ZHwakZUWTA1lMOGWNEkRS
  120. bKZNHgrngs2zk5qCYRllmsBZ3obdufnP/wyag+BFVniAIN3a08y46SYmgYTeLdBX
  121. /DHSZIKWI9rBiNg6Qw49N+06XwiBAoHBAOMZQbRT8hEffRFbxcsRdJ4dUCM1RAXV
  122. /IMLeVQgKEWETX3pCydpQ2v65fJPACfLLwwRMq4BX4YpJVHCk6BZh/2zx8T1spmJ
  123. uBkHH6+VYgB9JVU0hv/APAjTZxdBjdhkaXVxccpmBBJqKKwOGf3nRVhmMsItBx2x
  124. ZCz+x50+buRMTKsF+FeK2Dr2e9WrfMkOJ3nQFwbGvOBIQeXKmu0wYUVyebnCdZW5
  125. pKI0Co7wp9soCa02YvTFR8n2kxMe9Y91jQKBwQDSD/xSsRfgDT0uiEwazVQ2D/42
  126. 96U2MYe+k+p1GHBnjIX4eRPcWOnQNUd/QVy1UK4bQg1dVZi+NQJ1YS3mKNCpqOaK
  127. ovrgHHmYC1YIn8Xmq2YGzrm/JLwXw0BkPhHp/1yQVPVgyFKeNa3fSa0tkqCed5rs
  128. erM8090IIzWPzKtXId8Db4i0xHkDzP7xDThb6pPNx5bvAaempJRDLtN9xP/hQRyh
  129. xZ/MECKGRgyAVfndIZaI82kuUQFlnPMqk4FxFhUCgcAhnMdgzVvytNpqC09HMxoz
  130. nNsTmvqqcnWhX71hejD7uQ1PKYMBHk9gWA5YwuCfAy+/dXwuzP06ejSP2WDIRvgd
  131. 0NIskMESgJPDAI7sCgwrTlqMNe4VRHqeQ8vqYUWBVbtWKqhQ8LCBmTzT2nJ2ZhiZ
  132. cObqXofDGVJeZodc+rSnDbP7TDLpoh9G+txxT6R0jafCG86MrjWebJN0U3yCxrpe
  133. 8QabO/DzbDq110YIyg3OHirwfDBBUkHB3sD9/4MQ7LECgcEAs2UFhxVIn4aO5ott
  134. +0G5lkYIQ6cwx9x64i3ugDvz2uruiunUJU0luTOXML2AUDRrzEmXokr0nBQnWlk4
  135. 2qOmuA3PfTx85iJLUab0vX69gyaDhnLLvMrBe8W62yELKXx076ouuI27yPNs3xFL
  136. vWzIkSzx+N0870i8LjPrjTgsZ8g8bfG1nTNhafaLDw/MPutReN7oLouKQs2w9MMr
  137. yPAR2qxBqIJe2uY4pdVy3bMPJWOG7MR74hs6By6HmKfKVuqVAoHBAMRSefX1QtfS
  138. 3wWpQhkE7Sooco4LI8kfNncZ2gzNDbYf6aOkgzv0/SWJh+CdcKep9xk12O02Lpsm
  139. SsPYeYlPDCCvyJYGpR19QocYp6JCaemb7uMd6FuPHSHUgyoR4GS8PUuIbiRnpPxN
  140. 4ta7VzmIZOCFu5e+vOq1NwTd0hR6sy5uNsTHV5ezOOqz2SB+yTRMDPr7cW0dMSJ8
  141. jsvxvqVnkIhWeuP9GIb6XUhq74huGZ0Hpaxe6xG34QYiBpr/O3O/ew==
  142. -----END RSA PRIVATE KEY-----
  143. """
  144. root_key_der = base64.b64decode(
  145. """
  146. MIIG5AIBAAKCAYEAuljmNv5LsBRvH2DM3TrCSpR5v540tOMI4qh+IxOfxjROoIDZ
  147. nJjdcxw0ExohLuF0VOCaaq18We1ihvEsCX+3B9vP0CdFpUOHYfJS8e8wHEqfUdIM
  148. sAsu2p0XSlxciM/ThLs0o9BSaCS/YfQrBxSliWCNMW1dGI/7vANKJB4/VhVKuISg
  149. TRNcrXgXyenpkorShD67Xp1afcwZDAXNL4imCjPSNuLkPYrOYrZ3Md3FjwzYOS2T
  150. P9bcNR9TBpOiFh53YMbf0s81QU7F6SBd0hne9BsN+wRC3btNTM7O1uj8GortiREv
  151. PM5AXP50oDEfofLoG72int4NZL1N8P/5SYPGvch6gsymZQErGbNMLiql6P5bVS4I
  152. TXZ0yjguhp2WQb7+XWgAGp1Rx/jlaBoWTfGnIS4acPGOzqupg+gRqkiJyHE3Z+A3
  153. 6OSAf153jivTI6hV4bambANgUILHOSaK7MsAOV8zUtTOpQ0pUVw5qQPeK6McRqWc
  154. Mgmxz/OdiyppG8KRAgMBAAECggGAGi6Tafagu8SjOE1pe0veMIxb7shTr3aWsQHr
  155. dxIyyK5gvbxc1tvDgYDc8DIjp2qV5bcI+yQU7K2lwj/waAVBuiDwOdbKukWap/Bc
  156. JxHsOI1jhSN2FOX9V0nrE8+WUMKifWuwIbQLYAaJvUGJKh2EhKDENcWf5uuT+v6b
  157. VCfLzlR/gx1fSHUH+Hd/ICd1YdmPanVF7i09oZ8jhcTq51rTuWs+heerGdp+1O++
  158. H4uBTnAHkUEOB1Iw7mXQTIRBqcntzob/TJrDKycdbFHEeRR0L1hALGEVftq7zI6F
  159. BA9caO1W7HkcVmeT6HATIEIGG5H7QAwSfZflJ/82ZXtDemqhBRVwQ2Fx/99wW3r9
  160. puUvJyLbba7NCwL1+P9w8ebr00kFyYoy6rE1JjqlE+9ZHwakZUWTA1lMOGWNEkRS
  161. bKZNHgrngs2zk5qCYRllmsBZ3obdufnP/wyag+BFVniAIN3a08y46SYmgYTeLdBX
  162. /DHSZIKWI9rBiNg6Qw49N+06XwiBAoHBAOMZQbRT8hEffRFbxcsRdJ4dUCM1RAXV
  163. /IMLeVQgKEWETX3pCydpQ2v65fJPACfLLwwRMq4BX4YpJVHCk6BZh/2zx8T1spmJ
  164. uBkHH6+VYgB9JVU0hv/APAjTZxdBjdhkaXVxccpmBBJqKKwOGf3nRVhmMsItBx2x
  165. ZCz+x50+buRMTKsF+FeK2Dr2e9WrfMkOJ3nQFwbGvOBIQeXKmu0wYUVyebnCdZW5
  166. pKI0Co7wp9soCa02YvTFR8n2kxMe9Y91jQKBwQDSD/xSsRfgDT0uiEwazVQ2D/42
  167. 96U2MYe+k+p1GHBnjIX4eRPcWOnQNUd/QVy1UK4bQg1dVZi+NQJ1YS3mKNCpqOaK
  168. ovrgHHmYC1YIn8Xmq2YGzrm/JLwXw0BkPhHp/1yQVPVgyFKeNa3fSa0tkqCed5rs
  169. erM8090IIzWPzKtXId8Db4i0xHkDzP7xDThb6pPNx5bvAaempJRDLtN9xP/hQRyh
  170. xZ/MECKGRgyAVfndIZaI82kuUQFlnPMqk4FxFhUCgcAhnMdgzVvytNpqC09HMxoz
  171. nNsTmvqqcnWhX71hejD7uQ1PKYMBHk9gWA5YwuCfAy+/dXwuzP06ejSP2WDIRvgd
  172. 0NIskMESgJPDAI7sCgwrTlqMNe4VRHqeQ8vqYUWBVbtWKqhQ8LCBmTzT2nJ2ZhiZ
  173. cObqXofDGVJeZodc+rSnDbP7TDLpoh9G+txxT6R0jafCG86MrjWebJN0U3yCxrpe
  174. 8QabO/DzbDq110YIyg3OHirwfDBBUkHB3sD9/4MQ7LECgcEAs2UFhxVIn4aO5ott
  175. +0G5lkYIQ6cwx9x64i3ugDvz2uruiunUJU0luTOXML2AUDRrzEmXokr0nBQnWlk4
  176. 2qOmuA3PfTx85iJLUab0vX69gyaDhnLLvMrBe8W62yELKXx076ouuI27yPNs3xFL
  177. vWzIkSzx+N0870i8LjPrjTgsZ8g8bfG1nTNhafaLDw/MPutReN7oLouKQs2w9MMr
  178. yPAR2qxBqIJe2uY4pdVy3bMPJWOG7MR74hs6By6HmKfKVuqVAoHBAMRSefX1QtfS
  179. 3wWpQhkE7Sooco4LI8kfNncZ2gzNDbYf6aOkgzv0/SWJh+CdcKep9xk12O02Lpsm
  180. SsPYeYlPDCCvyJYGpR19QocYp6JCaemb7uMd6FuPHSHUgyoR4GS8PUuIbiRnpPxN
  181. 4ta7VzmIZOCFu5e+vOq1NwTd0hR6sy5uNsTHV5ezOOqz2SB+yTRMDPr7cW0dMSJ8
  182. jsvxvqVnkIhWeuP9GIb6XUhq74huGZ0Hpaxe6xG34QYiBpr/O3O/ew=='
  183. """
  184. )
  185. normalized_root_key_pem = normalize_privatekey_pem(root_key_pem)
  186. intermediate_cert_pem = b"""-----BEGIN CERTIFICATE-----
  187. MIIEXDCCAsSgAwIBAgIRAMPzhm6//0Y/g2pmnHR2C4cwDQYJKoZIhvcNAQELBQAw
  188. WDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQHEwdDaGljYWdvMRAw
  189. DgYDVQQKEwdUZXN0aW5nMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0EwHhcNMjAw
  190. ODAyMTcxMTIwWhcNNDcxMjIwMTcxMTIwWjBmMRUwEwYDVQQDEwxpbnRlcm1lZGlh
  191. dGUxDDAKBgNVBAoTA29yZzERMA8GA1UECxMIb3JnLXVuaXQxCzAJBgNVBAYTAlVT
  192. MQswCQYDVQQIEwJDQTESMBAGA1UEBxMJU2FuIERpZWdvMIIBojANBgkqhkiG9w0B
  193. AQEFAAOCAY8AMIIBigKCAYEAo3rOxOVrdLdRsR1o0+JG7MRpCtMoafA63TM/DczL
  194. Q4jURv5MzyTE7FFdXq4xNJRYgD16vUavZluQGj30+5Lkt07CuO/BK3itl8UW+dsH
  195. p95gzBvgnj5AVZGkNOQ0Y4CbXO087Ywep7tpBfZ5fzURLeH+OHQGseEFZ5e0w8Az
  196. AarWu+Ez5RGpkaZ61iiJa53mAgkrjw+o83UrpDT2nrXiyR6Fx4K4eb1rarodWqGv
  197. jSkdT5MA4i0gDhsIBnTarPB+0KM8M7od8DkLsTHBt4rYYCHgCX1bWavzGlqPEw9h
  198. ksK+LAbQKD9J2AxYDkL0PAeUuvWMhxEmN6hXePiw63sJzukRunAvut5A2+42JMkW
  199. guDyqIvAjlCYcIyBvUbphP3qSFqww/hpZ2wh5UZOc1mzYJKR9MgI8/UhRJEJ7NyY
  200. pF24EJbisjNE30ot8aM2/5cI5KevclcuPJWH8PjT/i1VnNpM4S8MqoPw6F+d75d/
  201. CtfI+LLfns4k3G9I+Qgxmpa5AgMBAAGjEzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJ
  202. KoZIhvcNAQELBQADggGBAFVQ3Dmljrnbjys9ZIqcTs/B5ktKUAU2KNMO9TmoFymE
  203. YhHKbCb5u/CnWq3jtBW6jgkQHrhfY9leUlH87BkB2o16BcSKjHknHZ2MCdEvQvOM
  204. /nkkMDkOEoRn8mfCCxxgt8Kxf07wHDcnKoeJ3h9BXIl6nyJqJAcVWEJm1d75ayDG
  205. 0Kr0z+LcqMtQqYI0csK/XDQkunlE95qti1HzxW+JeAf6nRkr7RNZLtGmUGAMfyBK
  206. 9A0Db8QLR7O92YEmwoXtp+euN6uDdjw4A7KHjNXMdvqZoRfbZEA9c6XJTBj22h87
  207. gYUFRVpkNDrC/c9u6WgA943yMgFCwjrlTsmi+uoweT9U5r4TA+dVCDAv943aWCNm
  208. A+TiuIXlJAHl2PlH7Umu/oMQKDEt+0n4QcQLBZyK3CYU5kg+ms9vOvE19Lhp8HeS
  209. xqm6dwKpdm7/8EfGNW3s8Gm4KM26mb7dtSdHJFuR/BQ5y/cn4qIMyeGfHvsVew+2
  210. neyFR2Oc/nUlZMKfyHI+pA==
  211. -----END CERTIFICATE-----
  212. """
  213. intermediate_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
  214. MIIG4gIBAAKCAYEAo3rOxOVrdLdRsR1o0+JG7MRpCtMoafA63TM/DczLQ4jURv5M
  215. zyTE7FFdXq4xNJRYgD16vUavZluQGj30+5Lkt07CuO/BK3itl8UW+dsHp95gzBvg
  216. nj5AVZGkNOQ0Y4CbXO087Ywep7tpBfZ5fzURLeH+OHQGseEFZ5e0w8AzAarWu+Ez
  217. 5RGpkaZ61iiJa53mAgkrjw+o83UrpDT2nrXiyR6Fx4K4eb1rarodWqGvjSkdT5MA
  218. 4i0gDhsIBnTarPB+0KM8M7od8DkLsTHBt4rYYCHgCX1bWavzGlqPEw9hksK+LAbQ
  219. KD9J2AxYDkL0PAeUuvWMhxEmN6hXePiw63sJzukRunAvut5A2+42JMkWguDyqIvA
  220. jlCYcIyBvUbphP3qSFqww/hpZ2wh5UZOc1mzYJKR9MgI8/UhRJEJ7NyYpF24EJbi
  221. sjNE30ot8aM2/5cI5KevclcuPJWH8PjT/i1VnNpM4S8MqoPw6F+d75d/CtfI+LLf
  222. ns4k3G9I+Qgxmpa5AgMBAAECggGAc0i/V4qR5JUCPuyGaCVB7uXzTXbrIQoP+L2S
  223. 0aCCFvX+/LGIaOt9E0mtln8wo+uZHZY9YAzg1EXtsRPQFzjXoY0hNFme15EamdSb
  224. B0e2dmMTz9w44l7z72PtcH8dkq224ilKthoB5Db9MP9HXrWFj9228QihT/9nWE5b
  225. Y0++qIZZN9TwS7HQ6q2EIlIj1ohbE0R0O0bH1ifixsGyyOlrLHkhzjgY74Dspy7o
  226. VGmA6wL7cIoyLU21NT1Kw4LUUvCk3MTd62gIg43qLsoLJ1AVZg9AmLmhZn4HiGZa
  227. tiE1+Iz70E+qxIXDQTip/EY4qe9HHYM2VccjlMQsLLCw5Y2CJL0xbRUSPkKev+Us
  228. PyasHgxPP6s5sHTKm0fee+riJrR+CqODGT45CirJr+WjDznlJETgVDW5DmtTWGVW
  229. 2WeBarXdYOn4S+uK3Pe3aTAiE9Uw7KrOdJqrWg89YFnMWw4HlMz0369HCUv5BqSg
  230. qtrJ7iPJhN5MMhA4Te2Rnc5onqEhAoHBANKmZP4/g5RoYy6Gjkwe9PSgp9URxCJt
  231. VHiE5r33jXxOMw2lJQD8JVLmWuNTbKEClj6Rd/5OzM2q2icYDu0k/wcX+BgXg5b2
  232. ozyfjzgnqddKs8SlNd9oc2xiFRLgBkdHI5XFQlcp6vpEM+m47azEw72RtsKObN0g
  233. PZwSK8RWTj4zCXTdYMdr+gbdOA3fzUztckHLJQeS42JT3XJVSrSzFyXuVgXmdnS9
  234. bQ2dUfPT+JzwHy/HMmaBDM7fodDgv/XUywKBwQDGrLTomybbfc3ilZv+CZMW7bTy
  235. pX8ydj6GSIBWLd+7gduQHYqam5gNK2v4BKPVHXMMcRZNIIId3FZztMaP3vkWQXIG
  236. /bNBnL4Aa8mZFUle1VGoPZxMt1aaVLv3UqWi47ptciA6uZCuc/6si3THTsNr/7kR
  237. k6A7UmA0CRYWzuezRsbEGRXZCCFGwJm2WCfewjNRqH/I+Kvfj06AddKkwByujfc6
  238. zQDH/m0QFNAKgEZYvFOL/Yd2cuFhU2OPUO4jFgsCgcBXRbjx3T6WbekpjXXG88xo
  239. zWa7T/ECkmk8xVMTwUxNA9kC/jimf9C219kv9ZA75OZ6ZaphIiSX0QEw0Tbd6UX/
  240. ml6fHJ7YHLbklvavPT+QgtKX1hrLxGqNrNUuTMJNJZwIoQErO6KurTMU0hkmSx8N
  241. myEs2fUgaAsebijT3y3rdxmj4VQHSyT7Uwu2M9LK3FVKDO/6g1DRnA1TISMiWlBs
  242. 1qGtMB5Dn3de/J7Hdjq6SoGhOdYXwb+ctepEr9jX8KECgcAE2nk86XVkjUk3TNJX
  243. vWIjgEEYYGSgFfVnEGRaNpqtmPmFJsOZDU4EnFfx4iMidKq31hdmYPHsytIt12+2
  244. WgsZuRWRCCeV5b9agUeWfsehEnMBOigUU7JA6OsCmrlDJm8Kd2xEIv5e1KSXEH0U
  245. 1V6+x6t8u2+Bo3yIKOSqP/m3DnaSmc5H1AQEF3Zp1vN6ZKIeT5B3l2OTfYu8ZaR0
  246. s+C/fuZYQGPRfuypJOkEKKgPSOJ9m/7wLNRGrWPUP3Th1IsCgcBb2O9ROv793a3x
  247. PtW4qzkqF69KKc2O/vT819NBQjGopQetOcsY3VHp0eJMv85ut4cCeqScAfdtFIiC
  248. ScnrBO4JtdE6FkTY1k8el1DrctrUR3PZ2rt3m5k2XfPDGEypH3BReD3dHUe2M99D
  249. +dceH46rKyMXQ2lLA3iyzGE6NyWUTZ6co35/Qm2n8lV9IG1CuX5HVAVrr2osLG93
  250. zZvFSeTrN2MZvmelhS6aUJCV/PxiQPHlou8vLU6zzfPMSERTjOI=
  251. -----END RSA PRIVATE KEY-----
  252. """
  253. server_cert_pem = b"""-----BEGIN CERTIFICATE-----
  254. MIIEKTCCApGgAwIBAgIJAJn/HpR21r/8MA0GCSqGSIb3DQEBCwUAMFgxCzAJBgNV
  255. BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
  256. VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTIwMDgwMjE3MTEy
  257. MFoXDTQ3MTIyMDE3MTEyMFowGDEWMBQGA1UEAwwNbG92ZWx5IHNlcnZlcjCCAaIw
  258. DQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAKU9txhKg6Nc0dVK9Vv4MYuYP6Hs
  259. oR483+wC53V8axkfy2TynrBSug8HapeSFW5jwdwcsjaDwEIAugZfRoz0N1vR/Q6T
  260. OFAYn2hRwlAgUXVk3NXpDNV/QRliGvxhLAVpvu1a4ExfVZoOQyPa8pogDgrUdB3e
  261. tYmmFHNa09Lv1nyMZWi6t7zH2weq6/Dxpm0BWf+THFcunv9TNfAqmDV5qbxvaUPh
  262. uvRpN+X2N3tejB8WKt+UmzAXUi3P3OgYimWXwq8Rmorc1rk5j+ksl6qYwZvi7rRV
  263. g1ZAH7bGhXC9eEU/1Z9q26OhAPdTyJD0pc+G9vMz6VijLRXcgHBUP09lSeqxnNxc
  264. pWoX6nRdGn6PkDhewHM05iqAE3ZHnc8kSBcRX85SoW5dGOhvvUTs4ePVNTo3vHdQ
  265. vftTDD+I3rbFnYTKUAzHTPSWGE7LVEiWJ94RKSADXgve0qq8o377UMnY7W3UygSY
  266. odyUZ29B5EfZ88EpIs/h5NomDv5VcQEoCWN1owIDAQABozYwNDAdBgNVHQ4EFgQU
  267. g1V3LV4h8UkMCSTnVAkSjch+BK4wEwYDVR0lBAwwCgYIKwYBBQUHAwEwDQYJKoZI
  268. hvcNAQELBQADggGBACn0LsqO94tk8i+RbG5hryNduem9n8b8doYD97iaux6QLvY/
  269. A8DFduJtUevZ3OCsRYQSGa3V/ysMzN7/DIUkpRLevZmdw+1L6PGR7peR2xIQ+yEW
  270. bL88vLjezaYIzMKHJRmN8oP3DQtGJm6U2fMMiEHWqRtULIVpnFppzPI2z7+tDeyg
  271. PFD2YeiFWoq5lmXStrK+KYPJbhTn0gz4QlGBs7PLY2JMDRSVj6ctkvrpXbC3Rb3m
  272. qo2FY/y51ACg77Txc6NAmNE6tCknwaUjRQP2MuoYFm5/Z6O9/g49AEVIE101zHqV
  273. N6SkcTUaXAuQIyZaqwdndfOB4rrFyAkoxTM5OamIQl80hZKf4R5rM7D7Sz8kAWJi
  274. BPIcewN0XnI6lm+zPAVUAE8dZfgJmJR5ifZHYCuv96EX0RpYsddeik8UmjkZ2/ch
  275. vRzvRSNNxVC6Zoe6vKNUb89XMtJZqY80WxfWG3Z2Hwf9KvS+2KAH/6MiSMj0RI5F
  276. SCB2PMQm6DYXwM1EyA==
  277. -----END CERTIFICATE-----
  278. """
  279. server_key_pem = normalize_privatekey_pem(
  280. b"""-----BEGIN RSA PRIVATE KEY-----
  281. MIIG5AIBAAKCAYEApT23GEqDo1zR1Ur1W/gxi5g/oeyhHjzf7ALndXxrGR/LZPKe
  282. sFK6Dwdql5IVbmPB3ByyNoPAQgC6Bl9GjPQ3W9H9DpM4UBifaFHCUCBRdWTc1ekM
  283. 1X9BGWIa/GEsBWm+7VrgTF9Vmg5DI9rymiAOCtR0Hd61iaYUc1rT0u/WfIxlaLq3
  284. vMfbB6rr8PGmbQFZ/5McVy6e/1M18CqYNXmpvG9pQ+G69Gk35fY3e16MHxYq35Sb
  285. MBdSLc/c6BiKZZfCrxGaitzWuTmP6SyXqpjBm+LutFWDVkAftsaFcL14RT/Vn2rb
  286. o6EA91PIkPSlz4b28zPpWKMtFdyAcFQ/T2VJ6rGc3FylahfqdF0afo+QOF7AczTm
  287. KoATdkedzyRIFxFfzlKhbl0Y6G+9ROzh49U1Oje8d1C9+1MMP4jetsWdhMpQDMdM
  288. 9JYYTstUSJYn3hEpIANeC97SqryjfvtQydjtbdTKBJih3JRnb0HkR9nzwSkiz+Hk
  289. 2iYO/lVxASgJY3WjAgMBAAECggGAJST2X5OAe9yFnri25vGn0YVr6G5U2YM9osQU
  290. W6iYOpGXGx4e5evyvyYfo+rGvoXWMjCRLwf2099t8bjBFzZeq1lM1VXqtraSPtUC
  291. JRjettDxg3Rb2jI85APVpR4C00SuEpT3DrPvfi3ukcTJ/DNwdKbFY2GI1WRr/HJS
  292. Y3xebqjwstYmL12Nsu+NEiCAFMjU/kqHeGGWhDakTVSF2p96tE0nEIdRi1eLpTnv
  293. xt++B87n3FJ/gBP9+SZcth+uHKA8Wr42CqJR3z8b/blICYCd2LABFdZjL4aHfce9
  294. Xe7UyVoySYC6N0YSbLLfsVu/w/qsYitcTvWCyekX4eT2U9Sdje46LGN4MFJSYy8K
  295. Qw4hzz6JhUrAiwxPb2MLkq6q7AvdFwVAFl7xuH9J13yuN9x+w4NL9h3hzr4iC7nk
  296. xVrmme279h1hfuCR1+1Bb0fLvdl5VevT9SZYCg5BCL7JxHGofcBZ3ZE9R9Q7QYVv
  297. rCKHFZ5tIOkVJk2mcR5NvK6r7ethAoHBAM7BFvBPHgJ5xtny7M9xvaMQD9PZ3zzb
  298. PUD83lh+DlmLyzKLw2/OblyJgO8ECWUDNR1QkL5khq5Z2t1Kj77Hak7mUUlICbIc
  299. LKZLiAosuKBo/ps6emRRhIf9NNYR2G1k9GWyk3KicD/htllPl10j64vgBg2M/LQJ
  300. 2Oh95oWMck7RRdWHCwfBjND3YsYoN0hY9GXgr+ByDRQgAacvnpHlFCRmSPqiAJGh
  301. kPKIRfjLgVFbL1cIj7oHpcModgZr7Dgc/wKBwQDMmVhsmiefTscZSCoCIqXVsJJ0
  302. edDmIvAl3cFozf9/+5JADjnp/9zcdANNN/oMfynOPx+0R2CygxooZaRKbnHPcVlu
  303. SCxwaloagNSFVt8lZ2PwybutfdMN8YbU431ypNLJjInI3Z66eHBRDZZZviu5AtoL
  304. 5WYAvFzN502P1IVrJBo0lht7ftQMwM4NAhRaaFrUCrycREwUl0u9PxswmDhignWs
  305. +fyJ93D5aVC1wHjUN9WYTEOM66goZTuSDD8mE10CgcAbl3UiOMy+c9XvvBWSUZGH
  306. M1uJYCgEjRWNmLFridcMaDWD11cLkrbzrn4AZ7+BNX5fHSNT5UJ7/g3RPmQUh7RO
  307. Nzpd1zlEBbKHtsi+4tz4u0pPGOzAeoh/RXFJqDQD1VcwQzaeM8NbIxocrRx8F5EV
  308. p53nLQuEU1QZIsQiym1uy0rQhicYr+HE+V67Jx7JjuV+uw99mnrYVrUhxJ8axUF8
  309. 4hGXMQt2Y+NeGoWMAEyPuOWGbeQQZXjfpISrsrdhfa0CgcEAxqbdRBUpA3Tpu5Jl
  310. t00M1z5p9M2SFuE1ao61i5z3xrvsdGVbtefH+gRqcD85eYi+fpKrpc7oBGtmqnKF
  311. 4f76YgAcZQeOnlekxLbxocWHRDnuv4wfvYO9uHwZ/fojg3ylbSwXXABSbZsi8o/O
  312. u7P5n9k0/Pfu4igBs6oxlMU0BaM4DnbwmCe8m+VYKykpud440kjaeJ+XfyanU0hC
  313. jhw+Iueoehr/KLYn6wJmaxJGP0c3DHh/3gOxcgdYn6VkawPBAoHBAMJ7jfxZJfBO
  314. i0gDsD9Kz3EkGI8HbBpgC2Cd9DGQR9qTZy1/l/ObM2jwNumJjoHsN8fkha1d6/3n
  315. 01hA4LwLB/SLQHx+7k1749sH7m1FaczWa9eUxNkwFiVTBYIyvbekNfJogLX9pVow
  316. vEuNe+J8vxLt3gQJ1DUz+2Air8v//OIqQ+akDnPkwiqHDqynNNWO+jq708aUunVT
  317. TTvknsoT3qT8H/N1FwbCZ14eKV+bXHcv1lVrLdW/DnjDZRpMFa3LSg==
  318. -----END RSA PRIVATE KEY-----
  319. """
  320. )
  321. intermediate_server_cert_pem = b"""-----BEGIN CERTIFICATE-----
  322. MIIEXTCCAsWgAwIBAgIRAPQFY9jfskSihdiNSNdt6GswDQYJKoZIhvcNAQELBQAw
  323. ZjEVMBMGA1UEAxMMaW50ZXJtZWRpYXRlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
  324. CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
  325. biBEaWVnbzAeFw0yMDA4MDIxNzExMjBaFw00NzEyMjAxNzExMjBaMG4xHTAbBgNV
  326. BAMTFGludGVybWVkaWF0ZS1zZXJ2aWNlMQwwCgYDVQQKEwNvcmcxETAPBgNVBAsT
  327. CG9yZy11bml0MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExEjAQBgNVBAcTCVNh
  328. biBEaWVnbzCCAaIwDQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAL3UcTxwCsMZ
  329. qIE+7lolm8t6lT0IYZkE4L7u2qI64m9CvztudqqKYZcrprZobZxqPhqc8IO3CFR2
  330. nVzwZWxrHCcm6nAzJjVXUFrc4TLsVYYJL1QvKXxr97VIiySU7x6xWrQQsqDtlrb0
  331. jH59EYFbM2eMk2fBT2X4h6YMXlqyrDjZF6apClXtkdxGJGqR5PCTs4cvrYW7TpIm
  332. cuJq0S+MRBguZpriM+wOK7cXrqfRPFRzZtPXskpQPSAMDDAOGKl8OZfoVFYzG8KG
  333. omOa0hcHtgYX2GCDs1g1maY6Haw9bgs041BoApH9aQxehy5dfU39DcFoKSE3dCjR
  334. FaR6ryCA+f8L1F3xVaHsvX443CYF0/holfsptTjNd1T1z8WR5h1jtY0gJ/ERgcJZ
  335. UgDRE3lEkTLExS/nuGVfdwnlkxny9jbtYp2YcjYjUkChLtTgz4ommeIdBdDvSu8M
  336. wWHMtQNxECs5qA5J384cLh11Nd9exWUjiQ9yAZ0qTOzTkdH7VPHfxQIDAQABMA0G
  337. CSqGSIb3DQEBCwUAA4IBgQA2jC5hJ/+46RLBuaZiJhBawiY+HqybEAZWM/IBGZO4
  338. UKcRotovU+sb1jg+vpXwePSBPEtQoZce0jN0TKiCdlLM4/9lybAvc6qBLJ0d4VS5
  339. BU5QsCs9IKyvswAFVipQZi0szYwHk8T145SH/fPao8oznf5ae4a6rK9PyZqT7Ix1
  340. nnKGffbJs0dY+jlxmx/BPlbsGfTwPL6LexghjvbpbXWUdVLP3gAW6DPCtRd6lhWj
  341. JvgCkF2SnbQ7GgnPEYi8h09j0c6/sK6jLoNAatJyIlRGE1cdGYZVUlVW/xP6lYM0
  342. Mi1KKl0ZXOne4vPTtnTBBqrpjdLydH3WM1IxdwSRbmF15OD6BWzzKV4IYUJ21GDh
  343. YrVrcIeN49pUoKVTTn0Sql8f8mXxJhJ54wo9TKdIGZeuwTZrfWjcjWghXgghXGoP
  344. RI/I5fk/OMu0Oc06/+xdwCBHCSge0/vxK6fhTu7PxmJhQcZF0sDZyb6LXm2feVkG
  345. 6FsxnsvstVNO3oJdpa8daLs=
  346. -----END CERTIFICATE-----
  347. """
  348. intermediate_server_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
  349. MIIG5AIBAAKCAYEAvdRxPHAKwxmogT7uWiWby3qVPQhhmQTgvu7aojrib0K/O252
  350. qophlyumtmhtnGo+Gpzwg7cIVHadXPBlbGscJybqcDMmNVdQWtzhMuxVhgkvVC8p
  351. fGv3tUiLJJTvHrFatBCyoO2WtvSMfn0RgVszZ4yTZ8FPZfiHpgxeWrKsONkXpqkK
  352. Ve2R3EYkapHk8JOzhy+thbtOkiZy4mrRL4xEGC5mmuIz7A4rtxeup9E8VHNm09ey
  353. SlA9IAwMMA4YqXw5l+hUVjMbwoaiY5rSFwe2BhfYYIOzWDWZpjodrD1uCzTjUGgC
  354. kf1pDF6HLl19Tf0NwWgpITd0KNEVpHqvIID5/wvUXfFVoey9fjjcJgXT+GiV+ym1
  355. OM13VPXPxZHmHWO1jSAn8RGBwllSANETeUSRMsTFL+e4ZV93CeWTGfL2Nu1inZhy
  356. NiNSQKEu1ODPiiaZ4h0F0O9K7wzBYcy1A3EQKzmoDknfzhwuHXU1317FZSOJD3IB
  357. nSpM7NOR0ftU8d/FAgMBAAECggGAYNwla1FALIzLDieuNxE5jXne7GV6Zzm187as
  358. mFqzb1H/gbO7mQlDAn+jcS+Xvlf3mFy73HloJrDfWqzPE6MTmmag+N8gf9ctiS9r
  359. OTCd8uZ839ews2vj2PxLAz97Q437WiWq/7I7VN8zUNdAN2DxucRg8nAQs1c8390v
  360. x9ejSN580u0t+OpfoqWnrzkCOD8lO7V4NOR+EtTLifw3AKvxkuUaNa12ENyqMaJD
  361. 3B1HS1AXB8DnmEOY7OE41sxaiSB44M7tsr31ldUCbEf/A5OZWeCfloP2c2g+Td8s
  362. +sl+AzoGa1HsFOqiqdDw8lKynfT1VukaaCtOr0pGeh6XW65aHRGI0B+mHIEM7yR0
  363. f2NjfvgejqNekWyJ+XeTcmrPPcSH72F9ansLRpUullAi+6OkPFIiwyKCP/S2sLwh
  364. cqe3NITfMweWDt7GqgOhz1yWaewXgdruWiFAYAh2JDBtgMWTUwWgkKyFCb4mrI6r
  365. zqiBpA8Mjm/H17h/dQqF3iRuaZOBAoHBAPDvVseeiGwZjDXuQD9acCBZU23xwevR
  366. 6NVe/FLY1bybgsOBQCApQIWKH72eIHo12ULRMe/uZUo3su9JSCc8Gt8DsQpiZ2a+
  367. z8rS6uEw/UZGMWeLjcIVK5IeeD7OJ/BXEbwoxVvWLYYgWHpYwY9eqppsMlVqmIHY
  368. lfRAaepEkU/4euRl1VTFxkU0sYw7Tj+gbFQDydB0NSLIU/x10tlHblT+O5tgBLJh
  369. kL7II9tyoGaCUjNnACErmi1FA+lNsx1eAwKBwQDJsw+sIhujRHrajCV5dqq5cx3h
  370. ZQNfamoX6xfXYjNHjkeFnFpHB2w6ffe00q2Kt5+0AaSA295n1vPx6IKzKYMr8kpD
  371. 0Kiv+mlKK5w7lZzdCeoJb8Co2t9viZXrN9lNetXiSZldrg5nlG8Gmi2RKn65vIfp
  372. ZFc8CExXpQWNMSLJlu2qM8Sjt4h8M880khuTggCeIDbw7YfyanlNhsNpOGv/r+Hd
  373. 3i0BP0Qd1sZWkZ+hp/JJFdvyEh5vINgSABfNJJcCgcEA8LqioVcEBcZM8oG3jdVF
  374. 3PyDQIHieUXFdpOuVvSyMf3LXJ3ivX+aKRNF/YZl+tWc24b7dzhh2hLm5PD6d8E1
  375. NAiTNsX1fJJAOe4dopz5IuL1b/jezcGrRBbPnCkNfLTyUmcGMmlAGRhubugJlb9H
  376. hH2AmRmlgW8u/NnzOZADBL1HxLb+vPHS1cj9cRi8aRRXyGX0miPSB4vTZpcu8cvO
  377. MHvIgMkiSDz1i7mbIiNYorOpgBR066+OH5cqfkwVH82TAoHAO3dZdYyQzXARMIIF
  378. QmxkJUz1UFCxz93V7btYSh4ftEcUeyX/z9U2aYBeGafLloxQv4eEcqFgTwkm3vmI
  379. Hz5r9/b1Qk0wjsGrbTyyUTbpCpozsBiMmrv9CCtuUe0jWh6PFKpSVzZL9OnkWfP2
  380. 30fCGQymnX8B4ScpKuXyXxBPi1O+OmIM5Z/k04mK25sAGltHx1cEG8BMRoJxxROo
  381. ZUtHPBkk5H7ukeGPOaTq0PcaM1UKr9WMBTCmXGk4iwYP/mF9AoHBAOTlFVgGbbjk
  382. Cp/Wd7IrYCBKlnkIyBUMx5icLcsFmgXWx+Gx1HualD2aZ7kctYOfo+zLEyA6roni
  383. bSFLrxT4Od4uqwb51iZoJWxO+C3H1i9NoieU5JOnw5Osyl7OMXm3DkaS/N+ipP/b
  384. 3bx1y8/WnGgqWWguXKt2lmgOItaEKrXYr6VZ1Z4upnLtkbxLANnqkQcL9287tXaW
  385. GPVXEteEXrtPj1f+9QYsMKuTWfaw6XfnBkBHxEZgWR+2hAN2z3c/Eg==
  386. -----END RSA PRIVATE KEY-----
  387. """
  388. client_cert_pem = b"""-----BEGIN CERTIFICATE-----
  389. MIIEJzCCAo+gAwIBAgIJAKxpFI5lODkjMA0GCSqGSIb3DQEBCwUAMFgxCzAJBgNV
  390. BAYTAlVTMQswCQYDVQQIDAJJTDEQMA4GA1UEBwwHQ2hpY2FnbzEQMA4GA1UECgwH
  391. VGVzdGluZzEYMBYGA1UEAwwPVGVzdGluZyBSb290IENBMB4XDTIwMDgwMjE3MTEy
  392. MVoXDTQ3MTIyMDE3MTEyMVowFjEUMBIGA1UEAwwLdWdseSBjbGllbnQwggGiMA0G
  393. CSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQDGChdOMY164FScJqfiJ5LEtjYOKEg4
  394. nmMAMGuHIT8wZZEfzaaHhBbypzKq2cPP1qtyHgvtUMM6KOFEj4y9AonqzzdlVxbM
  395. i6+AvYLWlPoB5r/G1GdslUvXbc7F02B/6sB/+iFXmcdjOjAQcLWxVgUL+1CoeoY1
  396. awNYmzQueK/T82a/6AYTdrx7XRX4wfxjYb1o3bnnRD/jGSakIylXeUGFsiSNkBs/
  397. dJMkUONxizAdAE2tW6NhPuE2O0UipzUhdgFnH6WPfJ0J1S7jZ3eQTUrLkFpWSp/Z
  398. hx/l/Ql9vO0wagHaT2wOiZdKVT8S6V6OPzJ7/H1evCoM6EuSPBC5DDP1nPetCK1v
  399. uC9kb7Dg6yFPt1CKrVFt0Y6W5Y5/GzisUtvYV/OGtX4DOwL9It68D04Qrvun1t/a
  400. Dh/c5gKqfqIGHUvUucFmOi6DrRpadfraLZMRGN2ysPjoVwhMgwwSmSWhziQIUfxK
  401. oyz1CUsyr5Gh5gdifbe1AOYwu6YdtlmhqCsCAwEAAaM2MDQwHQYDVR0OBBYEFINV
  402. dy1eIfFJDAkk51QJEo3IfgSuMBMGA1UdJQQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3
  403. DQEBCwUAA4IBgQAhAEACc1j6EYoSfVJD8N/FlYfHRizdfVJyrmMnC8ID1vtfrU2z
  404. S2q+49ja2NyM4Sq+Cf+i+sFfzFG92LayZt9Mc1BnHZMdNzQL7Ynr2nDLxHsHzuYa
  405. N21/ucTpHEFGLmvQ/eWBMxQQ9TbiNXn+tnnqg46dRzN3vHJp+g5+ijtMcuh007z2
  406. niiO8F07wlb960XviejWejMC8hBLWlA7i3EjAkDO8RFQnG2Py5cQX9GgmWH1sDy3
  407. rIsWlU+e46ysSWK/bnudnAlzZMB9KJATVZu5+xmCumH2hLJv5vz+jnKcgU9MBZMO
  408. cKgNdFUbtRlU/gfTaohmLIuSquunCCrXLsLD8ygbKKXfSPGVo2XkvX3oxqUo6dmA
  409. LvU4N4sCQGiSzW+a13HBtk3TBZFsJSWUGSW/H7TVFiAonumJKRqRxMOkkB9JxX+V
  410. 9LZBYuBLpOeK4wZ8BUSNlHKnGpDzl0DzdYrGlzWz0jXlLGZ8KMfXAn9h0mOZ+IyK
  411. eUlgMBYyAspCQzM=
  412. -----END CERTIFICATE-----
  413. """
  414. client_key_pem = normalize_privatekey_pem(
  415. b"""-----BEGIN RSA PRIVATE KEY-----
  416. MIIG5AIBAAKCAYEAxgoXTjGNeuBUnCan4ieSxLY2DihIOJ5jADBrhyE/MGWRH82m
  417. h4QW8qcyqtnDz9arch4L7VDDOijhRI+MvQKJ6s83ZVcWzIuvgL2C1pT6Aea/xtRn
  418. bJVL123OxdNgf+rAf/ohV5nHYzowEHC1sVYFC/tQqHqGNWsDWJs0Lniv0/Nmv+gG
  419. E3a8e10V+MH8Y2G9aN2550Q/4xkmpCMpV3lBhbIkjZAbP3STJFDjcYswHQBNrVuj
  420. YT7hNjtFIqc1IXYBZx+lj3ydCdUu42d3kE1Ky5BaVkqf2Ycf5f0JfbztMGoB2k9s
  421. DomXSlU/Eulejj8ye/x9XrwqDOhLkjwQuQwz9Zz3rQitb7gvZG+w4OshT7dQiq1R
  422. bdGOluWOfxs4rFLb2FfzhrV+AzsC/SLevA9OEK77p9bf2g4f3OYCqn6iBh1L1LnB
  423. Zjoug60aWnX62i2TERjdsrD46FcITIMMEpkloc4kCFH8SqMs9QlLMq+RoeYHYn23
  424. tQDmMLumHbZZoagrAgMBAAECggGAAXA5UxwRBv9yHeA5/+6BpmQcaGXqgF7GIU44
  425. ubaIGvXh4/U+bGWNNR35xDvorC3G+QE23PZlNJrvZ+wS/ZxzG/19TYMga0Podmrp
  426. 9F0Io9LlObB5P9SlxF7LzawHW2Z9F3DdpSE8zX+ysavf5fXV+4xLva2GJAUu9QnL
  427. izrdLBDsgiBRSvrly4+VhUUDbEVddtGFdCSOwjuAiFipCDWdQDdXBKAzUnaqSu07
  428. eaulIdDKv6OWwDIQuLAdhG7qd9+/h5MB/rAG8v4bgbHz1H/RZw5VIOuOhfCodzJx
  429. 3Smfh5td21jwJ2RfZYEPNOMtFa9eRFtH2/uRa5jbJiZb8YWIzWy0xCNQpKheSoBO
  430. wiuMDBS2HCYm2SgEYDdJiE2OkRAk0UwTiUmlmZd0a3NfJ/rfQE+JiDQ28Arj3EZl
  431. SY/V3KdviM4MbaoX7f9j9sjAe5Rk1M+yI8OsnM/hf77m0CSiJJpLpvgqhMjjT+NI
  432. aBm1FyTq6qu506d0YUZy+Wr2DRsBAoHBAPfshuOiDXo9UmJxM1mSJQ0rQlxWSWmX
  433. bIAsPrpKslTFYHk7xbcCbJCqMbHmCsyvYy3oW3SpJs6Vi2wQWuUQmsm0YC7qdkXF
  434. Fyo2f7vF7roQcXLxVmQRo0OxZ9JpLAZ9DKMEcNfYyUiQiqJmZuIyWKngqBl6OoL2
  435. 8EJSFjTY1tR/nDxGLpZSsqoZJWQGd9B2bK4y6NktDF1GkexCpKaSyXZT612JGPG2
  436. 0gSIwRq1OgZH3SPHevhVMjJtxGue2XARywKBwQDMfZHtdJI9RuurM9UuULZ72SmW
  437. oLzki3LwFQ/QoS9wrHK+OqQDWH2ddON1PoB4LOCpwB4CC83pMyfxurgLHut6saHL
  438. hQ5N+h0jUC2pSJOXZSfF2Hx8YHCT7Dga5kmgEy89c1TF48IL2LdUZQQIGZt8+FxM
  439. 4nxT9NFlu/UWY2oftT+ZwFsIock/DYYUKxDXw9YkOmt1lO5u1SKte0NdQ4RhBeqK
  440. nRADMSS9oKZkSUxkwaDJH2GkUVTyBsF/kmh+dyECgcEA6jy3yRQPxcFwOAAZ8vOo
  441. PAP2I8WGgNQHOCYVce8nA/6jwocdq2YH6rpST3E4HOFMRFB3MAas2pvh6UyehDOm
  442. +xGHmmv9KLgoxcJN9rvwbC0i8uVfqRYc+dUAcYTaiprVOKP2dYilzAB8ayly5R2K
  443. NZ5DVCbuZ1Ql9ZMW1gFVH9odY7kvROmHUjyF3jZaN0PcNM12v9HXD72gGudwJs0i
  444. uMBa7LmeLql7TbtjLvewhcSaA7bx0PS1g33ACapAZ6j3AoHAN2PsGz3wPtjvDTjF
  445. Df6e730rXrm7cMy1HYMW/ZQrnYGYsx5/PsjBfd0jn6aGdgbx9AkuF6/K3tgUgc3p
  446. /Fkrv9hN0yr/bO/K5L3bIHegQuoLk/PIBIi69daOe/rVBp8rtKGA3PmMnljdj+as
  447. 6OTG0VsU5V6T/snZzozTHnVfUaduyt7nybbJJGMtZlkj/s31O2r3oKnuy+a/te4l
  448. mSWovf80QMe6hqLRKOxTJecU4lXwj4oIkNHXCJf74epuk5MBAoHBALyvg90KzMFX
  449. ZEjdPIXULR6/3rub8yD7LVYbNhhYWGo8GybzsBUC0kczRpRXFnmbq1GDIXQf5A+2
  450. 3ZaGsWzAxLjvL3KwH1LUaXVWwFMOM2n6zTk18XEXrNvp+E5QtPwpO5c4VlPr0cAC
  451. tTPAmbu6kVPlQ6mKiqlPAsfh0BD2mRVo2cTjZgDotKshb5uCHD8/PnCfOjCXFxOf
  452. DWjBuR73/r5Bj+ktRoD4V2SFdO6loJwH6B8rsBjD0NbAGs9otKvy+Q==
  453. -----END RSA PRIVATE KEY-----
  454. """
  455. )
  456. cleartextCertificateRequestPEM = b"""-----BEGIN CERTIFICATE REQUEST-----
  457. MIIBnjCCAQcCAQAwXjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAklMMRAwDgYDVQQH
  458. EwdDaGljYWdvMRcwFQYDVQQKEw5NeSBDb21wYW55IEx0ZDEXMBUGA1UEAxMORnJl
  459. ZGVyaWNrIERlYW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANp6Y17WzKSw
  460. BsUWkXdqg6tnXy8H8hA1msCMWpc+/2KJ4mbv5NyD6UD+/SqagQqulPbF/DFea9nA
  461. E0zhmHJELcM8gUTIlXv/cgDWnmK4xj8YkjVUiCdqKRAKeuzLG1pGmwwF5lGeJpXN
  462. xQn5ecR0UYSOWj6TTGXB9VyUMQzCClcBAgMBAAGgADANBgkqhkiG9w0BAQUFAAOB
  463. gQAAJGuF/R/GGbeC7FbFW+aJgr9ee0Xbl6nlhu7pTe67k+iiKT2dsl2ti68MVTnu
  464. Vrb3HUNqOkiwsJf6kCtq5oPn3QVYzTa76Dt2y3Rtzv6boRSlmlfrgS92GNma8JfR
  465. oICQk3nAudi6zl1Dix3BCv1pUp5KMtGn3MeDEi6QFGy2rA==
  466. -----END CERTIFICATE REQUEST-----
  467. """
  468. encryptedPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
  469. Proc-Type: 4,ENCRYPTED
  470. DEK-Info: DES-EDE3-CBC,9573604A18579E9E
  471. SHOho56WxDkT0ht10UTeKc0F5u8cqIa01kzFAmETw0MAs8ezYtK15NPdCXUm3X/2
  472. a17G7LSF5bkxOgZ7vpXyMzun/owrj7CzvLxyncyEFZWvtvzaAhPhvTJtTIB3kf8B
  473. 8+qRcpTGK7NgXEgYBW5bj1y4qZkD4zCL9o9NQzsKI3Ie8i0239jsDOWR38AxjXBH
  474. mGwAQ4Z6ZN5dnmM4fhMIWsmFf19sNyAML4gHenQCHhmXbjXeVq47aC2ProInJbrm
  475. +00TcisbAQ40V9aehVbcDKtS4ZbMVDwncAjpXpcncC54G76N6j7F7wL7L/FuXa3A
  476. fvSVy9n2VfF/pJ3kYSflLHH2G/DFxjF7dl0GxhKPxJjp3IJi9VtuvmN9R2jZWLQF
  477. tfC8dXgy/P9CfFQhlinqBTEwgH0oZ/d4k4NVFDSdEMaSdmBAjlHpc+Vfdty3HVnV
  478. rKXj//wslsFNm9kIwJGIgKUa/n2jsOiydrsk1mgH7SmNCb3YHgZhbbnq0qLat/HC
  479. gHDt3FHpNQ31QzzL3yrenFB2L9osIsnRsDTPFNi4RX4SpDgNroxOQmyzCCV6H+d4
  480. o1mcnNiZSdxLZxVKccq0AfRpHqpPAFnJcQHP6xyT9MZp6fBa0XkxDnt9kNU8H3Qw
  481. 7SJWZ69VXjBUzMlQViLuaWMgTnL+ZVyFZf9hTF7U/ef4HMLMAVNdiaGG+G+AjCV/
  482. MbzjS007Oe4qqBnCWaFPSnJX6uLApeTbqAxAeyCql56ULW5x6vDMNC3dwjvS/CEh
  483. 11n8RkgFIQA0AhuKSIg3CbuartRsJnWOLwgLTzsrKYL4yRog1RJrtw==
  484. -----END RSA PRIVATE KEY-----
  485. """
  486. encryptedPrivateKeyPEMPassphrase = b"foobar"
  487. cleartextPrivateKeyPEM = """-----BEGIN PRIVATE KEY-----
  488. MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMcRMugJ4kvkOEuT
  489. AvMFr9+3A6+HAB6nKYcXXZz93ube8rJpBZQEfWn73H10dQiQR/a+rhxYEeLy8dPc
  490. UkFcGR9miVkukJ59zex7iySJY76bdBD8gyx1LTKrkCstP2XHKEYqgbj+tm7VzJnY
  491. sQLqoaa5NeyWJnUC3MJympkAS7p3AgMBAAECgYAoBAcNqd75jnjaiETRgVUnTWzK
  492. PgMCJmwsob/JrSa/lhWHU6Exbe2f/mcGOQDFpesxaIcrX3DJBDkkc2d9h/vsfo5v
  493. JLk/rbHoItWxwuY5n5raAPeQPToKpTDxDrL6Ejhgcxd19wNht7/XSrYZ+dq3iU6G
  494. mOEvU2hrnfIW3kwVYQJBAP62G6R0gucNfaKGtHzfR3TN9G/DnCItchF+TxGTtpdh
  495. Cz32MG+7pirT/0xunekmUIp15QHdRy496sVxWTCooLkCQQDIEwXTAwhLNRGFEs5S
  496. jSkxNfTVeNiOzlG8jPBJJDAdlLt1gUqjZWnk9yU+itMSGi/6eeuH2n04FFk+SV/T
  497. 7ryvAkB0y0ZDk5VOozX/p2rtc2iNm77A3N4kIdiTQuq4sZXhNgN0pwWwxke8jbcb
  498. 8gEAnqwBwWt//locTxHu9TmjgT8pAkEAlbF16B0atXptM02QxT8MlN8z4gxaqu4/
  499. RX2FwpOq1FcVsqMbvwj/o+ouGY8wwRiK0TMrQCf/DFhdNTcc1aqHzQJBAKWtq4LI
  500. uVZjCAuyrqEnt7R1bOiLrar+/ezJPY2z+f2rb1TGr31ztPeFvO3edLw+QdhzwJGp
  501. QKImYzqMe+zkIOQ=
  502. -----END PRIVATE KEY-----
  503. """
  504. cleartextPublicKeyPEM = b"""-----BEGIN PUBLIC KEY-----
  505. MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxszlc+b71LvlLS0ypt/l
  506. gT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZOtPclNY823Q4pErMTSWC
  507. 90qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLjBuUIkQzEKEFV+8taiRV+
  508. ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPrUQqYQUEiTmVhh4FBUKZ5
  509. XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV215k4TeHMFYE5RG0KYAS
  510. 8Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6HXRpQCyASzEG7bgtROLhL
  511. ywIDAQAB
  512. -----END PUBLIC KEY-----
  513. """
  514. # Some PKCS#7 stuff. Generated with the openssl command line:
  515. #
  516. # openssl crl2pkcs7 -inform pem -outform pem -certfile s.pem -nocrl
  517. #
  518. # with a certificate and key (but the key should be irrelevant) in s.pem
  519. pkcs7Data = b"""\
  520. -----BEGIN PKCS7-----
  521. MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
  522. BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
  523. A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
  524. MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
  525. cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
  526. A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
  527. HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
  528. SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
  529. zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
  530. LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
  531. A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
  532. 65w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
  533. Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
  534. Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
  535. bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
  536. VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
  537. /g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
  538. Ho4EzbYCOaEAMQA=
  539. -----END PKCS7-----
  540. """
  541. pkcs7DataASN1 = base64.b64decode(
  542. b"""
  543. MIIDNwYJKoZIhvcNAQcCoIIDKDCCAyQCAQExADALBgkqhkiG9w0BBwGgggMKMIID
  544. BjCCAm+gAwIBAgIBATANBgkqhkiG9w0BAQQFADB7MQswCQYDVQQGEwJTRzERMA8G
  545. A1UEChMITTJDcnlwdG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtN
  546. MkNyeXB0byBDZXJ0aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNA
  547. cG9zdDEuY29tMB4XDTAwMDkxMDA5NTEzMFoXDTAyMDkxMDA5NTEzMFowUzELMAkG
  548. A1UEBhMCU0cxETAPBgNVBAoTCE0yQ3J5cHRvMRIwEAYDVQQDEwlsb2NhbGhvc3Qx
  549. HTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tMFwwDQYJKoZIhvcNAQEBBQAD
  550. SwAwSAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh5kwI
  551. zOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEAAaOCAQQwggEAMAkGA1UdEwQCMAAw
  552. LAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0G
  553. A1UdDgQWBBTPhIKSvnsmYsBVNWjj0m3M2z0qVTCBpQYDVR0jBIGdMIGagBT7hyNp
  554. 65w6kxXlxb8pUU/+7Sg4AaF/pH0wezELMAkGA1UEBhMCU0cxETAPBgNVBAoTCE0y
  555. Q3J5cHRvMRQwEgYDVQQLEwtNMkNyeXB0byBDQTEkMCIGA1UEAxMbTTJDcnlwdG8g
  556. Q2VydGlmaWNhdGUgTWFzdGVyMR0wGwYJKoZIhvcNAQkBFg5uZ3BzQHBvc3QxLmNv
  557. bYIBADANBgkqhkiG9w0BAQQFAAOBgQA7/CqT6PoHycTdhEStWNZde7M/2Yc6BoJu
  558. VwnW8YxGO8Sn6UJ4FeffZNcYZddSDKosw8LtPOeWoK3JINjAk5jiPQ2cww++7QGG
  559. /g5NDjxFZNDJP1dGiLAxPW6JXwov4v0FmdzfLOZ01jDcgQQZqEpYlgpuI5JEWUQ9
  560. Ho4EzbYCOaEAMQA=
  561. """
  562. )
  563. crlData = b"""\
  564. -----BEGIN X509 CRL-----
  565. MIIBWzCBxTANBgkqhkiG9w0BAQQFADBYMQswCQYDVQQGEwJVUzELMAkGA1UECBMC
  566. SUwxEDAOBgNVBAcTB0NoaWNhZ28xEDAOBgNVBAoTB1Rlc3RpbmcxGDAWBgNVBAMT
  567. D1Rlc3RpbmcgUm9vdCBDQRcNMDkwNzI2MDQzNDU2WhcNMTIwOTI3MDI0MTUyWjA8
  568. MBUCAgOrGA8yMDA5MDcyNTIzMzQ1NlowIwICAQAYDzIwMDkwNzI1MjMzNDU2WjAM
  569. MAoGA1UdFQQDCgEEMA0GCSqGSIb3DQEBBAUAA4GBAEBt7xTs2htdD3d4ErrcGAw1
  570. 4dKcVnIWTutoI7xxen26Wwvh8VCsT7i/UeP+rBl9rC/kfjWjzQk3/zleaarGTpBT
  571. 0yp4HXRFFoRhhSE/hP+eteaPXRgrsNRLHe9ZDd69wmh7J1wMDb0m81RG7kqcbsid
  572. vrzEeLDRiiPl92dyyWmu
  573. -----END X509 CRL-----
  574. """
  575. crlDataUnsupportedExtension = b"""\
  576. -----BEGIN X509 CRL-----
  577. MIIGRzCCBS8CAQIwDQYJKoZIhvcNAQELBQAwJzELMAkGA1UEBhMCVVMxGDAWBgNV
  578. BAMMD2NyeXB0b2dyYXBoeS5pbxgPMjAxNTAxMDEwMDAwMDBaGA8yMDE2MDEwMTAw
  579. MDAwMFowggTOMBQCAQAYDzIwMTUwMTAxMDAwMDAwWjByAgEBGA8yMDE1MDEwMTAw
  580. MDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAn
  581. MQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQD
  582. CgEAMHICAQIYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAw
  583. MDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlw
  584. dG9ncmFwaHkuaW8wCgYDVR0VBAMKAQEwcgIBAxgPMjAxNTAxMDEwMDAwMDBaMFww
  585. GAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTArpCkwJzELMAkGA1UE
  586. BhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNVHRUEAwoBAjByAgEE
  587. GA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAxMDEwMDAwMDBaMDQG
  588. A1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5
  589. LmlvMAoGA1UdFQQDCgEDMHICAQUYDzIwMTUwMTAxMDAwMDAwWjBcMBgGA1UdGAQR
  590. GA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJBgNVBAYTAlVTMRgw
  591. FgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQQwcgIBBhgPMjAxNTAx
  592. MDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAwWjA0BgNVHR0ELTAr
  593. pCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dyYXBoeS5pbzAKBgNV
  594. HRUEAwoBBTByAgEHGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNVHRgEERgPMjAxNTAx
  595. MDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJVUzEYMBYGA1UEAwwP
  596. Y3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEGMHICAQgYDzIwMTUwMTAxMDAwMDAw
  597. WjBcMBgGA1UdGAQRGA8yMDE1MDEwMTAwMDAwMFowNAYDVR0dBC0wK6QpMCcxCzAJ
  598. BgNVBAYTAlVTMRgwFgYDVQQDDA9jcnlwdG9ncmFwaHkuaW8wCgYDVR0VBAMKAQgw
  599. cgIBCRgPMjAxNTAxMDEwMDAwMDBaMFwwGAYDVR0YBBEYDzIwMTUwMTAxMDAwMDAw
  600. WjA0BgNVHR0ELTArpCkwJzELMAkGA1UEBhMCVVMxGDAWBgNVBAMMD2NyeXB0b2dy
  601. YXBoeS5pbzAKBgNVHRUEAwoBCTByAgEKGA8yMDE1MDEwMTAwMDAwMFowXDAYBgNV
  602. HRgEERgPMjAxNTAxMDEwMDAwMDBaMDQGA1UdHQQtMCukKTAnMQswCQYDVQQGEwJV
  603. UzEYMBYGA1UEAwwPY3J5cHRvZ3JhcGh5LmlvMAoGA1UdFQQDCgEKMC4CAQsYDzIw
  604. MTUwMTAxMDAwMDAwWjAYMAoGA1UdFQQDCgEBMAoGAyoDBAQDCgEAMA0GCSqGSIb3
  605. DQEBCwUAA4IBAQBTaloHlPaCZzYee8LxkWej5meiqxQVNWFoVdjesroa+f1FRrH+
  606. drRU60Nq97KCKf7f9GNN/J3ZIlQmYhmuDqh12f+XLpotoj1ZRfBz2hjFCkJlv+2c
  607. oWWGNHgA70ndFoVtcmX088SYpX8E3ARATivS4q2h9WlwV6rO93mhg3HGIe3JpcK4
  608. 7BcW6Poi/ut/zsDOkVbI00SqaujRpdmdCTht82MH3ztjyDkI9KYaD/YEweKSrWOz
  609. SdEILd164bfBeLuplVI+xpmTEMVNpXBlSXl7+xIw9Vk7p7Q1Pa3k/SvhOldYCm6y
  610. C1xAg/AAq6w78yzYt18j5Mj0s6eeHi1YpHKw
  611. -----END X509 CRL-----
  612. """
  613. # A broken RSA private key which can be used to test the error path through
  614. # PKey.check.
  615. inconsistentPrivateKeyPEM = b"""-----BEGIN RSA PRIVATE KEY-----
  616. MIIBPAIBAAJBAKy+e3dulvXzV7zoTZWc5TzgApr8DmeQHTYC8ydfzH7EECe4R1Xh
  617. 5kwIzOuuFfn178FBiS84gngaNcrFi0Z5fAkCAwEaAQJBAIqm/bz4NA1H++Vx5Ewx
  618. OcKp3w19QSaZAwlGRtsUxrP7436QjnREM3Bm8ygU11BjkPVmtrKm6AayQfCHqJoT
  619. zIECIQDW0BoMoL0HOYM/mrTLhaykYAVqgIeJsPjvkEhTFXWBuQIhAM3deFAvWNu4
  620. nklUQ37XsCT2c9tmNt1LAT+slG2JOTTRAiAuXDtC/m3NYVwyHfFm+zKHRzHkClk2
  621. HjubeEgjpj32AQIhAJqMGTaZVOwevTXvvHwNeH+vRWsAYU/gbx+OQB+7VOcBAiEA
  622. oolb6NMg/R3enNPvS1O4UU1H8wpaF77L4yiSWlE0p4w=
  623. -----END RSA PRIVATE KEY-----
  624. """
  625. # certificate with NULL bytes in subjectAltName and common name
  626. nulbyteSubjectAltNamePEM = b"""-----BEGIN CERTIFICATE-----
  627. MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
  628. DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
  629. eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
  630. RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
  631. ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
  632. NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
  633. DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
  634. ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
  635. ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
  636. hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
  637. BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
  638. pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
  639. vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
  640. KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
  641. oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
  642. 08LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
  643. HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
  644. BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
  645. Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
  646. bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
  647. AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
  648. i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
  649. HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
  650. kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
  651. VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
  652. RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
  653. -----END CERTIFICATE-----"""
  654. large_key_pem = b"""-----BEGIN RSA PRIVATE KEY-----
  655. MIIJYgIBAAKCAg4AtRua8eIeevRfsj+fkcHr1vmse7Kgb+oX1ssJAvCb1R7JQMnH
  656. hNDjDP6b3vEkZuPUzlDHymP+cNkXvvi4wJ4miVbO3+SeU4Sh+jmsHeHzGIXat9xW
  657. 9PFtuPM5FQq8zvkY8aDeRYmYwN9JKu4/neMBCBqostYlTEWg+bSytO/qWnyHTHKh
  658. g0GfaDdqUQPsGQw+J0MgaYIjQOCVASHAPlzbDQLCtuOb587rwTLkZA2GwoHB/LyJ
  659. BwT0HHgBaiObE12Vs6wi2en0Uu11CiwEuK1KIBcZ2XbE6eApaZa6VH9ysEmUxPt7
  660. TqyZ4E2oMIYaLPNRxuvozdwTlj1svI1k1FrkaXGc5MTjbgigPMKjIb0T7b/4GNzt
  661. DhP1LvAeUMnrEi3hJJrcJPXHPqS8/RiytR9xQQW6Sdh4LaA3f9MQm3WSevWage3G
  662. P8YcCLssOVKsArDjuA52NF5LmYuAeUzXprm4ITDi2oO+0iFBpFW6VPEK4A9vO0Yk
  663. M/6Wt6tG8zyWhaSH1zFUTwfQ9Yvjyt5w1lrUaAJuoTpwbMVZaDJaEhjOaXU0dyPQ
  664. jOsePDOQcU6dkeTWsQ3LsHPEEug/X6819TLG5mb3V7bvV9nPFBfTJSCEG794kr90
  665. XgZfIN71FrdByxLerlbuJI21pPs/nZi9SXi9jAWeiS45/azUxMsyYgJArui+gjq7
  666. sV1pWiBm6/orAgMBAAECggINQp5L6Yu+oIXBqcSjgq8tfF9M5hd30pLuf/EheHZf
  667. LA7uAqn2fVGFI2OInIJhXIOT5OxsAXO0xXfltzawZxIFpOFMqajj4F7aYjvSpw9V
  668. J4EdSiJ/zgv8y1qUdbwEZbHVThRZjoSlrtSzilonBoHZAE0mHtqMz7iRFSk1zz6t
  669. GunRrvo/lROPentf3TsvHquVNUYI5yaapyO1S7xJhecMIIYSb8nbsHI54FBDGNas
  670. 6mFmpPwI/47/6HTwOEWupnn3NicsjrHzUInOUpaMig4cRR+aP5bjqg/ty8xI8AoN
  671. evEmCytiWTc+Rvbp1ieN+1jpjN18PjUk80/W7qioHUDt4ieLic8uxWH2VD9SCEnX
  672. Mpi9tA/FqoZ+2A/3m1OfrY6jiZVE2g+asi9lCK7QVWL39eK82H4rPvtp0/dyo1/i
  673. ZZz68TXg+m8IgEZcp88hngbkuoTTzpGE73QuPKhGA1uMIimDdqPPB5WP76q+03Oi
  674. IRR5DfZnqPERed49by0enJ7tKa/gFPZizOV8ALKr0Dp+vfAkxGDLPLBLd2A3//tw
  675. xg0Q/wltihHSBujv4nYlDXdc5oYyMYZ+Lhc/VuOghHfBq3tgEQ1ECM/ofqXEIdy7
  676. nVcpZn3Eeq8Jl5CrqxE1ee3NxlzsJHn99yGQpr7mOhW/psJF3XNz80Meg3L4m1T8
  677. sMBK0GbaassuJhdzb5whAoIBBw48sx1b1WR4XxQc5O/HjHva+l16i2pjUnOUTcDF
  678. RWmSbIhBm2QQ2rVhO8+fak0tkl6ZnMWW4i0U/X5LOEBbC7+IS8bO3j3Revi+Vw5x
  679. j96LMlIe9XEub5i/saEWgiz7maCvfzLFU08e1OpT4qPDpP293V400ubA6R7WQTCv
  680. pBkskGwHeu0l/TuKkVqBFFUTu7KEbps8Gjg7MkJaFriAOv1zis/umK8pVS3ZAM6e
  681. 8w5jfpRccn8Xzta2fRwTB5kCmfxdDsY0oYGxPLRAbW72bORoLGuyyPp/ojeGwoik
  682. JX9RttErc6FjyZtks370Pa8UL5QskyhMbDhrZW2jFD+RXYM1BrvmZRjbAoIBBwy4
  683. iFJpuDfytJfz1MWtaL5DqEL/kmiZYAXl6hifNhGu5GAipVIIGsDqEYW4i+VC15aa
  684. 7kOCwz/I5zsB3vSDW96IRs4wXtqEZSibc2W/bqfVi+xcvPPl1ZhQ2EAwa4D/x035
  685. kyf20ffWOU+1yf2cnijzqs3IzlveUm+meLw5s3Rc+iG7DPWWeCoe1hVwANI1euNc
  686. pqKwKY905yFyjOje2OgiEU2kS4YME4zGeBys8yo7E42hNnN2EPK6xkkUqzdudLLQ
  687. 8OUlKRTc8AbIf3XG1rpA4VUpTv3hhxGGwCRy6If8zgZQsNYchgNztRGk72Gcb8Dm
  688. vFSEN3ZtwxU64G3YZzntdcr2WPzxAoIBBw30g6Fgdb/gmVnOpL0//T0ePNDKIMPs
  689. jVJLaRduhoZgB1Bb9qPUPX0SzRzLZtg1tkZSDjBDoHmOHJfhxUaXt+FLCPPbrE4t
  690. +nq9n/nBaMM779w9ClqhqLOyGrwKoxjSmhi+TVEHyIxCbXMvPHVHfX9WzxjbcGrN
  691. ZvRaEVZWo+QlIX8yqdSwqxLk1WtAIRzvlcj7NKum8xBxPed6BNFep/PtgIAmoLT5
  692. L8wb7EWb2iUdc2KbZ4OaY51lDScqpATgXu3WjXfM+Q52G0mX6Wyd0cjlL711Zrjb
  693. yLbiueZT94lgIHHRRKtKc8CEqcjkQV5OzABS3P/gQSfgZXBdLKjOpTnKDUq7IBeH
  694. AoIBBweAOEIAPLQg1QRUrr3xRrYKRwlakgZDii9wJt1l5AgBTICzbTA1vzDJ1JM5
  695. AqSpCV6w9JWyYVcXK+HLdKBRZLaPPNEQDJ5lOxD6uMziWGl2rg8tj+1xNMWfxiPz
  696. aTCjoe4EoBUMoTq2gwzRcM2usEQNikXVhnj9Wzaivsaeb4bJ3GRPW5DkrO6JSEtT
  697. w+gvyMqQM2Hy5k7E7BT46sXVwaj/jZxuqGnebRixXtnp0WixdRIqYWUr1UqLf6hQ
  698. G7WP2BgoxCMaCmNW8+HMD/xuxucEotoIhZ+GgJKBFoNnjl3BX+qxYdSe9RbL/5Tr
  699. 4It6Jxtj8uETJXEbv9Cg6v1agWPS9YY8RLTBAoIBBwrU2AsAUts6h1LgGLKK3UWZ
  700. oLH5E+4o+7HqSGRcRodVeN9NBXIYdHHOLeEG6YNGJiJ3bFP5ZQEu9iDsyoFVKJ9O
  701. Mw/y6dKZuxOCZ+X8FopSROg3yWfdOpAm6cnQZp3WqLNX4n/Q6WvKojfyEiPphjwT
  702. 0ymrUJELXLWJmjUyPoAk6HgC0Gs28ZnEXbyhx7CSbZNFyCU/PNUDZwto3GisIPD3
  703. le7YjqHugezmjMGlA0sDw5aCXjfbl74vowRFYMO6e3ItApfSRgNV86CDoX74WI/5
  704. AYU/QVM4wGt8XGT2KwDFJaxYGKsGDMWmXY04dS+WPuetCbouWUusyFwRb9SzFave
  705. vYeU7Ab/
  706. -----END RSA PRIVATE KEY-----"""
  707. ec_private_key_pem = b"""-----BEGIN PRIVATE KEY-----
  708. MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgYirTZSx+5O8Y6tlG
  709. cka6W6btJiocdrdolfcukSoTEk+hRANCAAQkvPNu7Pa1GcsWU4v7ptNfqCJVq8Cx
  710. zo0MUVPQgwJ3aJtNM1QMOQUayCrRwfklg+D/rFSUwEUqtZh7fJDiFqz3
  711. -----END PRIVATE KEY-----
  712. """
  713. ec_root_key_pem = b"""-----BEGIN EC PRIVATE KEY-----
  714. MIGlAgEBBDEAz/HOBFPYLB0jLWeTpJn4Yc4m/C4mdWymVHBjOmnwiPHKT326iYN/
  715. ZhmSs+RM94RsoAcGBSuBBAAioWQDYgAEwE5vDdla/nLpWAPAQ0yFGqwLuw4BcN2r
  716. U+sKab5EAEHzLeceRa8ffncYdCXNoVsBcdob1y66CFZMEWLetPTmGapyWkBAs6/L
  717. 8kUlkU9OsE+7IVo4QQJkgV5gM+Dim1XE
  718. -----END EC PRIVATE KEY-----
  719. """
  720. ec_root_cert_pem = b"""-----BEGIN CERTIFICATE-----
  721. MIICLTCCAbKgAwIBAgIMWW/hwTl6ufz6/WkCMAoGCCqGSM49BAMDMFgxGDAWBgNV
  722. BAMTD1Rlc3RpbmcgUm9vdCBDQTEQMA4GA1UEChMHVGVzdGluZzEQMA4GA1UEBxMH
  723. Q2hpY2FnbzELMAkGA1UECBMCSUwxCzAJBgNVBAYTAlVTMCAXDTE3MDcxOTIyNDgz
  724. M1oYDzk5OTkxMjMxMjM1OTU5WjBYMRgwFgYDVQQDEw9UZXN0aW5nIFJvb3QgQ0Ex
  725. EDAOBgNVBAoTB1Rlc3RpbmcxEDAOBgNVBAcTB0NoaWNhZ28xCzAJBgNVBAgTAklM
  726. MQswCQYDVQQGEwJVUzB2MBAGByqGSM49AgEGBSuBBAAiA2IABMBObw3ZWv5y6VgD
  727. wENMhRqsC7sOAXDdq1PrCmm+RABB8y3nHkWvH353GHQlzaFbAXHaG9cuughWTBFi
  728. 3rT05hmqclpAQLOvy/JFJZFPTrBPuyFaOEECZIFeYDPg4ptVxKNDMEEwDwYDVR0T
  729. AQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwQAMB0GA1UdDgQWBBSoTrF0H2m8RDzB
  730. MnY2KReEPfz7ZjAKBggqhkjOPQQDAwNpADBmAjEA3+G1oVCxGjYX4iUN93QYcNHe
  731. e3fJQJwX9+KsHRut6qNZDUbvRbtO1YIAwB4UJZjwAjEAtXCPURS5A4McZHnSwgTi
  732. Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
  733. -----END CERTIFICATE-----"""
  734. rsa_p_not_prime_pem = """
  735. -----BEGIN RSA PRIVATE KEY-----
  736. MBsCAQACAS0CAQcCAQACAQ8CAQMCAQACAQACAQA=
  737. -----END RSA PRIVATE KEY-----
  738. """
  739. @pytest.fixture
  740. def x509_data():
  741. """
  742. Create a new private key and start a certificate request (for a test
  743. to finish in one way or another).
  744. """
  745. # Basic setup stuff to generate a certificate
  746. pkey = PKey()
  747. pkey.generate_key(TYPE_RSA, 512)
  748. req = X509Req()
  749. req.set_pubkey(pkey)
  750. # Authority good you have.
  751. req.get_subject().commonName = "Yoda root CA"
  752. x509 = X509()
  753. subject = x509.get_subject()
  754. subject.commonName = req.get_subject().commonName
  755. x509.set_issuer(subject)
  756. x509.set_pubkey(pkey)
  757. now = datetime.now()
  758. expire = datetime.now() + timedelta(days=100)
  759. x509.set_notBefore(now.strftime("%Y%m%d%H%M%SZ").encode())
  760. x509.set_notAfter(expire.strftime("%Y%m%d%H%M%SZ").encode())
  761. yield pkey, x509
  762. class TestX509Ext(object):
  763. """
  764. Tests for `OpenSSL.crypto.X509Extension`.
  765. """
  766. def test_str(self):
  767. """
  768. The string representation of `X509Extension` instances as
  769. returned by `str` includes stuff.
  770. """
  771. # This isn't necessarily the best string representation. Perhaps it
  772. # will be changed/improved in the future.
  773. assert (
  774. str(X509Extension(b"basicConstraints", True, b"CA:false"))
  775. == "CA:FALSE"
  776. )
  777. def test_type(self):
  778. """
  779. `X509Extension` can be used to create instances of that type.
  780. """
  781. assert is_consistent_type(
  782. X509Extension,
  783. "X509Extension",
  784. b"basicConstraints",
  785. True,
  786. b"CA:true",
  787. )
  788. def test_construction(self):
  789. """
  790. `X509Extension` accepts an extension type name, a critical flag,
  791. and an extension value and returns an `X509Extension` instance.
  792. """
  793. basic = X509Extension(b"basicConstraints", True, b"CA:true")
  794. assert isinstance(basic, X509Extension)
  795. comment = X509Extension(b"nsComment", False, b"pyOpenSSL unit test")
  796. assert isinstance(comment, X509Extension)
  797. @pytest.mark.parametrize(
  798. "type_name, critical, value",
  799. [
  800. (b"thisIsMadeUp", False, b"hi"),
  801. (b"basicConstraints", False, b"blah blah"),
  802. # Exercise a weird one (an extension which uses the r2i method).
  803. # This exercises the codepath that requires a non-NULL ctx to be
  804. # passed to X509V3_EXT_nconf. It can't work now because we provide
  805. # no configuration database. It might be made to work in the
  806. # future.
  807. (
  808. b"proxyCertInfo",
  809. True,
  810. b"language:id-ppl-anyLanguage,pathlen:1,policy:text:AB",
  811. ),
  812. ],
  813. )
  814. def test_invalid_extension(self, type_name, critical, value):
  815. """
  816. `X509Extension` raises something if it is passed a bad
  817. extension name or value.
  818. """
  819. with pytest.raises(Error):
  820. X509Extension(type_name, critical, value)
  821. @pytest.mark.parametrize("critical_flag", [True, False])
  822. def test_get_critical(self, critical_flag):
  823. """
  824. `X509ExtensionType.get_critical` returns the value of the
  825. extension's critical flag.
  826. """
  827. ext = X509Extension(b"basicConstraints", critical_flag, b"CA:true")
  828. assert ext.get_critical() == critical_flag
  829. @pytest.mark.parametrize(
  830. "short_name, value",
  831. [(b"basicConstraints", b"CA:true"), (b"nsComment", b"foo bar")],
  832. )
  833. def test_get_short_name(self, short_name, value):
  834. """
  835. `X509ExtensionType.get_short_name` returns a string giving the
  836. short type name of the extension.
  837. """
  838. ext = X509Extension(short_name, True, value)
  839. assert ext.get_short_name() == short_name
  840. def test_get_data(self):
  841. """
  842. `X509Extension.get_data` returns a string giving the data of
  843. the extension.
  844. """
  845. ext = X509Extension(b"basicConstraints", True, b"CA:true")
  846. # Expect to get back the DER encoded form of CA:true.
  847. assert ext.get_data() == b"0\x03\x01\x01\xff"
  848. def test_unused_subject(self, x509_data):
  849. """
  850. The `subject` parameter to `X509Extension` may be provided for an
  851. extension which does not use it and is ignored in this case.
  852. """
  853. pkey, x509 = x509_data
  854. ext1 = X509Extension(
  855. b"basicConstraints", False, b"CA:TRUE", subject=x509
  856. )
  857. x509.add_extensions([ext1])
  858. x509.sign(pkey, "sha1")
  859. # This is a little lame. Can we think of a better way?
  860. text = dump_certificate(FILETYPE_TEXT, x509)
  861. assert b"X509v3 Basic Constraints:" in text
  862. assert b"CA:TRUE" in text
  863. def test_subject(self, x509_data):
  864. """
  865. If an extension requires a subject, the `subject` parameter to
  866. `X509Extension` provides its value.
  867. """
  868. pkey, x509 = x509_data
  869. ext3 = X509Extension(
  870. b"subjectKeyIdentifier", False, b"hash", subject=x509
  871. )
  872. x509.add_extensions([ext3])
  873. x509.sign(pkey, "sha1")
  874. text = dump_certificate(FILETYPE_TEXT, x509)
  875. assert b"X509v3 Subject Key Identifier:" in text
  876. def test_missing_subject(self):
  877. """
  878. If an extension requires a subject and the `subject` parameter
  879. is given no value, something happens.
  880. """
  881. with pytest.raises(Error):
  882. X509Extension(b"subjectKeyIdentifier", False, b"hash")
  883. @pytest.mark.parametrize("bad_obj", [True, object(), "hello", []])
  884. def test_invalid_subject(self, bad_obj):
  885. """
  886. If the `subject` parameter is given a value which is not an
  887. `X509` instance, `TypeError` is raised.
  888. """
  889. with pytest.raises(TypeError):
  890. X509Extension(
  891. "basicConstraints", False, "CA:TRUE", subject=bad_obj
  892. )
  893. def test_unused_issuer(self, x509_data):
  894. """
  895. The `issuer` parameter to `X509Extension` may be provided for an
  896. extension which does not use it and is ignored in this case.
  897. """
  898. pkey, x509 = x509_data
  899. ext1 = X509Extension(
  900. b"basicConstraints", False, b"CA:TRUE", issuer=x509
  901. )
  902. x509.add_extensions([ext1])
  903. x509.sign(pkey, "sha1")
  904. text = dump_certificate(FILETYPE_TEXT, x509)
  905. assert b"X509v3 Basic Constraints:" in text
  906. assert b"CA:TRUE" in text
  907. def test_issuer(self, x509_data):
  908. """
  909. If an extension requires an issuer, the `issuer` parameter to
  910. `X509Extension` provides its value.
  911. """
  912. pkey, x509 = x509_data
  913. ext2 = X509Extension(
  914. b"authorityKeyIdentifier", False, b"issuer:always", issuer=x509
  915. )
  916. x509.add_extensions([ext2])
  917. x509.sign(pkey, "sha1")
  918. text = dump_certificate(FILETYPE_TEXT, x509)
  919. assert b"X509v3 Authority Key Identifier:" in text
  920. assert b"DirName:/CN=Yoda root CA" in text
  921. def test_missing_issuer(self):
  922. """
  923. If an extension requires an issue and the `issuer` parameter is
  924. given no value, something happens.
  925. """
  926. with pytest.raises(Error):
  927. X509Extension(
  928. b"authorityKeyIdentifier", False, b"keyid:always,issuer:always"
  929. )
  930. @pytest.mark.parametrize("bad_obj", [True, object(), "hello", []])
  931. def test_invalid_issuer(self, bad_obj):
  932. """
  933. If the `issuer` parameter is given a value which is not an
  934. `X509` instance, `TypeError` is raised.
  935. """
  936. with pytest.raises(TypeError):
  937. X509Extension(
  938. "basicConstraints",
  939. False,
  940. "keyid:always,issuer:always",
  941. issuer=bad_obj,
  942. )
  943. class TestPKey(object):
  944. """
  945. Tests for `OpenSSL.crypto.PKey`.
  946. """
  947. def test_convert_from_cryptography_private_key(self):
  948. """
  949. PKey.from_cryptography_key creates a proper private PKey.
  950. """
  951. key = serialization.load_pem_private_key(
  952. intermediate_key_pem, None, backend
  953. )
  954. pkey = PKey.from_cryptography_key(key)
  955. assert isinstance(pkey, PKey)
  956. assert pkey.bits() == key.key_size
  957. assert pkey._only_public is False
  958. assert pkey._initialized is True
  959. def test_convert_from_cryptography_public_key(self):
  960. """
  961. PKey.from_cryptography_key creates a proper public PKey.
  962. """
  963. key = serialization.load_pem_public_key(cleartextPublicKeyPEM, backend)
  964. pkey = PKey.from_cryptography_key(key)
  965. assert isinstance(pkey, PKey)
  966. assert pkey.bits() == key.key_size
  967. assert pkey._only_public is True
  968. assert pkey._initialized is True
  969. def test_convert_from_cryptography_unsupported_type(self):
  970. """
  971. PKey.from_cryptography_key raises TypeError with an unsupported type.
  972. """
  973. key = serialization.load_pem_private_key(
  974. ec_private_key_pem, None, backend
  975. )
  976. with pytest.raises(TypeError):
  977. PKey.from_cryptography_key(key)
  978. def test_convert_public_pkey_to_cryptography_key(self):
  979. """
  980. PKey.to_cryptography_key creates a proper cryptography public key.
  981. """
  982. pkey = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
  983. key = pkey.to_cryptography_key()
  984. assert isinstance(key, rsa.RSAPublicKey)
  985. assert pkey.bits() == key.key_size
  986. def test_convert_private_pkey_to_cryptography_key(self):
  987. """
  988. PKey.to_cryptography_key creates a proper cryptography private key.
  989. """
  990. pkey = load_privatekey(FILETYPE_PEM, root_key_pem)
  991. key = pkey.to_cryptography_key()
  992. assert isinstance(key, rsa.RSAPrivateKey)
  993. assert pkey.bits() == key.key_size
  994. def test_type(self):
  995. """
  996. `PKey` can be used to create instances of that type.
  997. """
  998. assert is_consistent_type(PKey, "PKey")
  999. def test_construction(self):
  1000. """
  1001. `PKey` takes no arguments and returns a new `PKey` instance.
  1002. """
  1003. key = PKey()
  1004. assert isinstance(key, PKey)
  1005. def test_pregeneration(self):
  1006. """
  1007. `PKey.bits` and `PKey.type` return `0` before the key is generated.
  1008. `PKey.check` raises `TypeError` before the key is generated.
  1009. """
  1010. key = PKey()
  1011. assert key.type() == 0
  1012. assert key.bits() == 0
  1013. with pytest.raises(TypeError):
  1014. key.check()
  1015. def test_failed_generation(self):
  1016. """
  1017. `PKey.generate_key` takes two arguments, the first giving the key type
  1018. as one of `TYPE_RSA` or `TYPE_DSA` and the second giving the number of
  1019. bits to generate. If an invalid type is specified or generation fails,
  1020. `Error` is raised. If an invalid number of bits is specified,
  1021. `ValueError` or `Error` is raised.
  1022. """
  1023. key = PKey()
  1024. with pytest.raises(TypeError):
  1025. key.generate_key("foo", "bar")
  1026. with pytest.raises(Error):
  1027. key.generate_key(-1, 0)
  1028. with pytest.raises(ValueError):
  1029. key.generate_key(TYPE_RSA, -1)
  1030. with pytest.raises(ValueError):
  1031. key.generate_key(TYPE_RSA, 0)
  1032. with pytest.raises(TypeError):
  1033. key.generate_key(TYPE_RSA, object())
  1034. # XXX RSA generation for small values of bits is fairly buggy in a wide
  1035. # range of OpenSSL versions. I need to figure out what the safe lower
  1036. # bound for a reasonable number of OpenSSL versions is and explicitly
  1037. # check for that in the wrapper. The failure behavior is typically an
  1038. # infinite loop inside OpenSSL.
  1039. # with pytest.raises(Error):
  1040. # key.generate_key(TYPE_RSA, 2)
  1041. # XXX DSA generation seems happy with any number of bits. The DSS
  1042. # says bits must be between 512 and 1024 inclusive. OpenSSL's DSA
  1043. # generator doesn't seem to care about the upper limit at all. For
  1044. # the lower limit, it uses 512 if anything smaller is specified.
  1045. # So, it doesn't seem possible to make generate_key fail for
  1046. # TYPE_DSA with a bits argument which is at least an int.
  1047. # with pytest.raises(Error):
  1048. # key.generate_key(TYPE_DSA, -7)
  1049. def test_rsa_generation(self):
  1050. """
  1051. `PKey.generate_key` generates an RSA key when passed `TYPE_RSA` as a
  1052. type and a reasonable number of bits.
  1053. """
  1054. bits = 512
  1055. key = PKey()
  1056. key.generate_key(TYPE_RSA, bits)
  1057. assert key.type() == TYPE_RSA
  1058. assert key.bits() == bits
  1059. assert key.check()
  1060. def test_dsa_generation(self):
  1061. """
  1062. `PKey.generate_key` generates a DSA key when passed `TYPE_DSA` as a
  1063. type and a reasonable number of bits.
  1064. """
  1065. # 512 is a magic number. The DSS (Digital Signature Standard)
  1066. # allows a minimum of 512 bits for DSA. DSA_generate_parameters
  1067. # will silently promote any value below 512 to 512.
  1068. bits = 512
  1069. key = PKey()
  1070. key.generate_key(TYPE_DSA, bits)
  1071. assert key.type() == TYPE_DSA
  1072. assert key.bits() == bits
  1073. with pytest.raises(TypeError):
  1074. key.check()
  1075. def test_regeneration(self):
  1076. """
  1077. `PKey.generate_key` can be called multiple times on the same key to
  1078. generate new keys.
  1079. """
  1080. key = PKey()
  1081. for type, bits in [(TYPE_RSA, 512), (TYPE_DSA, 576)]:
  1082. key.generate_key(type, bits)
  1083. assert key.type() == type
  1084. assert key.bits() == bits
  1085. def test_inconsistent_key(self):
  1086. """
  1087. `PKey.check` returns `Error` if the key is not consistent.
  1088. """
  1089. key = load_privatekey(FILETYPE_PEM, inconsistentPrivateKeyPEM)
  1090. with pytest.raises(Error):
  1091. key.check()
  1092. def test_check_public_key(self):
  1093. """
  1094. `PKey.check` raises `TypeError` if only the public part of the key
  1095. is available.
  1096. """
  1097. # A trick to get a public-only key
  1098. key = PKey()
  1099. key.generate_key(TYPE_RSA, 512)
  1100. cert = X509()
  1101. cert.set_pubkey(key)
  1102. pub = cert.get_pubkey()
  1103. with pytest.raises(TypeError):
  1104. pub.check()
  1105. def test_check_pr_897(self):
  1106. """
  1107. `PKey.check` raises `OpenSSL.crypto.Error` if provided with broken key
  1108. """
  1109. pkey = load_privatekey(FILETYPE_PEM, rsa_p_not_prime_pem)
  1110. with pytest.raises(Error):
  1111. pkey.check()
  1112. def x509_name(**attrs):
  1113. """
  1114. Return a new X509Name with the given attributes.
  1115. """
  1116. # XXX There's no other way to get a new X509Name yet.
  1117. name = X509().get_subject()
  1118. attrs = list(attrs.items())
  1119. # Make the order stable - order matters!
  1120. def key(attr):
  1121. return attr[1]
  1122. attrs.sort(key=key)
  1123. for k, v in attrs:
  1124. setattr(name, k, v)
  1125. return name
  1126. class TestX509Name(object):
  1127. """
  1128. Unit tests for `OpenSSL.crypto.X509Name`.
  1129. """
  1130. def test_type(self):
  1131. """
  1132. The type of X509Name objects is `X509Name`.
  1133. """
  1134. name = x509_name()
  1135. assert isinstance(name, X509Name)
  1136. def test_only_string_attributes(self):
  1137. """
  1138. Attempting to set a non-`str` attribute name on an `X509Name` instance
  1139. causes `TypeError` to be raised.
  1140. """
  1141. name = x509_name()
  1142. # Beyond these cases, you may also think that unicode should be
  1143. # rejected. Sorry, you're wrong. unicode is automatically converted
  1144. # to str outside of the control of X509Name, so there's no way to
  1145. # reject it.
  1146. # Also, this used to test str subclasses, but that test is less
  1147. # relevant now that the implementation is in Python instead of C. Also
  1148. # PyPy automatically converts str subclasses to str when they are
  1149. # passed to setattr, so we can't test it on PyPy. Apparently CPython
  1150. # does this sometimes as well.
  1151. with pytest.raises(TypeError):
  1152. setattr(name, None, "hello")
  1153. with pytest.raises(TypeError):
  1154. setattr(name, 30, "hello")
  1155. def test_set_invalid_attribute(self):
  1156. """
  1157. Attempting to set any attribute name on an `X509Name` instance for
  1158. which no corresponding NID is defined causes `AttributeError` to be
  1159. raised.
  1160. """
  1161. name = x509_name()
  1162. with pytest.raises(AttributeError):
  1163. setattr(name, "no such thing", None)
  1164. def test_attributes(self):
  1165. """
  1166. `X509Name` instances have attributes for each standard (?)
  1167. X509Name field.
  1168. """
  1169. name = x509_name()
  1170. name.commonName = "foo"
  1171. assert name.commonName == "foo"
  1172. assert name.CN == "foo"
  1173. name.CN = "baz"
  1174. assert name.commonName == "baz"
  1175. assert name.CN == "baz"
  1176. name.commonName = "bar"
  1177. assert name.commonName == "bar"
  1178. assert name.CN == "bar"
  1179. name.CN = "quux"
  1180. assert name.commonName == "quux"
  1181. assert name.CN == "quux"
  1182. assert name.OU is None
  1183. with pytest.raises(AttributeError):
  1184. name.foobar
  1185. def test_copy(self):
  1186. """
  1187. `X509Name` creates a new `X509Name` instance with all the same
  1188. attributes as an existing `X509Name` instance when called with one.
  1189. """
  1190. name = x509_name(commonName="foo", emailAddress="bar@example.com")
  1191. copy = X509Name(name)
  1192. assert copy.commonName == "foo"
  1193. assert copy.emailAddress == "bar@example.com"
  1194. # Mutate the copy and ensure the original is unmodified.
  1195. copy.commonName = "baz"
  1196. assert name.commonName == "foo"
  1197. # Mutate the original and ensure the copy is unmodified.
  1198. name.emailAddress = "quux@example.com"
  1199. assert copy.emailAddress == "bar@example.com"
  1200. def test_repr(self):
  1201. """
  1202. `repr` passed an `X509Name` instance should return a string containing
  1203. a description of the type and the NIDs which have been set on it.
  1204. """
  1205. name = x509_name(commonName="foo", emailAddress="bar")
  1206. assert repr(name) == "<X509Name object '/emailAddress=bar/CN=foo'>"
  1207. def test_comparison(self):
  1208. """
  1209. `X509Name` instances should compare based on their NIDs.
  1210. """
  1211. def _equality(a, b, assert_true, assert_false):
  1212. assert_true(a == b)
  1213. assert_false(a != b)
  1214. assert_true(b == a)
  1215. assert_false(b != a)
  1216. def assert_true(x):
  1217. assert x
  1218. def assert_false(x):
  1219. assert not x
  1220. def assert_equal(a, b):
  1221. _equality(a, b, assert_true, assert_false)
  1222. # Instances compare equal to themselves.
  1223. name = x509_name()
  1224. assert_equal(name, name)
  1225. # Empty instances should compare equal to each other.
  1226. assert_equal(x509_name(), x509_name())
  1227. # Instances with equal NIDs should compare equal to each other.
  1228. assert_equal(x509_name(commonName="foo"), x509_name(commonName="foo"))
  1229. # Instance with equal NIDs set using different aliases should compare
  1230. # equal to each other.
  1231. assert_equal(x509_name(commonName="foo"), x509_name(CN="foo"))
  1232. # Instances with more than one NID with the same values should compare
  1233. # equal to each other.
  1234. assert_equal(
  1235. x509_name(CN="foo", organizationalUnitName="bar"),
  1236. x509_name(commonName="foo", OU="bar"),
  1237. )
  1238. def assert_not_equal(a, b):
  1239. _equality(a, b, assert_false, assert_true)
  1240. # Instances with different values for the same NID should not compare
  1241. # equal to each other.
  1242. assert_not_equal(x509_name(CN="foo"), x509_name(CN="bar"))
  1243. # Instances with different NIDs should not compare equal to each other.
  1244. assert_not_equal(x509_name(CN="foo"), x509_name(OU="foo"))
  1245. assert_not_equal(x509_name(), object())
  1246. def _inequality(a, b, assert_true, assert_false):
  1247. assert_true(a < b)
  1248. assert_true(a <= b)
  1249. assert_true(b > a)
  1250. assert_true(b >= a)
  1251. assert_false(a > b)
  1252. assert_false(a >= b)
  1253. assert_false(b < a)
  1254. assert_false(b <= a)
  1255. def assert_less_than(a, b):
  1256. _inequality(a, b, assert_true, assert_false)
  1257. # An X509Name with a NID with a value which sorts less than the value
  1258. # of the same NID on another X509Name compares less than the other
  1259. # X509Name.
  1260. assert_less_than(x509_name(CN="abc"), x509_name(CN="def"))
  1261. def assert_greater_than(a, b):
  1262. _inequality(a, b, assert_false, assert_true)
  1263. # An X509Name with a NID with a value which sorts greater than the
  1264. # value of the same NID on another X509Name compares greater than the
  1265. # other X509Name.
  1266. assert_greater_than(x509_name(CN="def"), x509_name(CN="abc"))
  1267. def test_hash(self):
  1268. """
  1269. `X509Name.hash` returns an integer hash based on the value of the name.
  1270. """
  1271. a = x509_name(CN="foo")
  1272. b = x509_name(CN="foo")
  1273. assert a.hash() == b.hash()
  1274. a.CN = "bar"
  1275. assert a.hash() != b.hash()
  1276. def test_der(self):
  1277. """
  1278. `X509Name.der` returns the DER encoded form of the name.
  1279. """
  1280. a = x509_name(CN="foo", C="US")
  1281. assert (
  1282. a.der() == b"0\x1b1\x0b0\t\x06\x03U\x04\x06\x13\x02US"
  1283. b"1\x0c0\n\x06\x03U\x04\x03\x0c\x03foo"
  1284. )
  1285. def test_get_components(self):
  1286. """
  1287. `X509Name.get_components` returns a `list` of two-tuples of `str`
  1288. giving the NIDs and associated values which make up the name.
  1289. """
  1290. a = x509_name()
  1291. assert a.get_components() == []
  1292. a.CN = "foo"
  1293. assert a.get_components() == [(b"CN", b"foo")]
  1294. a.organizationalUnitName = "bar"
  1295. assert a.get_components() == [(b"CN", b"foo"), (b"OU", b"bar")]
  1296. def test_load_nul_byte_attribute(self):
  1297. """
  1298. An `X509Name` from an `X509` instance loaded from a file can have a
  1299. NUL byte in the value of one of its attributes.
  1300. """
  1301. cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
  1302. subject = cert.get_subject()
  1303. assert "null.python.org\x00example.org" == subject.commonName
  1304. def test_load_nul_byte_components(self):
  1305. """
  1306. An `X509Name` from an `X509` instance loaded from a file can have a
  1307. NUL byte in the value of its components
  1308. """
  1309. cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
  1310. subject = cert.get_subject()
  1311. components = subject.get_components()
  1312. ccn = [value for name, value in components if name == b"CN"]
  1313. assert ccn[0] == b"null.python.org\x00example.org"
  1314. def test_set_attribute_failure(self):
  1315. """
  1316. If the value of an attribute cannot be set for some reason then
  1317. `Error` is raised.
  1318. """
  1319. name = x509_name()
  1320. # This value is too long
  1321. with pytest.raises(Error):
  1322. setattr(name, "O", b"x" * 512)
  1323. class _PKeyInteractionTestsMixin:
  1324. """
  1325. Tests which involve another thing and a PKey.
  1326. """
  1327. def signable(self):
  1328. """
  1329. Return something with `set_pubkey` and `sign` methods.
  1330. """
  1331. raise NotImplementedError()
  1332. def test_sign_with_ungenerated(self):
  1333. """
  1334. `X509Req.sign` raises `ValueError` when passed a `PKey` with no parts.
  1335. """
  1336. request = self.signable()
  1337. key = PKey()
  1338. with pytest.raises(ValueError):
  1339. request.sign(key, GOOD_DIGEST)
  1340. def test_sign_with_public_key(self):
  1341. """
  1342. `X509Req.sign` raises `ValueError` when passed a `PKey` with no private
  1343. part as the signing key.
  1344. """
  1345. request = self.signable()
  1346. key = PKey()
  1347. key.generate_key(TYPE_RSA, 512)
  1348. request.set_pubkey(key)
  1349. pub = request.get_pubkey()
  1350. with pytest.raises(ValueError):
  1351. request.sign(pub, GOOD_DIGEST)
  1352. def test_sign_with_unknown_digest(self):
  1353. """
  1354. `X509Req.sign` raises `ValueError` when passed a digest name which is
  1355. not known.
  1356. """
  1357. request = self.signable()
  1358. key = PKey()
  1359. key.generate_key(TYPE_RSA, 512)
  1360. with pytest.raises(ValueError):
  1361. request.sign(key, BAD_DIGEST)
  1362. def test_sign(self):
  1363. """
  1364. `X509Req.sign` succeeds when passed a private key object and a
  1365. valid digest function. `X509Req.verify` can be used to check
  1366. the signature.
  1367. """
  1368. request = self.signable()
  1369. key = PKey()
  1370. key.generate_key(TYPE_RSA, 512)
  1371. request.set_pubkey(key)
  1372. request.sign(key, GOOD_DIGEST)
  1373. # If the type has a verify method, cover that too.
  1374. if getattr(request, "verify", None) is not None:
  1375. pub = request.get_pubkey()
  1376. assert request.verify(pub)
  1377. # Make another key that won't verify.
  1378. key = PKey()
  1379. key.generate_key(TYPE_RSA, 512)
  1380. with pytest.raises(Error):
  1381. request.verify(key)
  1382. class TestX509Req(_PKeyInteractionTestsMixin):
  1383. """
  1384. Tests for `OpenSSL.crypto.X509Req`.
  1385. """
  1386. def signable(self):
  1387. """
  1388. Create and return a new `X509Req`.
  1389. """
  1390. return X509Req()
  1391. def test_type(self):
  1392. """
  1393. `X509Req` can be used to create instances of that type.
  1394. """
  1395. assert is_consistent_type(X509Req, "X509Req")
  1396. def test_construction(self):
  1397. """
  1398. `X509Req` takes no arguments and returns an `X509Req` instance.
  1399. """
  1400. request = X509Req()
  1401. assert isinstance(request, X509Req)
  1402. def test_version(self):
  1403. """
  1404. `X509Req.set_version` sets the X.509 version of the certificate
  1405. request. `X509Req.get_version` returns the X.509 version of the
  1406. certificate request. The initial value of the version is 0.
  1407. """
  1408. request = X509Req()
  1409. assert request.get_version() == 0
  1410. request.set_version(1)
  1411. assert request.get_version() == 1
  1412. request.set_version(3)
  1413. assert request.get_version() == 3
  1414. def test_version_wrong_args(self):
  1415. """
  1416. `X509Req.set_version` raises `TypeError` if called with a non-`int`
  1417. argument.
  1418. """
  1419. request = X509Req()
  1420. with pytest.raises(TypeError):
  1421. request.set_version("foo")
  1422. def test_get_subject(self):
  1423. """
  1424. `X509Req.get_subject` returns an `X509Name` for the subject of the
  1425. request and which is valid even after the request object is
  1426. otherwise dead.
  1427. """
  1428. request = X509Req()
  1429. subject = request.get_subject()
  1430. assert isinstance(subject, X509Name)
  1431. subject.commonName = "foo"
  1432. assert request.get_subject().commonName == "foo"
  1433. del request
  1434. subject.commonName = "bar"
  1435. assert subject.commonName == "bar"
  1436. def test_add_extensions(self):
  1437. """
  1438. `X509Req.add_extensions` accepts a `list` of `X509Extension` instances
  1439. and adds them to the X509 request.
  1440. """
  1441. request = X509Req()
  1442. request.add_extensions(
  1443. [X509Extension(b"basicConstraints", True, b"CA:false")]
  1444. )
  1445. exts = request.get_extensions()
  1446. assert len(exts) == 1
  1447. assert exts[0].get_short_name() == b"basicConstraints"
  1448. assert exts[0].get_critical() == 1
  1449. assert exts[0].get_data() == b"0\x00"
  1450. def test_get_extensions(self):
  1451. """
  1452. `X509Req.get_extensions` returns a `list` of extensions added to this
  1453. X509 request.
  1454. """
  1455. request = X509Req()
  1456. exts = request.get_extensions()
  1457. assert exts == []
  1458. request.add_extensions(
  1459. [
  1460. X509Extension(b"basicConstraints", True, b"CA:true"),
  1461. X509Extension(b"keyUsage", False, b"digitalSignature"),
  1462. ]
  1463. )
  1464. exts = request.get_extensions()
  1465. assert len(exts) == 2
  1466. assert exts[0].get_short_name() == b"basicConstraints"
  1467. assert exts[0].get_critical() == 1
  1468. assert exts[0].get_data() == b"0\x03\x01\x01\xff"
  1469. assert exts[1].get_short_name() == b"keyUsage"
  1470. assert exts[1].get_critical() == 0
  1471. assert exts[1].get_data() == b"\x03\x02\x07\x80"
  1472. # Requesting it a second time should return the same list
  1473. exts = request.get_extensions()
  1474. assert len(exts) == 2
  1475. def test_add_extensions_wrong_args(self):
  1476. """
  1477. `X509Req.add_extensions` raises `TypeError` if called with a
  1478. non-`list`. Or it raises `ValueError` if called with a `list`
  1479. containing objects other than `X509Extension` instances.
  1480. """
  1481. request = X509Req()
  1482. with pytest.raises(TypeError):
  1483. request.add_extensions(object())
  1484. with pytest.raises(ValueError):
  1485. request.add_extensions([object()])
  1486. def test_verify_wrong_args(self):
  1487. """
  1488. `X509Req.verify` raises `TypeError` if passed anything other than a
  1489. `PKey` instance as its single argument.
  1490. """
  1491. request = X509Req()
  1492. with pytest.raises(TypeError):
  1493. request.verify(object())
  1494. def test_verify_uninitialized_key(self):
  1495. """
  1496. `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
  1497. `OpenSSL.crypto.PKey` which contains no key data.
  1498. """
  1499. request = X509Req()
  1500. pkey = PKey()
  1501. with pytest.raises(Error):
  1502. request.verify(pkey)
  1503. def test_verify_wrong_key(self):
  1504. """
  1505. `X509Req.verify` raises `OpenSSL.crypto.Error` if called with a
  1506. `OpenSSL.crypto.PKey` which does not represent the public part of the
  1507. key which signed the request.
  1508. """
  1509. request = X509Req()
  1510. pkey = load_privatekey(FILETYPE_PEM, root_key_pem)
  1511. request.set_pubkey(pkey)
  1512. request.sign(pkey, GOOD_DIGEST)
  1513. another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
  1514. with pytest.raises(Error):
  1515. request.verify(another_pkey)
  1516. def test_verify_success(self):
  1517. """
  1518. `X509Req.verify` returns `True` if called with a `OpenSSL.crypto.PKey`
  1519. which represents the public part of the key which signed the request.
  1520. """
  1521. request = X509Req()
  1522. pkey = load_privatekey(FILETYPE_PEM, root_key_pem)
  1523. request.set_pubkey(pkey)
  1524. request.sign(pkey, GOOD_DIGEST)
  1525. assert request.verify(pkey)
  1526. def test_convert_from_cryptography(self):
  1527. crypto_req = x509.load_pem_x509_csr(
  1528. cleartextCertificateRequestPEM, backend
  1529. )
  1530. req = X509Req.from_cryptography(crypto_req)
  1531. assert isinstance(req, X509Req)
  1532. def test_convert_from_cryptography_unsupported_type(self):
  1533. with pytest.raises(TypeError):
  1534. X509Req.from_cryptography(object())
  1535. def test_convert_to_cryptography_key(self):
  1536. req = load_certificate_request(
  1537. FILETYPE_PEM, cleartextCertificateRequestPEM
  1538. )
  1539. crypto_req = req.to_cryptography()
  1540. assert isinstance(crypto_req, x509.CertificateSigningRequest)
  1541. class TestX509(_PKeyInteractionTestsMixin):
  1542. """
  1543. Tests for `OpenSSL.crypto.X509`.
  1544. """
  1545. pemData = root_cert_pem + root_key_pem
  1546. def signable(self):
  1547. """
  1548. Create and return a new `X509`.
  1549. """
  1550. certificate = X509()
  1551. # Fill in placeholder validity values. signable only expects to call
  1552. # set_pubkey and sign.
  1553. certificate.gmtime_adj_notBefore(-24 * 60 * 60)
  1554. certificate.gmtime_adj_notAfter(24 * 60 * 60)
  1555. return certificate
  1556. def test_type(self):
  1557. """
  1558. `X509` can be used to create instances of that type.
  1559. """
  1560. assert is_consistent_type(X509, "X509")
  1561. def test_construction(self):
  1562. """
  1563. `X509` takes no arguments and returns an instance of `X509`.
  1564. """
  1565. certificate = X509()
  1566. assert isinstance(certificate, X509)
  1567. assert type(certificate).__name__ == "X509"
  1568. assert type(certificate) == X509
  1569. def test_set_version_wrong_args(self):
  1570. """
  1571. `X509.set_version` raises `TypeError` if invoked with an argument
  1572. not of type `int`.
  1573. """
  1574. cert = X509()
  1575. with pytest.raises(TypeError):
  1576. cert.set_version(None)
  1577. def test_version(self):
  1578. """
  1579. `X509.set_version` sets the certificate version number.
  1580. `X509.get_version` retrieves it.
  1581. """
  1582. cert = X509()
  1583. cert.set_version(1234)
  1584. assert cert.get_version() == 1234
  1585. def test_serial_number(self):
  1586. """
  1587. The serial number of an `X509` can be retrieved and
  1588. modified with `X509.get_serial_number` and
  1589. `X509.set_serial_number`.
  1590. """
  1591. certificate = X509()
  1592. with pytest.raises(TypeError):
  1593. certificate.set_serial_number("1")
  1594. assert certificate.get_serial_number() == 0
  1595. certificate.set_serial_number(1)
  1596. assert certificate.get_serial_number() == 1
  1597. certificate.set_serial_number(2 ** 32 + 1)
  1598. assert certificate.get_serial_number() == 2 ** 32 + 1
  1599. certificate.set_serial_number(2 ** 64 + 1)
  1600. assert certificate.get_serial_number() == 2 ** 64 + 1
  1601. certificate.set_serial_number(2 ** 128 + 1)
  1602. assert certificate.get_serial_number() == 2 ** 128 + 1
  1603. def _setBoundTest(self, which):
  1604. """
  1605. `X509.set_notBefore` takes a string in the format of an
  1606. ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
  1607. validity period to it.
  1608. """
  1609. certificate = X509()
  1610. set = getattr(certificate, "set_not" + which)
  1611. get = getattr(certificate, "get_not" + which)
  1612. # Starts with no value.
  1613. assert get() is None
  1614. # GMT (Or is it UTC?) -exarkun
  1615. when = b"20040203040506Z"
  1616. set(when)
  1617. assert get() == when
  1618. # A plus two hours and thirty minutes offset
  1619. when = b"20040203040506+0530"
  1620. set(when)
  1621. assert get() == when
  1622. # A minus one hour fifteen minutes offset
  1623. when = b"20040203040506-0115"
  1624. set(when)
  1625. assert get() == when
  1626. # An invalid string results in a ValueError
  1627. with pytest.raises(ValueError):
  1628. set(b"foo bar")
  1629. # The wrong number of arguments results in a TypeError.
  1630. with pytest.raises(TypeError):
  1631. set()
  1632. with pytest.raises(TypeError):
  1633. set(b"20040203040506Z", b"20040203040506Z")
  1634. with pytest.raises(TypeError):
  1635. get(b"foo bar")
  1636. # XXX ASN1_TIME (not GENERALIZEDTIME)
  1637. def test_set_notBefore(self):
  1638. """
  1639. `X509.set_notBefore` takes a string in the format of an
  1640. ASN1 GENERALIZEDTIME and sets the beginning of the certificate's
  1641. validity period to it.
  1642. """
  1643. self._setBoundTest("Before")
  1644. def test_set_notAfter(self):
  1645. """
  1646. `X509.set_notAfter` takes a string in the format of an ASN1
  1647. GENERALIZEDTIME and sets the end of the certificate's validity period
  1648. to it.
  1649. """
  1650. self._setBoundTest("After")
  1651. def test_get_notBefore(self):
  1652. """
  1653. `X509.get_notBefore` returns a string in the format of an
  1654. ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
  1655. internally.
  1656. """
  1657. cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
  1658. assert cert.get_notBefore() == b"20090325123658Z"
  1659. def test_get_notAfter(self):
  1660. """
  1661. `X509.get_notAfter` returns a string in the format of an
  1662. ASN1 GENERALIZEDTIME even for certificates which store it as UTCTIME
  1663. internally.
  1664. """
  1665. cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
  1666. assert cert.get_notAfter() == b"20170611123658Z"
  1667. def test_gmtime_adj_notBefore_wrong_args(self):
  1668. """
  1669. `X509.gmtime_adj_notBefore` raises `TypeError` if called with a
  1670. non-`int` argument.
  1671. """
  1672. cert = X509()
  1673. with pytest.raises(TypeError):
  1674. cert.gmtime_adj_notBefore(None)
  1675. @flaky.flaky
  1676. def test_gmtime_adj_notBefore(self):
  1677. """
  1678. `X509.gmtime_adj_notBefore` changes the not-before timestamp to be the
  1679. current time plus the number of seconds passed in.
  1680. """
  1681. cert = load_certificate(FILETYPE_PEM, self.pemData)
  1682. not_before_min = datetime.utcnow().replace(microsecond=0) + timedelta(
  1683. seconds=100
  1684. )
  1685. cert.gmtime_adj_notBefore(100)
  1686. not_before = datetime.strptime(
  1687. cert.get_notBefore().decode(), "%Y%m%d%H%M%SZ"
  1688. )
  1689. not_before_max = datetime.utcnow() + timedelta(seconds=100)
  1690. assert not_before_min <= not_before <= not_before_max
  1691. def test_gmtime_adj_notAfter_wrong_args(self):
  1692. """
  1693. `X509.gmtime_adj_notAfter` raises `TypeError` if called with a
  1694. non-`int` argument.
  1695. """
  1696. cert = X509()
  1697. with pytest.raises(TypeError):
  1698. cert.gmtime_adj_notAfter(None)
  1699. @flaky.flaky
  1700. def test_gmtime_adj_notAfter(self):
  1701. """
  1702. `X509.gmtime_adj_notAfter` changes the not-after timestamp
  1703. to be the current time plus the number of seconds passed in.
  1704. """
  1705. cert = load_certificate(FILETYPE_PEM, self.pemData)
  1706. not_after_min = datetime.utcnow().replace(microsecond=0) + timedelta(
  1707. seconds=100
  1708. )
  1709. cert.gmtime_adj_notAfter(100)
  1710. not_after = datetime.strptime(
  1711. cert.get_notAfter().decode(), "%Y%m%d%H%M%SZ"
  1712. )
  1713. not_after_max = datetime.utcnow() + timedelta(seconds=100)
  1714. assert not_after_min <= not_after <= not_after_max
  1715. def test_has_expired(self):
  1716. """
  1717. `X509.has_expired` returns `True` if the certificate's not-after time
  1718. is in the past.
  1719. """
  1720. cert = X509()
  1721. cert.gmtime_adj_notAfter(-1)
  1722. assert cert.has_expired()
  1723. def test_has_not_expired(self):
  1724. """
  1725. `X509.has_expired` returns `False` if the certificate's not-after time
  1726. is in the future.
  1727. """
  1728. cert = X509()
  1729. cert.gmtime_adj_notAfter(2)
  1730. assert not cert.has_expired()
  1731. def test_root_has_not_expired(self):
  1732. """
  1733. `X509.has_expired` returns `False` if the certificate's not-after time
  1734. is in the future.
  1735. """
  1736. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  1737. assert not cert.has_expired()
  1738. def test_digest(self):
  1739. """
  1740. `X509.digest` returns a string giving ":"-separated hex-encoded
  1741. words of the digest of the certificate.
  1742. """
  1743. cert = load_certificate(FILETYPE_PEM, old_root_cert_pem)
  1744. assert (
  1745. # This is MD5 instead of GOOD_DIGEST because the digest algorithm
  1746. # actually matters to the assertion (ie, another arbitrary, good
  1747. # digest will not product the same digest).
  1748. # Digest verified with the command:
  1749. # openssl x509 -in root_cert.pem -noout -fingerprint -md5
  1750. cert.digest("MD5")
  1751. == b"19:B3:05:26:2B:F8:F2:FF:0B:8F:21:07:A8:28:B8:75"
  1752. )
  1753. def _extcert(self, pkey, extensions):
  1754. cert = X509()
  1755. # Certificates with extensions must be X.509v3, which is encoded with a
  1756. # version of two.
  1757. cert.set_version(2)
  1758. cert.set_pubkey(pkey)
  1759. cert.get_subject().commonName = "Unit Tests"
  1760. cert.get_issuer().commonName = "Unit Tests"
  1761. when = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
  1762. cert.set_notBefore(when)
  1763. cert.set_notAfter(when)
  1764. cert.add_extensions(extensions)
  1765. cert.sign(pkey, "sha1")
  1766. return load_certificate(
  1767. FILETYPE_PEM, dump_certificate(FILETYPE_PEM, cert)
  1768. )
  1769. def test_extension_count(self):
  1770. """
  1771. `X509.get_extension_count` returns the number of extensions
  1772. that are present in the certificate.
  1773. """
  1774. pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
  1775. ca = X509Extension(b"basicConstraints", True, b"CA:FALSE")
  1776. key = X509Extension(b"keyUsage", True, b"digitalSignature")
  1777. subjectAltName = X509Extension(
  1778. b"subjectAltName", True, b"DNS:example.com"
  1779. )
  1780. # Try a certificate with no extensions at all.
  1781. c = self._extcert(pkey, [])
  1782. assert c.get_extension_count() == 0
  1783. # And a certificate with one
  1784. c = self._extcert(pkey, [ca])
  1785. assert c.get_extension_count() == 1
  1786. # And a certificate with several
  1787. c = self._extcert(pkey, [ca, key, subjectAltName])
  1788. assert c.get_extension_count() == 3
  1789. def test_get_extension(self):
  1790. """
  1791. `X509.get_extension` takes an integer and returns an
  1792. `X509Extension` corresponding to the extension at that index.
  1793. """
  1794. pkey = load_privatekey(FILETYPE_PEM, client_key_pem)
  1795. ca = X509Extension(b"basicConstraints", True, b"CA:FALSE")
  1796. key = X509Extension(b"keyUsage", True, b"digitalSignature")
  1797. subjectAltName = X509Extension(
  1798. b"subjectAltName", False, b"DNS:example.com"
  1799. )
  1800. cert = self._extcert(pkey, [ca, key, subjectAltName])
  1801. ext = cert.get_extension(0)
  1802. assert isinstance(ext, X509Extension)
  1803. assert ext.get_critical()
  1804. assert ext.get_short_name() == b"basicConstraints"
  1805. ext = cert.get_extension(1)
  1806. assert isinstance(ext, X509Extension)
  1807. assert ext.get_critical()
  1808. assert ext.get_short_name() == b"keyUsage"
  1809. ext = cert.get_extension(2)
  1810. assert isinstance(ext, X509Extension)
  1811. assert not ext.get_critical()
  1812. assert ext.get_short_name() == b"subjectAltName"
  1813. with pytest.raises(IndexError):
  1814. cert.get_extension(-1)
  1815. with pytest.raises(IndexError):
  1816. cert.get_extension(4)
  1817. with pytest.raises(TypeError):
  1818. cert.get_extension("hello")
  1819. def test_nullbyte_subjectAltName(self):
  1820. """
  1821. The fields of a `subjectAltName` extension on an X509 may contain NUL
  1822. bytes and this value is reflected in the string representation of the
  1823. extension object.
  1824. """
  1825. cert = load_certificate(FILETYPE_PEM, nulbyteSubjectAltNamePEM)
  1826. ext = cert.get_extension(3)
  1827. assert ext.get_short_name() == b"subjectAltName"
  1828. assert (
  1829. b"DNS:altnull.python.org\x00example.com, "
  1830. b"email:null@python.org\x00user@example.org, "
  1831. b"URI:http://null.python.org\x00http://example.org, "
  1832. b"IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1\n"
  1833. == str(ext).encode("ascii")
  1834. )
  1835. def test_invalid_digest_algorithm(self):
  1836. """
  1837. `X509.digest` raises `ValueError` if called with an unrecognized hash
  1838. algorithm.
  1839. """
  1840. cert = X509()
  1841. with pytest.raises(ValueError):
  1842. cert.digest(BAD_DIGEST)
  1843. def test_get_subject(self):
  1844. """
  1845. `X509.get_subject` returns an `X509Name` instance.
  1846. """
  1847. cert = load_certificate(FILETYPE_PEM, self.pemData)
  1848. subj = cert.get_subject()
  1849. assert isinstance(subj, X509Name)
  1850. assert subj.get_components() == [
  1851. (b"C", b"US"),
  1852. (b"ST", b"IL"),
  1853. (b"L", b"Chicago"),
  1854. (b"O", b"Testing"),
  1855. (b"CN", b"Testing Root CA"),
  1856. ]
  1857. def test_set_subject_wrong_args(self):
  1858. """
  1859. `X509.set_subject` raises a `TypeError` if called with an argument not
  1860. of type `X509Name`.
  1861. """
  1862. cert = X509()
  1863. with pytest.raises(TypeError):
  1864. cert.set_subject(None)
  1865. def test_set_subject(self):
  1866. """
  1867. `X509.set_subject` changes the subject of the certificate to the one
  1868. passed in.
  1869. """
  1870. cert = X509()
  1871. name = cert.get_subject()
  1872. name.C = "AU"
  1873. name.OU = "Unit Tests"
  1874. cert.set_subject(name)
  1875. assert cert.get_subject().get_components() == [
  1876. (b"C", b"AU"),
  1877. (b"OU", b"Unit Tests"),
  1878. ]
  1879. def test_get_issuer(self):
  1880. """
  1881. `X509.get_issuer` returns an `X509Name` instance.
  1882. """
  1883. cert = load_certificate(FILETYPE_PEM, self.pemData)
  1884. subj = cert.get_issuer()
  1885. assert isinstance(subj, X509Name)
  1886. comp = subj.get_components()
  1887. assert comp == [
  1888. (b"C", b"US"),
  1889. (b"ST", b"IL"),
  1890. (b"L", b"Chicago"),
  1891. (b"O", b"Testing"),
  1892. (b"CN", b"Testing Root CA"),
  1893. ]
  1894. def test_set_issuer_wrong_args(self):
  1895. """
  1896. `X509.set_issuer` raises a `TypeError` if called with an argument not
  1897. of type `X509Name`.
  1898. """
  1899. cert = X509()
  1900. with pytest.raises(TypeError):
  1901. cert.set_issuer(None)
  1902. def test_set_issuer(self):
  1903. """
  1904. `X509.set_issuer` changes the issuer of the certificate to the
  1905. one passed in.
  1906. """
  1907. cert = X509()
  1908. name = cert.get_issuer()
  1909. name.C = "AU"
  1910. name.OU = "Unit Tests"
  1911. cert.set_issuer(name)
  1912. assert cert.get_issuer().get_components() == [
  1913. (b"C", b"AU"),
  1914. (b"OU", b"Unit Tests"),
  1915. ]
  1916. def test_get_pubkey_uninitialized(self):
  1917. """
  1918. When called on a certificate with no public key, `X509.get_pubkey`
  1919. raises `OpenSSL.crypto.Error`.
  1920. """
  1921. cert = X509()
  1922. with pytest.raises(Error):
  1923. cert.get_pubkey()
  1924. def test_set_pubkey_wrong_type(self):
  1925. """
  1926. `X509.set_pubkey` raises `TypeError` when given an object of the
  1927. wrong type.
  1928. """
  1929. cert = X509()
  1930. with pytest.raises(TypeError):
  1931. cert.set_pubkey(object())
  1932. def test_subject_name_hash(self):
  1933. """
  1934. `X509.subject_name_hash` returns the hash of the certificate's
  1935. subject name.
  1936. """
  1937. cert = load_certificate(FILETYPE_PEM, self.pemData)
  1938. # SHA1
  1939. assert cert.subject_name_hash() == 3278919224
  1940. def test_get_signature_algorithm(self):
  1941. """
  1942. `X509.get_signature_algorithm` returns a string which means
  1943. the algorithm used to sign the certificate.
  1944. """
  1945. cert = load_certificate(FILETYPE_PEM, self.pemData)
  1946. assert b"sha256WithRSAEncryption" == cert.get_signature_algorithm()
  1947. def test_get_undefined_signature_algorithm(self):
  1948. """
  1949. `X509.get_signature_algorithm` raises `ValueError` if the signature
  1950. algorithm is undefined or unknown.
  1951. """
  1952. # This certificate has been modified to indicate a bogus OID in the
  1953. # signature algorithm field so that OpenSSL does not recognize it.
  1954. certPEM = b"""\
  1955. -----BEGIN CERTIFICATE-----
  1956. MIIC/zCCAmigAwIBAgIBATAGBgJ8BQUAMHsxCzAJBgNVBAYTAlNHMREwDwYDVQQK
  1957. EwhNMkNyeXB0bzEUMBIGA1UECxMLTTJDcnlwdG8gQ0ExJDAiBgNVBAMTG00yQ3J5
  1958. cHRvIENlcnRpZmljYXRlIE1hc3RlcjEdMBsGCSqGSIb3DQEJARYObmdwc0Bwb3N0
  1959. MS5jb20wHhcNMDAwOTEwMDk1MTMwWhcNMDIwOTEwMDk1MTMwWjBTMQswCQYDVQQG
  1960. EwJTRzERMA8GA1UEChMITTJDcnlwdG8xEjAQBgNVBAMTCWxvY2FsaG9zdDEdMBsG
  1961. CSqGSIb3DQEJARYObmdwc0Bwb3N0MS5jb20wXDANBgkqhkiG9w0BAQEFAANLADBI
  1962. AkEArL57d26W9fNXvOhNlZzlPOACmvwOZ5AdNgLzJ1/MfsQQJ7hHVeHmTAjM664V
  1963. +fXvwUGJLziCeBo1ysWLRnl8CQIDAQABo4IBBDCCAQAwCQYDVR0TBAIwADAsBglg
  1964. hkgBhvhCAQ0EHxYdT3BlblNTTCBHZW5lcmF0ZWQgQ2VydGlmaWNhdGUwHQYDVR0O
  1965. BBYEFM+EgpK+eyZiwFU1aOPSbczbPSpVMIGlBgNVHSMEgZ0wgZqAFPuHI2nrnDqT
  1966. FeXFvylRT/7tKDgBoX+kfTB7MQswCQYDVQQGEwJTRzERMA8GA1UEChMITTJDcnlw
  1967. dG8xFDASBgNVBAsTC00yQ3J5cHRvIENBMSQwIgYDVQQDExtNMkNyeXB0byBDZXJ0
  1968. aWZpY2F0ZSBNYXN0ZXIxHTAbBgkqhkiG9w0BCQEWDm5ncHNAcG9zdDEuY29tggEA
  1969. MA0GCSqGSIb3DQEBBAUAA4GBADv8KpPo+gfJxN2ERK1Y1l17sz/ZhzoGgm5XCdbx
  1970. jEY7xKfpQngV599k1xhl11IMqizDwu0855agrckg2MCTmOI9DZzDD77tAYb+Dk0O
  1971. PEVk0Mk/V0aIsDE9bolfCi/i/QWZ3N8s5nTWMNyBBBmoSliWCm4jkkRZRD0ejgTN
  1972. tgI5
  1973. -----END CERTIFICATE-----
  1974. """
  1975. cert = load_certificate(FILETYPE_PEM, certPEM)
  1976. with pytest.raises(ValueError):
  1977. cert.get_signature_algorithm()
  1978. def test_sign_bad_pubkey_type(self):
  1979. """
  1980. `X509.sign` raises `TypeError` when called with the wrong type.
  1981. """
  1982. cert = X509()
  1983. with pytest.raises(TypeError):
  1984. cert.sign(object(), b"sha256")
  1985. def test_convert_from_cryptography(self):
  1986. crypto_cert = x509.load_pem_x509_certificate(
  1987. intermediate_cert_pem, backend
  1988. )
  1989. cert = X509.from_cryptography(crypto_cert)
  1990. assert isinstance(cert, X509)
  1991. assert cert.get_version() == crypto_cert.version.value
  1992. def test_convert_from_cryptography_unsupported_type(self):
  1993. with pytest.raises(TypeError):
  1994. X509.from_cryptography(object())
  1995. def test_convert_to_cryptography_key(self):
  1996. cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
  1997. crypto_cert = cert.to_cryptography()
  1998. assert isinstance(crypto_cert, x509.Certificate)
  1999. assert crypto_cert.version.value == cert.get_version()
  2000. class TestX509Store(object):
  2001. """
  2002. Test for `OpenSSL.crypto.X509Store`.
  2003. """
  2004. def test_type(self):
  2005. """
  2006. `X509Store` is a type object.
  2007. """
  2008. assert is_consistent_type(X509Store, "X509Store")
  2009. def test_add_cert(self):
  2010. """
  2011. `X509Store.add_cert` adds a `X509` instance to the certificate store.
  2012. """
  2013. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  2014. store = X509Store()
  2015. store.add_cert(cert)
  2016. @pytest.mark.parametrize("cert", [None, 1.0, "cert", object()])
  2017. def test_add_cert_wrong_args(self, cert):
  2018. """
  2019. `X509Store.add_cert` raises `TypeError` if passed a non-X509 object
  2020. as its first argument.
  2021. """
  2022. store = X509Store()
  2023. with pytest.raises(TypeError):
  2024. store.add_cert(cert)
  2025. def test_add_cert_accepts_duplicate(self):
  2026. """
  2027. `X509Store.add_cert` doesn't raise `OpenSSL.crypto.Error` if an attempt
  2028. is made to add the same certificate to the store more than once.
  2029. """
  2030. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  2031. store = X509Store()
  2032. store.add_cert(cert)
  2033. store.add_cert(cert)
  2034. @pytest.mark.parametrize(
  2035. "cafile, capath, call_cafile, call_capath",
  2036. [
  2037. (
  2038. "/cafile" + NON_ASCII,
  2039. None,
  2040. b"/cafile" + NON_ASCII.encode(sys.getfilesystemencoding()),
  2041. _ffi.NULL,
  2042. ),
  2043. (
  2044. b"/cafile" + NON_ASCII.encode("utf-8"),
  2045. None,
  2046. b"/cafile" + NON_ASCII.encode("utf-8"),
  2047. _ffi.NULL,
  2048. ),
  2049. (
  2050. None,
  2051. "/capath" + NON_ASCII,
  2052. _ffi.NULL,
  2053. b"/capath" + NON_ASCII.encode(sys.getfilesystemencoding()),
  2054. ),
  2055. (
  2056. None,
  2057. b"/capath" + NON_ASCII.encode("utf-8"),
  2058. _ffi.NULL,
  2059. b"/capath" + NON_ASCII.encode("utf-8"),
  2060. ),
  2061. ],
  2062. )
  2063. def test_load_locations_parameters(
  2064. self, cafile, capath, call_cafile, call_capath, monkeypatch
  2065. ):
  2066. class LibMock(object):
  2067. def load_locations(self, store, cafile, capath):
  2068. self.cafile = cafile
  2069. self.capath = capath
  2070. return 1
  2071. lib_mock = LibMock()
  2072. monkeypatch.setattr(
  2073. _lib, "X509_STORE_load_locations", lib_mock.load_locations
  2074. )
  2075. store = X509Store()
  2076. store.load_locations(cafile=cafile, capath=capath)
  2077. assert call_cafile == lib_mock.cafile
  2078. assert call_capath == lib_mock.capath
  2079. def test_load_locations_fails_when_all_args_are_none(self):
  2080. store = X509Store()
  2081. with pytest.raises(Error):
  2082. store.load_locations(None, None)
  2083. def test_load_locations_raises_error_on_failure(self, tmpdir):
  2084. invalid_ca_file = tmpdir.join("invalid.pem")
  2085. invalid_ca_file.write("This is not a certificate")
  2086. store = X509Store()
  2087. with pytest.raises(Error):
  2088. store.load_locations(cafile=str(invalid_ca_file))
  2089. class TestPKCS12(object):
  2090. """
  2091. Test for `OpenSSL.crypto.PKCS12` and `OpenSSL.crypto.load_pkcs12`.
  2092. """
  2093. def test_type(self):
  2094. """
  2095. `PKCS12` is a type object.
  2096. """
  2097. assert is_consistent_type(PKCS12, "PKCS12")
  2098. def test_empty_construction(self):
  2099. """
  2100. `PKCS12` returns a new instance of `PKCS12` with no certificate,
  2101. private key, CA certificates, or friendly name.
  2102. """
  2103. p12 = PKCS12()
  2104. assert None is p12.get_certificate()
  2105. assert None is p12.get_privatekey()
  2106. assert None is p12.get_ca_certificates()
  2107. assert None is p12.get_friendlyname()
  2108. def test_type_errors(self):
  2109. """
  2110. The `PKCS12` setter functions (`set_certificate`, `set_privatekey`,
  2111. `set_ca_certificates`, and `set_friendlyname`) raise `TypeError`
  2112. when passed objects of types other than those expected.
  2113. """
  2114. p12 = PKCS12()
  2115. for bad_arg in [3, PKey(), X509]:
  2116. with pytest.raises(TypeError):
  2117. p12.set_certificate(bad_arg)
  2118. for bad_arg in [3, "legbone", X509()]:
  2119. with pytest.raises(TypeError):
  2120. p12.set_privatekey(bad_arg)
  2121. for bad_arg in [3, X509(), (3, 4), (PKey(),)]:
  2122. with pytest.raises(TypeError):
  2123. p12.set_ca_certificates(bad_arg)
  2124. for bad_arg in [6, ("foo", "bar")]:
  2125. with pytest.raises(TypeError):
  2126. p12.set_friendlyname(bad_arg)
  2127. def test_key_only(self):
  2128. """
  2129. A `PKCS12` with only a private key can be exported using
  2130. `PKCS12.export` and loaded again using `load_pkcs12`.
  2131. """
  2132. passwd = b"blah"
  2133. p12 = PKCS12()
  2134. pkey = load_privatekey(FILETYPE_PEM, root_key_pem)
  2135. p12.set_privatekey(pkey)
  2136. assert None is p12.get_certificate()
  2137. assert pkey == p12.get_privatekey()
  2138. try:
  2139. dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
  2140. except Error:
  2141. # Some versions of OpenSSL will throw an exception
  2142. # for this nearly useless PKCS12 we tried to generate:
  2143. # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
  2144. return
  2145. p12 = load_pkcs12(dumped_p12, passwd)
  2146. assert None is p12.get_ca_certificates()
  2147. assert None is p12.get_certificate()
  2148. # OpenSSL fails to bring the key back to us. So sad. Perhaps in the
  2149. # future this will be improved.
  2150. assert isinstance(p12.get_privatekey(), (PKey, type(None)))
  2151. def test_cert_only(self):
  2152. """
  2153. A `PKCS12` with only a certificate can be exported using
  2154. `PKCS12.export` and loaded again using `load_pkcs12`.
  2155. """
  2156. passwd = b"blah"
  2157. p12 = PKCS12()
  2158. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  2159. p12.set_certificate(cert)
  2160. assert cert == p12.get_certificate()
  2161. assert None is p12.get_privatekey()
  2162. try:
  2163. dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
  2164. except Error:
  2165. # Some versions of OpenSSL will throw an exception
  2166. # for this nearly useless PKCS12 we tried to generate:
  2167. # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')]
  2168. return
  2169. p12 = load_pkcs12(dumped_p12, passwd)
  2170. assert None is p12.get_privatekey()
  2171. # OpenSSL fails to bring the cert back to us. Groany mcgroan.
  2172. assert isinstance(p12.get_certificate(), (X509, type(None)))
  2173. # Oh ho. It puts the certificate into the ca certificates list, in
  2174. # fact. Totally bogus, I would think. Nevertheless, let's exploit
  2175. # that to check to see if it reconstructed the certificate we expected
  2176. # it to. At some point, hopefully this will change so that
  2177. # p12.get_certificate() is actually what returns the loaded
  2178. # certificate.
  2179. assert root_cert_pem == dump_certificate(
  2180. FILETYPE_PEM, p12.get_ca_certificates()[0]
  2181. )
  2182. def gen_pkcs12(
  2183. self, cert_pem=None, key_pem=None, ca_pem=None, friendly_name=None
  2184. ):
  2185. """
  2186. Generate a PKCS12 object with components from PEM. Verify that the set
  2187. functions return None.
  2188. """
  2189. p12 = PKCS12()
  2190. if cert_pem:
  2191. ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem))
  2192. assert ret is None
  2193. if key_pem:
  2194. ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem))
  2195. assert ret is None
  2196. if ca_pem:
  2197. ret = p12.set_ca_certificates(
  2198. (load_certificate(FILETYPE_PEM, ca_pem),)
  2199. )
  2200. assert ret is None
  2201. if friendly_name:
  2202. ret = p12.set_friendlyname(friendly_name)
  2203. assert ret is None
  2204. return p12
  2205. def check_recovery(
  2206. self, p12_str, key=None, cert=None, ca=None, passwd=b"", extra=()
  2207. ):
  2208. """
  2209. Use openssl program to confirm three components are recoverable from a
  2210. PKCS12 string.
  2211. """
  2212. if key:
  2213. recovered_key = _runopenssl(
  2214. p12_str,
  2215. b"pkcs12",
  2216. b"-nocerts",
  2217. b"-nodes",
  2218. b"-passin",
  2219. b"pass:" + passwd,
  2220. *extra
  2221. )
  2222. assert recovered_key[-len(key) :] == key
  2223. if cert:
  2224. recovered_cert = _runopenssl(
  2225. p12_str,
  2226. b"pkcs12",
  2227. b"-clcerts",
  2228. b"-nodes",
  2229. b"-passin",
  2230. b"pass:" + passwd,
  2231. b"-nokeys",
  2232. *extra
  2233. )
  2234. assert recovered_cert[-len(cert) :] == cert
  2235. if ca:
  2236. recovered_cert = _runopenssl(
  2237. p12_str,
  2238. b"pkcs12",
  2239. b"-cacerts",
  2240. b"-nodes",
  2241. b"-passin",
  2242. b"pass:" + passwd,
  2243. b"-nokeys",
  2244. *extra
  2245. )
  2246. assert recovered_cert[-len(ca) :] == ca
  2247. def verify_pkcs12_container(self, p12):
  2248. """
  2249. Verify that the PKCS#12 container contains the correct client
  2250. certificate and private key.
  2251. :param p12: The PKCS12 instance to verify.
  2252. :type p12: `PKCS12`
  2253. """
  2254. cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate())
  2255. key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey())
  2256. assert (client_cert_pem, client_key_pem, None) == (
  2257. cert_pem,
  2258. key_pem,
  2259. p12.get_ca_certificates(),
  2260. )
  2261. def test_load_pkcs12(self):
  2262. """
  2263. A PKCS12 string generated using the openssl command line can be loaded
  2264. with `load_pkcs12` and its components extracted and examined.
  2265. """
  2266. passwd = b"whatever"
  2267. pem = client_key_pem + client_cert_pem
  2268. p12_str = _runopenssl(
  2269. pem,
  2270. b"pkcs12",
  2271. b"-export",
  2272. b"-clcerts",
  2273. b"-passout",
  2274. b"pass:" + passwd,
  2275. )
  2276. p12 = load_pkcs12(p12_str, passphrase=passwd)
  2277. self.verify_pkcs12_container(p12)
  2278. def test_load_pkcs12_text_passphrase(self):
  2279. """
  2280. A PKCS12 string generated using the openssl command line can be loaded
  2281. with `load_pkcs12` and its components extracted and examined.
  2282. Using text as passphrase instead of bytes. DeprecationWarning expected.
  2283. """
  2284. pem = client_key_pem + client_cert_pem
  2285. passwd = b"whatever"
  2286. p12_str = _runopenssl(
  2287. pem,
  2288. b"pkcs12",
  2289. b"-export",
  2290. b"-clcerts",
  2291. b"-passout",
  2292. b"pass:" + passwd,
  2293. )
  2294. with pytest.warns(DeprecationWarning) as w:
  2295. simplefilter("always")
  2296. p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii"))
  2297. msg = "{0} for passphrase is no longer accepted, use bytes".format(
  2298. WARNING_TYPE_EXPECTED
  2299. )
  2300. assert msg == str(w[-1].message)
  2301. self.verify_pkcs12_container(p12)
  2302. def test_load_pkcs12_no_passphrase(self):
  2303. """
  2304. A PKCS12 string generated using openssl command line can be loaded with
  2305. `load_pkcs12` without a passphrase and its components extracted
  2306. and examined.
  2307. """
  2308. pem = client_key_pem + client_cert_pem
  2309. p12_str = _runopenssl(
  2310. pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:"
  2311. )
  2312. p12 = load_pkcs12(p12_str)
  2313. self.verify_pkcs12_container(p12)
  2314. def _dump_and_load(self, dump_passphrase, load_passphrase):
  2315. """
  2316. A helper method to dump and load a PKCS12 object.
  2317. """
  2318. p12 = self.gen_pkcs12(client_cert_pem, client_key_pem)
  2319. dumped_p12 = p12.export(passphrase=dump_passphrase, iter=2, maciter=3)
  2320. return load_pkcs12(dumped_p12, passphrase=load_passphrase)
  2321. def test_load_pkcs12_null_passphrase_load_empty(self):
  2322. """
  2323. A PKCS12 string can be dumped with a null passphrase, loaded with an
  2324. empty passphrase with `load_pkcs12`, and its components
  2325. extracted and examined.
  2326. """
  2327. self.verify_pkcs12_container(
  2328. self._dump_and_load(dump_passphrase=None, load_passphrase=b"")
  2329. )
  2330. def test_load_pkcs12_null_passphrase_load_null(self):
  2331. """
  2332. A PKCS12 string can be dumped with a null passphrase, loaded with a
  2333. null passphrase with `load_pkcs12`, and its components
  2334. extracted and examined.
  2335. """
  2336. self.verify_pkcs12_container(
  2337. self._dump_and_load(dump_passphrase=None, load_passphrase=None)
  2338. )
  2339. def test_load_pkcs12_empty_passphrase_load_empty(self):
  2340. """
  2341. A PKCS12 string can be dumped with an empty passphrase, loaded with an
  2342. empty passphrase with `load_pkcs12`, and its components
  2343. extracted and examined.
  2344. """
  2345. self.verify_pkcs12_container(
  2346. self._dump_and_load(dump_passphrase=b"", load_passphrase=b"")
  2347. )
  2348. def test_load_pkcs12_empty_passphrase_load_null(self):
  2349. """
  2350. A PKCS12 string can be dumped with an empty passphrase, loaded with a
  2351. null passphrase with `load_pkcs12`, and its components
  2352. extracted and examined.
  2353. """
  2354. self.verify_pkcs12_container(
  2355. self._dump_and_load(dump_passphrase=b"", load_passphrase=None)
  2356. )
  2357. def test_load_pkcs12_garbage(self):
  2358. """
  2359. `load_pkcs12` raises `OpenSSL.crypto.Error` when passed
  2360. a string which is not a PKCS12 dump.
  2361. """
  2362. passwd = b"whatever"
  2363. with pytest.raises(Error) as err:
  2364. load_pkcs12(b"fruit loops", passwd)
  2365. assert err.value.args[0][0][0] == "asn1 encoding routines"
  2366. assert len(err.value.args[0][0]) == 3
  2367. def test_replace(self):
  2368. """
  2369. `PKCS12.set_certificate` replaces the certificate in a PKCS12
  2370. cluster. `PKCS12.set_privatekey` replaces the private key.
  2371. `PKCS12.set_ca_certificates` replaces the CA certificates.
  2372. """
  2373. p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
  2374. p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem))
  2375. p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem))
  2376. root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  2377. client_cert = load_certificate(FILETYPE_PEM, client_cert_pem)
  2378. p12.set_ca_certificates([root_cert]) # not a tuple
  2379. assert 1 == len(p12.get_ca_certificates())
  2380. assert root_cert == p12.get_ca_certificates()[0]
  2381. p12.set_ca_certificates([client_cert, root_cert])
  2382. assert 2 == len(p12.get_ca_certificates())
  2383. assert client_cert == p12.get_ca_certificates()[0]
  2384. assert root_cert == p12.get_ca_certificates()[1]
  2385. def test_friendly_name(self):
  2386. """
  2387. The *friendlyName* of a PKCS12 can be set and retrieved via
  2388. `PKCS12.get_friendlyname` and `PKCS12_set_friendlyname`, and a
  2389. `PKCS12` with a friendly name set can be dumped with `PKCS12.export`.
  2390. """
  2391. passwd = b'Dogmeat[]{}!@#$%^&*()~`?/.,<>-_+=";:'
  2392. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
  2393. for friendly_name in [b"Serverlicious", None, b"###"]:
  2394. p12.set_friendlyname(friendly_name)
  2395. assert p12.get_friendlyname() == friendly_name
  2396. dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3)
  2397. reloaded_p12 = load_pkcs12(dumped_p12, passwd)
  2398. assert p12.get_friendlyname() == reloaded_p12.get_friendlyname()
  2399. # We would use the openssl program to confirm the friendly
  2400. # name, but it is not possible. The pkcs12 command
  2401. # does not store the friendly name in the cert's
  2402. # alias, which we could then extract.
  2403. self.check_recovery(
  2404. dumped_p12,
  2405. key=server_key_pem,
  2406. cert=server_cert_pem,
  2407. ca=root_cert_pem,
  2408. passwd=passwd,
  2409. )
  2410. def test_various_empty_passphrases(self):
  2411. """
  2412. Test that missing, None, and '' passphrases are identical for PKCS12
  2413. export.
  2414. """
  2415. p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem)
  2416. passwd = b""
  2417. dumped_p12_empty = p12.export(iter=2, maciter=0, passphrase=passwd)
  2418. dumped_p12_none = p12.export(iter=3, maciter=2, passphrase=None)
  2419. dumped_p12_nopw = p12.export(iter=9, maciter=4)
  2420. for dumped_p12 in [dumped_p12_empty, dumped_p12_none, dumped_p12_nopw]:
  2421. self.check_recovery(
  2422. dumped_p12,
  2423. key=client_key_pem,
  2424. cert=client_cert_pem,
  2425. ca=root_cert_pem,
  2426. passwd=passwd,
  2427. )
  2428. def test_removing_ca_cert(self):
  2429. """
  2430. Passing `None` to `PKCS12.set_ca_certificates` removes all CA
  2431. certificates.
  2432. """
  2433. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
  2434. p12.set_ca_certificates(None)
  2435. assert None is p12.get_ca_certificates()
  2436. def test_export_without_mac(self):
  2437. """
  2438. Exporting a PKCS12 with a `maciter` of `-1` excludes the MAC entirely.
  2439. """
  2440. passwd = b"Lake Michigan"
  2441. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
  2442. dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
  2443. self.check_recovery(
  2444. dumped_p12,
  2445. key=server_key_pem,
  2446. cert=server_cert_pem,
  2447. passwd=passwd,
  2448. extra=(b"-nomacver",),
  2449. )
  2450. def test_load_without_mac(self):
  2451. """
  2452. Loading a PKCS12 without a MAC does something other than crash.
  2453. """
  2454. passwd = b"Lake Michigan"
  2455. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
  2456. dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2)
  2457. try:
  2458. recovered_p12 = load_pkcs12(dumped_p12, passwd)
  2459. # The person who generated this PCKS12 should be flogged,
  2460. # or better yet we should have a means to determine
  2461. # whether a PCKS12 had a MAC that was verified.
  2462. # Anyway, libopenssl chooses to allow it, so the
  2463. # pyopenssl binding does as well.
  2464. assert isinstance(recovered_p12, PKCS12)
  2465. except Error:
  2466. # Failing here with an exception is preferred as some openssl
  2467. # versions do.
  2468. pass
  2469. def test_zero_len_list_for_ca(self):
  2470. """
  2471. A PKCS12 with an empty CA certificates list can be exported.
  2472. """
  2473. passwd = b"Hobie 18"
  2474. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem)
  2475. p12.set_ca_certificates([])
  2476. assert () == p12.get_ca_certificates()
  2477. dumped_p12 = p12.export(passphrase=passwd, iter=3)
  2478. self.check_recovery(
  2479. dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=passwd
  2480. )
  2481. def test_export_without_args(self):
  2482. """
  2483. All the arguments to `PKCS12.export` are optional.
  2484. """
  2485. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
  2486. dumped_p12 = p12.export() # no args
  2487. self.check_recovery(
  2488. dumped_p12, key=server_key_pem, cert=server_cert_pem, passwd=b""
  2489. )
  2490. def test_export_without_bytes(self):
  2491. """
  2492. Test `PKCS12.export` with text not bytes as passphrase
  2493. """
  2494. p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem)
  2495. with pytest.warns(DeprecationWarning) as w:
  2496. simplefilter("always")
  2497. dumped_p12 = p12.export(passphrase=b"randomtext".decode("ascii"))
  2498. msg = "{0} for passphrase is no longer accepted, use bytes".format(
  2499. WARNING_TYPE_EXPECTED
  2500. )
  2501. assert msg == str(w[-1].message)
  2502. self.check_recovery(
  2503. dumped_p12,
  2504. key=server_key_pem,
  2505. cert=server_cert_pem,
  2506. passwd=b"randomtext",
  2507. )
  2508. def test_key_cert_mismatch(self):
  2509. """
  2510. `PKCS12.export` raises an exception when a key and certificate
  2511. mismatch.
  2512. """
  2513. p12 = self.gen_pkcs12(server_cert_pem, client_key_pem, root_cert_pem)
  2514. with pytest.raises(Error):
  2515. p12.export()
  2516. def _runopenssl(pem, *args):
  2517. """
  2518. Run the command line openssl tool with the given arguments and write
  2519. the given PEM to its stdin. Not safe for quotes.
  2520. """
  2521. proc = Popen([b"openssl"] + list(args), stdin=PIPE, stdout=PIPE)
  2522. proc.stdin.write(pem)
  2523. proc.stdin.close()
  2524. output = proc.stdout.read()
  2525. proc.stdout.close()
  2526. proc.wait()
  2527. return output
  2528. class TestLoadPublicKey(object):
  2529. """
  2530. Tests for :func:`load_publickey`.
  2531. """
  2532. def test_loading_works(self):
  2533. """
  2534. load_publickey loads public keys and sets correct attributes.
  2535. """
  2536. key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
  2537. assert True is key._only_public
  2538. assert 2048 == key.bits()
  2539. assert TYPE_RSA == key.type()
  2540. def test_invalid_type(self):
  2541. """
  2542. load_publickey doesn't support FILETYPE_TEXT.
  2543. """
  2544. with pytest.raises(ValueError):
  2545. load_publickey(FILETYPE_TEXT, cleartextPublicKeyPEM)
  2546. def test_invalid_key_format(self):
  2547. """
  2548. load_publickey explodes on incorrect keys.
  2549. """
  2550. with pytest.raises(Error):
  2551. load_publickey(FILETYPE_ASN1, cleartextPublicKeyPEM)
  2552. def test_tolerates_unicode_strings(self):
  2553. """
  2554. load_publickey works with text strings, not just bytes.
  2555. """
  2556. serialized = cleartextPublicKeyPEM.decode("ascii")
  2557. key = load_publickey(FILETYPE_PEM, serialized)
  2558. dumped_pem = dump_publickey(FILETYPE_PEM, key)
  2559. assert dumped_pem == cleartextPublicKeyPEM
  2560. class TestFunction(object):
  2561. """
  2562. Tests for free-functions in the `OpenSSL.crypto` module.
  2563. """
  2564. def test_load_privatekey_invalid_format(self):
  2565. """
  2566. `load_privatekey` raises `ValueError` if passed an unknown filetype.
  2567. """
  2568. with pytest.raises(ValueError):
  2569. load_privatekey(100, root_key_pem)
  2570. def test_load_privatekey_invalid_passphrase_type(self):
  2571. """
  2572. `load_privatekey` raises `TypeError` if passed a passphrase that is
  2573. neither a `str` nor a callable.
  2574. """
  2575. with pytest.raises(TypeError):
  2576. load_privatekey(
  2577. FILETYPE_PEM, encryptedPrivateKeyPEMPassphrase, object()
  2578. )
  2579. def test_load_privatekey_wrongPassphrase(self):
  2580. """
  2581. `load_privatekey` raises `OpenSSL.crypto.Error` when it is passed an
  2582. encrypted PEM and an incorrect passphrase.
  2583. """
  2584. with pytest.raises(Error) as err:
  2585. load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, b"quack")
  2586. assert err.value.args[0] != []
  2587. def test_load_privatekey_passphraseWrongType(self):
  2588. """
  2589. `load_privatekey` raises `ValueError` when it is passeda passphrase
  2590. with a private key encoded in a format, that doesn't support
  2591. encryption.
  2592. """
  2593. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2594. blob = dump_privatekey(FILETYPE_ASN1, key)
  2595. with pytest.raises(ValueError):
  2596. load_privatekey(FILETYPE_ASN1, blob, "secret")
  2597. def test_load_privatekey_passphrase(self):
  2598. """
  2599. `load_privatekey` can create a `PKey` object from an encrypted PEM
  2600. string if given the passphrase.
  2601. """
  2602. key = load_privatekey(
  2603. FILETYPE_PEM,
  2604. encryptedPrivateKeyPEM,
  2605. encryptedPrivateKeyPEMPassphrase,
  2606. )
  2607. assert isinstance(key, PKey)
  2608. def test_load_privatekey_passphrase_exception(self):
  2609. """
  2610. If the passphrase callback raises an exception, that exception is
  2611. raised by `load_privatekey`.
  2612. """
  2613. def cb(ignored):
  2614. raise ArithmeticError
  2615. with pytest.raises(ArithmeticError):
  2616. load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
  2617. def test_load_privatekey_wrongPassphraseCallback(self):
  2618. """
  2619. `load_privatekey` raises `OpenSSL.crypto.Error` when it
  2620. is passed an encrypted PEM and a passphrase callback which returns an
  2621. incorrect passphrase.
  2622. """
  2623. called = []
  2624. def cb(*a):
  2625. called.append(None)
  2626. return b"quack"
  2627. with pytest.raises(Error) as err:
  2628. load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
  2629. assert called
  2630. assert err.value.args[0] != []
  2631. def test_load_privatekey_passphraseCallback(self):
  2632. """
  2633. `load_privatekey` can create a `PKey` object from an encrypted PEM
  2634. string if given a passphrase callback which returns the correct
  2635. password.
  2636. """
  2637. called = []
  2638. def cb(writing):
  2639. called.append(writing)
  2640. return encryptedPrivateKeyPEMPassphrase
  2641. key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
  2642. assert isinstance(key, PKey)
  2643. assert called == [False]
  2644. def test_load_privatekey_passphrase_wrong_return_type(self):
  2645. """
  2646. `load_privatekey` raises `ValueError` if the passphrase callback
  2647. returns something other than a byte string.
  2648. """
  2649. with pytest.raises(ValueError):
  2650. load_privatekey(
  2651. FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3
  2652. )
  2653. def test_dump_privatekey_wrong_args(self):
  2654. """
  2655. `dump_privatekey` raises `TypeError` if called with a `cipher`
  2656. argument but no `passphrase` argument.
  2657. """
  2658. key = PKey()
  2659. key.generate_key(TYPE_RSA, 512)
  2660. with pytest.raises(TypeError):
  2661. dump_privatekey(FILETYPE_PEM, key, cipher=GOOD_CIPHER)
  2662. def test_dump_privatekey_not_rsa_key(self):
  2663. """
  2664. `dump_privatekey` raises `TypeError` if called with a key that is
  2665. not RSA.
  2666. """
  2667. key = PKey()
  2668. key.generate_key(TYPE_DSA, 512)
  2669. with pytest.raises(TypeError):
  2670. dump_privatekey(FILETYPE_TEXT, key)
  2671. def test_dump_privatekey_invalid_pkey(self):
  2672. with pytest.raises(TypeError):
  2673. dump_privatekey(FILETYPE_TEXT, object())
  2674. def test_dump_privatekey_unknown_cipher(self):
  2675. """
  2676. `dump_privatekey` raises `ValueError` if called with an unrecognized
  2677. cipher name.
  2678. """
  2679. key = PKey()
  2680. key.generate_key(TYPE_RSA, 512)
  2681. with pytest.raises(ValueError):
  2682. dump_privatekey(FILETYPE_PEM, key, BAD_CIPHER, "passphrase")
  2683. def test_dump_privatekey_invalid_passphrase_type(self):
  2684. """
  2685. `dump_privatekey` raises `TypeError` if called with a passphrase which
  2686. is neither a `str` nor a callable.
  2687. """
  2688. key = PKey()
  2689. key.generate_key(TYPE_RSA, 512)
  2690. with pytest.raises(TypeError):
  2691. dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, object())
  2692. def test_dump_privatekey_invalid_filetype(self):
  2693. """
  2694. `dump_privatekey` raises `ValueError` if called with an unrecognized
  2695. filetype.
  2696. """
  2697. key = PKey()
  2698. key.generate_key(TYPE_RSA, 512)
  2699. with pytest.raises(ValueError):
  2700. dump_privatekey(100, key)
  2701. def test_load_privatekey_passphrase_callback_length(self):
  2702. """
  2703. `crypto.load_privatekey` should raise an error when the passphrase
  2704. provided by the callback is too long, not silently truncate it.
  2705. """
  2706. def cb(ignored):
  2707. return "a" * 1025
  2708. with pytest.raises(ValueError):
  2709. load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
  2710. def test_dump_privatekey_passphrase(self):
  2711. """
  2712. `dump_privatekey` writes an encrypted PEM when given a passphrase.
  2713. """
  2714. passphrase = b"foo"
  2715. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2716. pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase)
  2717. assert isinstance(pem, bytes)
  2718. loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
  2719. assert isinstance(loadedKey, PKey)
  2720. assert loadedKey.type() == key.type()
  2721. assert loadedKey.bits() == key.bits()
  2722. def test_dump_privatekey_passphrase_wrong_type(self):
  2723. """
  2724. `dump_privatekey` raises `ValueError` when it is passed a passphrase
  2725. with a private key encoded in a format, that doesn't support
  2726. encryption.
  2727. """
  2728. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2729. with pytest.raises(ValueError):
  2730. dump_privatekey(FILETYPE_ASN1, key, GOOD_CIPHER, "secret")
  2731. def test_dump_certificate(self):
  2732. """
  2733. `dump_certificate` writes PEM, DER, and text.
  2734. """
  2735. pemData = root_cert_pem + root_key_pem
  2736. cert = load_certificate(FILETYPE_PEM, pemData)
  2737. dumped_pem = dump_certificate(FILETYPE_PEM, cert)
  2738. assert dumped_pem == root_cert_pem
  2739. dumped_der = dump_certificate(FILETYPE_ASN1, cert)
  2740. good_der = _runopenssl(dumped_pem, b"x509", b"-outform", b"DER")
  2741. assert dumped_der == good_der
  2742. cert2 = load_certificate(FILETYPE_ASN1, dumped_der)
  2743. dumped_pem2 = dump_certificate(FILETYPE_PEM, cert2)
  2744. assert dumped_pem2 == root_cert_pem
  2745. dumped_text = dump_certificate(FILETYPE_TEXT, cert)
  2746. assert len(dumped_text) > 500
  2747. def test_dump_certificate_bad_type(self):
  2748. """
  2749. `dump_certificate` raises a `ValueError` if it's called with
  2750. a bad type.
  2751. """
  2752. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  2753. with pytest.raises(ValueError):
  2754. dump_certificate(object(), cert)
  2755. def test_dump_privatekey_pem(self):
  2756. """
  2757. `dump_privatekey` writes a PEM
  2758. """
  2759. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2760. assert key.check()
  2761. dumped_pem = dump_privatekey(FILETYPE_PEM, key)
  2762. assert dumped_pem == normalized_root_key_pem
  2763. def test_dump_privatekey_asn1(self):
  2764. """
  2765. `dump_privatekey` writes a DER
  2766. """
  2767. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2768. dumped_der = dump_privatekey(FILETYPE_ASN1, key)
  2769. assert dumped_der == root_key_der
  2770. def test_load_privatekey_asn1(self):
  2771. """
  2772. `dump_privatekey` writes a DER
  2773. """
  2774. key = load_privatekey(FILETYPE_ASN1, root_key_der)
  2775. assert key.bits() == 3072
  2776. assert key.type() == TYPE_RSA
  2777. def test_dump_privatekey_text(self):
  2778. """
  2779. `dump_privatekey` writes a text
  2780. """
  2781. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2782. dumped_text = dump_privatekey(FILETYPE_TEXT, key)
  2783. assert len(dumped_text) > 500
  2784. def test_dump_publickey_pem(self):
  2785. """
  2786. dump_publickey writes a PEM.
  2787. """
  2788. key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
  2789. dumped_pem = dump_publickey(FILETYPE_PEM, key)
  2790. assert dumped_pem == cleartextPublicKeyPEM
  2791. def test_dump_publickey_asn1(self):
  2792. """
  2793. dump_publickey writes a DER.
  2794. """
  2795. key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
  2796. dumped_der = dump_publickey(FILETYPE_ASN1, key)
  2797. key2 = load_publickey(FILETYPE_ASN1, dumped_der)
  2798. dumped_pem2 = dump_publickey(FILETYPE_PEM, key2)
  2799. assert dumped_pem2 == cleartextPublicKeyPEM
  2800. def test_dump_publickey_invalid_type(self):
  2801. """
  2802. dump_publickey doesn't support FILETYPE_TEXT.
  2803. """
  2804. key = load_publickey(FILETYPE_PEM, cleartextPublicKeyPEM)
  2805. with pytest.raises(ValueError):
  2806. dump_publickey(FILETYPE_TEXT, key)
  2807. def test_dump_certificate_request(self):
  2808. """
  2809. `dump_certificate_request` writes a PEM, DER, and text.
  2810. """
  2811. req = load_certificate_request(
  2812. FILETYPE_PEM, cleartextCertificateRequestPEM
  2813. )
  2814. dumped_pem = dump_certificate_request(FILETYPE_PEM, req)
  2815. assert dumped_pem == cleartextCertificateRequestPEM
  2816. dumped_der = dump_certificate_request(FILETYPE_ASN1, req)
  2817. good_der = _runopenssl(dumped_pem, b"req", b"-outform", b"DER")
  2818. assert dumped_der == good_der
  2819. req2 = load_certificate_request(FILETYPE_ASN1, dumped_der)
  2820. dumped_pem2 = dump_certificate_request(FILETYPE_PEM, req2)
  2821. assert dumped_pem2 == cleartextCertificateRequestPEM
  2822. dumped_text = dump_certificate_request(FILETYPE_TEXT, req)
  2823. assert len(dumped_text) > 500
  2824. with pytest.raises(ValueError):
  2825. dump_certificate_request(100, req)
  2826. def test_dump_privatekey_passphrase_callback(self):
  2827. """
  2828. `dump_privatekey` writes an encrypted PEM when given a callback
  2829. which returns the correct passphrase.
  2830. """
  2831. passphrase = b"foo"
  2832. called = []
  2833. def cb(writing):
  2834. called.append(writing)
  2835. return passphrase
  2836. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2837. pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
  2838. assert isinstance(pem, bytes)
  2839. assert called == [True]
  2840. loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase)
  2841. assert isinstance(loadedKey, PKey)
  2842. assert loadedKey.type() == key.type()
  2843. assert loadedKey.bits() == key.bits()
  2844. def test_dump_privatekey_passphrase_exception(self):
  2845. """
  2846. `dump_privatekey` should not overwrite the exception raised
  2847. by the passphrase callback.
  2848. """
  2849. def cb(ignored):
  2850. raise ArithmeticError
  2851. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2852. with pytest.raises(ArithmeticError):
  2853. dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
  2854. def test_dump_privatekey_passphraseCallbackLength(self):
  2855. """
  2856. `crypto.dump_privatekey` should raise an error when the passphrase
  2857. provided by the callback is too long, not silently truncate it.
  2858. """
  2859. def cb(ignored):
  2860. return "a" * 1025
  2861. key = load_privatekey(FILETYPE_PEM, root_key_pem)
  2862. with pytest.raises(ValueError):
  2863. dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb)
  2864. def test_dump_privatekey_truncated(self):
  2865. """
  2866. `crypto.dump_privatekey` should not truncate a passphrase that contains
  2867. a null byte.
  2868. """
  2869. key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
  2870. passphrase = b"foo\x00bar"
  2871. truncated_passphrase = passphrase.split(b"\x00", 1)[0]
  2872. # By dumping with the full passphrase load should raise an error if we
  2873. # try to load using the truncated passphrase. If dump truncated the
  2874. # passphrase, then we WILL load the privatekey and the test fails
  2875. encrypted_key_pem = dump_privatekey(
  2876. FILETYPE_PEM, key, "AES-256-CBC", passphrase
  2877. )
  2878. with pytest.raises(Error):
  2879. load_privatekey(
  2880. FILETYPE_PEM, encrypted_key_pem, truncated_passphrase
  2881. )
  2882. def test_load_privatekey_truncated(self):
  2883. """
  2884. `crypto.load_privatekey` should not truncate a passphrase that contains
  2885. a null byte.
  2886. """
  2887. key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)
  2888. passphrase = b"foo\x00bar"
  2889. truncated_passphrase = passphrase.split(b"\x00", 1)[0]
  2890. # By dumping using the truncated passphrase load should raise an error
  2891. # if we try to load using the full passphrase. If load truncated the
  2892. # passphrase, then we WILL load the privatekey and the test fails
  2893. encrypted_key_pem = dump_privatekey(
  2894. FILETYPE_PEM, key, "AES-256-CBC", truncated_passphrase
  2895. )
  2896. with pytest.raises(Error):
  2897. load_privatekey(FILETYPE_PEM, encrypted_key_pem, passphrase)
  2898. def test_load_pkcs7_data_pem(self):
  2899. """
  2900. `load_pkcs7_data` accepts a PKCS#7 string and returns an instance of
  2901. `PKCS`.
  2902. """
  2903. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2904. assert isinstance(pkcs7, PKCS7)
  2905. def test_load_pkcs7_data_asn1(self):
  2906. """
  2907. `load_pkcs7_data` accepts a bytes containing ASN1 data representing
  2908. PKCS#7 and returns an instance of `PKCS7`.
  2909. """
  2910. pkcs7 = load_pkcs7_data(FILETYPE_ASN1, pkcs7DataASN1)
  2911. assert isinstance(pkcs7, PKCS7)
  2912. def test_load_pkcs7_data_invalid(self):
  2913. """
  2914. If the data passed to `load_pkcs7_data` is invalid, `Error` is raised.
  2915. """
  2916. with pytest.raises(Error):
  2917. load_pkcs7_data(FILETYPE_PEM, b"foo")
  2918. def test_load_pkcs7_type_invalid(self):
  2919. """
  2920. If the type passed to `load_pkcs7_data`, `ValueError` is raised.
  2921. """
  2922. with pytest.raises(ValueError):
  2923. load_pkcs7_data(object(), b"foo")
  2924. class TestLoadCertificate(object):
  2925. """
  2926. Tests for `load_certificate_request`.
  2927. """
  2928. def test_bad_file_type(self):
  2929. """
  2930. If the file type passed to `load_certificate_request` is neither
  2931. `FILETYPE_PEM` nor `FILETYPE_ASN1` then `ValueError` is raised.
  2932. """
  2933. with pytest.raises(ValueError):
  2934. load_certificate_request(object(), b"")
  2935. with pytest.raises(ValueError):
  2936. load_certificate(object(), b"")
  2937. def test_bad_certificate(self):
  2938. """
  2939. If the bytes passed to `load_certificate` are not a valid certificate,
  2940. an exception is raised.
  2941. """
  2942. with pytest.raises(Error):
  2943. load_certificate(FILETYPE_ASN1, b"lol")
  2944. class TestPKCS7(object):
  2945. """
  2946. Tests for `PKCS7`.
  2947. """
  2948. def test_type_is_signed(self):
  2949. """
  2950. `PKCS7.type_is_signed` returns `True` if the PKCS7 object is of
  2951. the type *signed*.
  2952. """
  2953. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2954. assert pkcs7.type_is_signed()
  2955. def test_type_is_enveloped(self):
  2956. """
  2957. `PKCS7.type_is_enveloped` returns `False` if the PKCS7 object is not
  2958. of the type *enveloped*.
  2959. """
  2960. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2961. assert not pkcs7.type_is_enveloped()
  2962. def test_type_is_signed_and_enveloped(self):
  2963. """
  2964. `PKCS7.type_is_signedAndEnveloped` returns `False`
  2965. if the PKCS7 object is not of the type *signed and enveloped*.
  2966. """
  2967. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2968. assert not pkcs7.type_is_signedAndEnveloped()
  2969. def test_type_is_data(self):
  2970. """
  2971. `PKCS7.type_is_data` returns `False` if the PKCS7 object is not of
  2972. the type data.
  2973. """
  2974. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2975. assert not pkcs7.type_is_data()
  2976. def test_get_type_name(self):
  2977. """
  2978. `PKCS7.get_type_name` returns a `str` giving the
  2979. type name.
  2980. """
  2981. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2982. assert pkcs7.get_type_name() == b"pkcs7-signedData"
  2983. def test_attribute(self):
  2984. """
  2985. If an attribute other than one of the methods tested here is accessed
  2986. on an instance of `PKCS7`, `AttributeError` is raised.
  2987. """
  2988. pkcs7 = load_pkcs7_data(FILETYPE_PEM, pkcs7Data)
  2989. with pytest.raises(AttributeError):
  2990. pkcs7.foo
  2991. class TestNetscapeSPKI(_PKeyInteractionTestsMixin):
  2992. """
  2993. Tests for `OpenSSL.crypto.NetscapeSPKI`.
  2994. """
  2995. def signable(self):
  2996. """
  2997. Return a new `NetscapeSPKI` for use with signing tests.
  2998. """
  2999. return NetscapeSPKI()
  3000. def test_type(self):
  3001. """
  3002. `NetscapeSPKI` can be used to create instances of that type.
  3003. """
  3004. assert is_consistent_type(NetscapeSPKI, "NetscapeSPKI")
  3005. def test_construction(self):
  3006. """
  3007. `NetscapeSPKI` returns an instance of `NetscapeSPKI`.
  3008. """
  3009. nspki = NetscapeSPKI()
  3010. assert isinstance(nspki, NetscapeSPKI)
  3011. def test_invalid_attribute(self):
  3012. """
  3013. Accessing a non-existent attribute of a `NetscapeSPKI` instance
  3014. causes an `AttributeError` to be raised.
  3015. """
  3016. nspki = NetscapeSPKI()
  3017. with pytest.raises(AttributeError):
  3018. nspki.foo
  3019. def test_b64_encode(self):
  3020. """
  3021. `NetscapeSPKI.b64_encode` encodes the certificate to a base64 blob.
  3022. """
  3023. nspki = NetscapeSPKI()
  3024. pkey = load_privatekey(FILETYPE_PEM, root_key_pem)
  3025. nspki.set_pubkey(pkey)
  3026. nspki.sign(pkey, GOOD_DIGEST)
  3027. blob = nspki.b64_encode()
  3028. assert isinstance(blob, bytes)
  3029. class TestRevoked(object):
  3030. """
  3031. Tests for `OpenSSL.crypto.Revoked`.
  3032. """
  3033. def test_ignores_unsupported_revoked_cert_extension_get_reason(self):
  3034. """
  3035. The get_reason method on the Revoked class checks to see if the
  3036. extension is NID_crl_reason and should skip it otherwise. This test
  3037. loads a CRL with extensions it should ignore.
  3038. """
  3039. crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
  3040. revoked = crl.get_revoked()
  3041. reason = revoked[1].get_reason()
  3042. assert reason == b"Unspecified"
  3043. def test_ignores_unsupported_revoked_cert_extension_set_new_reason(self):
  3044. crl = load_crl(FILETYPE_PEM, crlDataUnsupportedExtension)
  3045. revoked = crl.get_revoked()
  3046. revoked[1].set_reason(None)
  3047. reason = revoked[1].get_reason()
  3048. assert reason is None
  3049. def test_construction(self):
  3050. """
  3051. Confirm we can create `OpenSSL.crypto.Revoked`. Check that it is
  3052. empty.
  3053. """
  3054. revoked = Revoked()
  3055. assert isinstance(revoked, Revoked)
  3056. assert type(revoked) == Revoked
  3057. assert revoked.get_serial() == b"00"
  3058. assert revoked.get_rev_date() is None
  3059. assert revoked.get_reason() is None
  3060. def test_serial(self):
  3061. """
  3062. Confirm we can set and get serial numbers from
  3063. `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
  3064. """
  3065. revoked = Revoked()
  3066. ret = revoked.set_serial(b"10b")
  3067. assert ret is None
  3068. ser = revoked.get_serial()
  3069. assert ser == b"010B"
  3070. revoked.set_serial(b"31ppp") # a type error would be nice
  3071. ser = revoked.get_serial()
  3072. assert ser == b"31"
  3073. with pytest.raises(ValueError):
  3074. revoked.set_serial(b"pqrst")
  3075. with pytest.raises(TypeError):
  3076. revoked.set_serial(100)
  3077. def test_date(self):
  3078. """
  3079. Confirm we can set and get revocation dates from
  3080. `OpenSSL.crypto.Revoked`. Confirm errors are handled with grace.
  3081. """
  3082. revoked = Revoked()
  3083. date = revoked.get_rev_date()
  3084. assert date is None
  3085. now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
  3086. ret = revoked.set_rev_date(now)
  3087. assert ret is None
  3088. date = revoked.get_rev_date()
  3089. assert date == now
  3090. def test_reason(self):
  3091. """
  3092. Confirm we can set and get revocation reasons from
  3093. `OpenSSL.crypto.Revoked`. The "get" need to work as "set".
  3094. Likewise, each reason of all_reasons() must work.
  3095. """
  3096. revoked = Revoked()
  3097. for r in revoked.all_reasons():
  3098. for x in range(2):
  3099. ret = revoked.set_reason(r)
  3100. assert ret is None
  3101. reason = revoked.get_reason()
  3102. assert reason.lower().replace(b" ", b"") == r.lower().replace(
  3103. b" ", b""
  3104. )
  3105. r = reason # again with the resp of get
  3106. revoked.set_reason(None)
  3107. assert revoked.get_reason() is None
  3108. @pytest.mark.parametrize("reason", [object(), 1.0, u"foo"])
  3109. def test_set_reason_wrong_args(self, reason):
  3110. """
  3111. `Revoked.set_reason` raises `TypeError` if called with an argument
  3112. which is neither `None` nor a byte string.
  3113. """
  3114. revoked = Revoked()
  3115. with pytest.raises(TypeError):
  3116. revoked.set_reason(reason)
  3117. def test_set_reason_invalid_reason(self):
  3118. """
  3119. Calling `OpenSSL.crypto.Revoked.set_reason` with an argument which
  3120. isn't a valid reason results in `ValueError` being raised.
  3121. """
  3122. revoked = Revoked()
  3123. with pytest.raises(ValueError):
  3124. revoked.set_reason(b"blue")
  3125. class TestCRL(object):
  3126. """
  3127. Tests for `OpenSSL.crypto.CRL`.
  3128. """
  3129. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3130. pkey = load_privatekey(FILETYPE_PEM, root_key_pem)
  3131. root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3132. root_key = load_privatekey(FILETYPE_PEM, root_key_pem)
  3133. intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
  3134. intermediate_key = load_privatekey(FILETYPE_PEM, intermediate_key_pem)
  3135. intermediate_server_cert = load_certificate(
  3136. FILETYPE_PEM, intermediate_server_cert_pem
  3137. )
  3138. intermediate_server_key = load_privatekey(
  3139. FILETYPE_PEM, intermediate_server_key_pem
  3140. )
  3141. def test_construction(self):
  3142. """
  3143. Confirm we can create `OpenSSL.crypto.CRL`. Check
  3144. that it is empty
  3145. """
  3146. crl = CRL()
  3147. assert isinstance(crl, CRL)
  3148. assert crl.get_revoked() is None
  3149. def _get_crl(self):
  3150. """
  3151. Get a new ``CRL`` with a revocation.
  3152. """
  3153. crl = CRL()
  3154. revoked = Revoked()
  3155. now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
  3156. revoked.set_rev_date(now)
  3157. revoked.set_serial(b"3ab")
  3158. revoked.set_reason(b"sUpErSeDEd")
  3159. crl.add_revoked(revoked)
  3160. return crl
  3161. def test_export_pem(self):
  3162. """
  3163. If not passed a format, ``CRL.export`` returns a "PEM" format string
  3164. representing a serial number, a revoked reason, and certificate issuer
  3165. information.
  3166. """
  3167. # PEM format
  3168. dumped_crl = self._get_crl().export(
  3169. self.cert, self.pkey, days=20, digest=b"sha256"
  3170. )
  3171. crl = x509.load_pem_x509_crl(dumped_crl, backend)
  3172. revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
  3173. assert revoked is not None
  3174. assert crl.issuer == x509.Name(
  3175. [
  3176. x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
  3177. x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
  3178. x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
  3179. x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
  3180. x509.NameAttribute(
  3181. x509.NameOID.COMMON_NAME, u"Testing Root CA"
  3182. ),
  3183. ]
  3184. )
  3185. def test_export_der(self):
  3186. """
  3187. If passed ``FILETYPE_ASN1`` for the format, ``CRL.export`` returns a
  3188. "DER" format string representing a serial number, a revoked reason, and
  3189. certificate issuer information.
  3190. """
  3191. crl = self._get_crl()
  3192. # DER format
  3193. dumped_crl = self._get_crl().export(
  3194. self.cert, self.pkey, FILETYPE_ASN1, digest=b"md5"
  3195. )
  3196. crl = x509.load_der_x509_crl(dumped_crl, backend)
  3197. revoked = crl.get_revoked_certificate_by_serial_number(0x03AB)
  3198. assert revoked is not None
  3199. assert crl.issuer == x509.Name(
  3200. [
  3201. x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"),
  3202. x509.NameAttribute(x509.NameOID.STATE_OR_PROVINCE_NAME, u"IL"),
  3203. x509.NameAttribute(x509.NameOID.LOCALITY_NAME, u"Chicago"),
  3204. x509.NameAttribute(x509.NameOID.ORGANIZATION_NAME, u"Testing"),
  3205. x509.NameAttribute(
  3206. x509.NameOID.COMMON_NAME, u"Testing Root CA"
  3207. ),
  3208. ]
  3209. )
  3210. def test_export_text(self):
  3211. """
  3212. If passed ``FILETYPE_TEXT`` for the format, ``CRL.export`` returns a
  3213. text format string like the one produced by the openssl command line
  3214. tool.
  3215. """
  3216. crl = self._get_crl()
  3217. # text format
  3218. dumped_text = crl.export(
  3219. self.cert, self.pkey, type=FILETYPE_TEXT, digest=b"md5"
  3220. )
  3221. assert len(dumped_text) > 500
  3222. def test_export_custom_digest(self):
  3223. """
  3224. If passed the name of a digest function, ``CRL.export`` uses a
  3225. signature algorithm based on that digest function.
  3226. """
  3227. crl = self._get_crl()
  3228. dumped_crl = crl.export(self.cert, self.pkey, digest=b"sha1")
  3229. text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
  3230. text.index(b"Signature Algorithm: sha1")
  3231. def test_export_md5_digest(self):
  3232. """
  3233. If passed md5 as the digest function, ``CRL.export`` uses md5 and does
  3234. not emit a deprecation warning.
  3235. """
  3236. crl = self._get_crl()
  3237. with pytest.warns(None) as catcher:
  3238. simplefilter("always")
  3239. assert 0 == len(catcher)
  3240. dumped_crl = crl.export(self.cert, self.pkey, digest=b"md5")
  3241. text = _runopenssl(dumped_crl, b"crl", b"-noout", b"-text")
  3242. text.index(b"Signature Algorithm: md5")
  3243. def test_export_default_digest(self):
  3244. """
  3245. If not passed the name of a digest function, ``CRL.export`` raises a
  3246. ``TypeError``.
  3247. """
  3248. crl = self._get_crl()
  3249. with pytest.raises(TypeError):
  3250. crl.export(self.cert, self.pkey)
  3251. def test_export_invalid(self):
  3252. """
  3253. If `CRL.export` is used with an uninitialized `X509` instance,
  3254. `OpenSSL.crypto.Error` is raised.
  3255. """
  3256. crl = CRL()
  3257. with pytest.raises(Error):
  3258. crl.export(X509(), PKey(), digest=b"sha256")
  3259. def test_add_revoked_keyword(self):
  3260. """
  3261. `OpenSSL.CRL.add_revoked` accepts its single argument as the
  3262. ``revoked`` keyword argument.
  3263. """
  3264. crl = CRL()
  3265. revoked = Revoked()
  3266. revoked.set_serial(b"01")
  3267. revoked.set_rev_date(b"20160310020145Z")
  3268. crl.add_revoked(revoked=revoked)
  3269. assert isinstance(crl.get_revoked()[0], Revoked)
  3270. def test_export_wrong_args(self):
  3271. """
  3272. Calling `OpenSSL.CRL.export` with arguments other than the certificate,
  3273. private key, integer file type, and integer number of days it
  3274. expects, results in a `TypeError` being raised.
  3275. """
  3276. crl = CRL()
  3277. with pytest.raises(TypeError):
  3278. crl.export(None, self.pkey, FILETYPE_PEM, 10)
  3279. with pytest.raises(TypeError):
  3280. crl.export(self.cert, None, FILETYPE_PEM, 10)
  3281. with pytest.raises(TypeError):
  3282. crl.export(self.cert, self.pkey, None, 10)
  3283. with pytest.raises(TypeError):
  3284. crl.export(self.cert, FILETYPE_PEM, None)
  3285. def test_export_unknown_filetype(self):
  3286. """
  3287. Calling `OpenSSL.CRL.export` with a file type other than
  3288. `FILETYPE_PEM`, `FILETYPE_ASN1`, or
  3289. `FILETYPE_TEXT` results in a `ValueError` being raised.
  3290. """
  3291. crl = CRL()
  3292. with pytest.raises(ValueError):
  3293. crl.export(self.cert, self.pkey, 100, 10, digest=b"sha256")
  3294. def test_export_unknown_digest(self):
  3295. """
  3296. Calling `OpenSSL.CRL.export` with an unsupported digest results
  3297. in a `ValueError` being raised.
  3298. """
  3299. crl = CRL()
  3300. with pytest.raises(ValueError):
  3301. crl.export(
  3302. self.cert, self.pkey, FILETYPE_PEM, 10, b"strange-digest"
  3303. )
  3304. def test_get_revoked(self):
  3305. """
  3306. Use python to create a simple CRL with two revocations. Get back the
  3307. `Revoked` using `OpenSSL.CRL.get_revoked` and verify them.
  3308. """
  3309. crl = CRL()
  3310. revoked = Revoked()
  3311. now = datetime.now().strftime("%Y%m%d%H%M%SZ").encode("ascii")
  3312. revoked.set_rev_date(now)
  3313. revoked.set_serial(b"3ab")
  3314. crl.add_revoked(revoked)
  3315. revoked.set_serial(b"100")
  3316. revoked.set_reason(b"sUpErSeDEd")
  3317. crl.add_revoked(revoked)
  3318. revs = crl.get_revoked()
  3319. assert len(revs) == 2
  3320. assert type(revs[0]) == Revoked
  3321. assert type(revs[1]) == Revoked
  3322. assert revs[0].get_serial() == b"03AB"
  3323. assert revs[1].get_serial() == b"0100"
  3324. assert revs[0].get_rev_date() == now
  3325. assert revs[1].get_rev_date() == now
  3326. def test_load_crl(self):
  3327. """
  3328. Load a known CRL and inspect its revocations. Both EM and DER formats
  3329. are loaded.
  3330. """
  3331. crl = load_crl(FILETYPE_PEM, crlData)
  3332. revs = crl.get_revoked()
  3333. assert len(revs) == 2
  3334. assert revs[0].get_serial() == b"03AB"
  3335. assert revs[0].get_reason() is None
  3336. assert revs[1].get_serial() == b"0100"
  3337. assert revs[1].get_reason() == b"Superseded"
  3338. der = _runopenssl(crlData, b"crl", b"-outform", b"DER")
  3339. crl = load_crl(FILETYPE_ASN1, der)
  3340. revs = crl.get_revoked()
  3341. assert len(revs) == 2
  3342. assert revs[0].get_serial() == b"03AB"
  3343. assert revs[0].get_reason() is None
  3344. assert revs[1].get_serial() == b"0100"
  3345. assert revs[1].get_reason() == b"Superseded"
  3346. def test_load_crl_bad_filetype(self):
  3347. """
  3348. Calling `OpenSSL.crypto.load_crl` with an unknown file type raises a
  3349. `ValueError`.
  3350. """
  3351. with pytest.raises(ValueError):
  3352. load_crl(100, crlData)
  3353. def test_load_crl_bad_data(self):
  3354. """
  3355. Calling `OpenSSL.crypto.load_crl` with file data which can't be loaded
  3356. raises a `OpenSSL.crypto.Error`.
  3357. """
  3358. with pytest.raises(Error):
  3359. load_crl(FILETYPE_PEM, b"hello, world")
  3360. def test_get_issuer(self):
  3361. """
  3362. Load a known CRL and assert its issuer's common name is what we expect
  3363. from the encoded crlData string.
  3364. """
  3365. crl = load_crl(FILETYPE_PEM, crlData)
  3366. assert isinstance(crl.get_issuer(), X509Name)
  3367. assert crl.get_issuer().CN == "Testing Root CA"
  3368. def test_dump_crl(self):
  3369. """
  3370. The dumped CRL matches the original input.
  3371. """
  3372. crl = load_crl(FILETYPE_PEM, crlData)
  3373. buf = dump_crl(FILETYPE_PEM, crl)
  3374. assert buf == crlData
  3375. def _make_test_crl(self, issuer_cert, issuer_key, certs=()):
  3376. """
  3377. Create a CRL.
  3378. :param list[X509] certs: A list of certificates to revoke.
  3379. :rtype: CRL
  3380. """
  3381. crl = CRL()
  3382. for cert in certs:
  3383. revoked = Revoked()
  3384. # FIXME: This string splicing is an unfortunate implementation
  3385. # detail that has been reported in
  3386. # https://github.com/pyca/pyopenssl/issues/258
  3387. serial = hex(cert.get_serial_number())[2:].encode("utf-8")
  3388. revoked.set_serial(serial)
  3389. revoked.set_reason(b"unspecified")
  3390. revoked.set_rev_date(b"20140601000000Z")
  3391. crl.add_revoked(revoked)
  3392. crl.set_version(1)
  3393. crl.set_lastUpdate(b"20140601000000Z")
  3394. crl.set_nextUpdate(b"20180601000000Z")
  3395. crl.sign(issuer_cert, issuer_key, digest=b"sha512")
  3396. return crl
  3397. def test_verify_with_revoked(self):
  3398. """
  3399. `verify_certificate` raises error when an intermediate certificate is
  3400. revoked.
  3401. """
  3402. store = X509Store()
  3403. store.add_cert(self.root_cert)
  3404. store.add_cert(self.intermediate_cert)
  3405. root_crl = self._make_test_crl(
  3406. self.root_cert, self.root_key, certs=[self.intermediate_cert]
  3407. )
  3408. intermediate_crl = self._make_test_crl(
  3409. self.intermediate_cert, self.intermediate_key, certs=[]
  3410. )
  3411. store.add_crl(root_crl)
  3412. store.add_crl(intermediate_crl)
  3413. store.set_flags(
  3414. X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL
  3415. )
  3416. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3417. with pytest.raises(X509StoreContextError) as err:
  3418. store_ctx.verify_certificate()
  3419. assert err.value.args[0][2] == "certificate revoked"
  3420. def test_verify_with_missing_crl(self):
  3421. """
  3422. `verify_certificate` raises error when an intermediate certificate's
  3423. CRL is missing.
  3424. """
  3425. store = X509Store()
  3426. store.add_cert(self.root_cert)
  3427. store.add_cert(self.intermediate_cert)
  3428. root_crl = self._make_test_crl(
  3429. self.root_cert, self.root_key, certs=[self.intermediate_cert]
  3430. )
  3431. store.add_crl(root_crl)
  3432. store.set_flags(
  3433. X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL
  3434. )
  3435. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3436. with pytest.raises(X509StoreContextError) as err:
  3437. store_ctx.verify_certificate()
  3438. assert err.value.args[0][2] == "unable to get certificate CRL"
  3439. assert err.value.certificate.get_subject().CN == "intermediate-service"
  3440. def test_convert_from_cryptography(self):
  3441. crypto_crl = x509.load_pem_x509_crl(crlData, backend)
  3442. crl = CRL.from_cryptography(crypto_crl)
  3443. assert isinstance(crl, CRL)
  3444. def test_convert_from_cryptography_unsupported_type(self):
  3445. with pytest.raises(TypeError):
  3446. CRL.from_cryptography(object())
  3447. def test_convert_to_cryptography_key(self):
  3448. crl = load_crl(FILETYPE_PEM, crlData)
  3449. crypto_crl = crl.to_cryptography()
  3450. assert isinstance(crypto_crl, x509.CertificateRevocationList)
  3451. class TestX509StoreContext(object):
  3452. """
  3453. Tests for `OpenSSL.crypto.X509StoreContext`.
  3454. """
  3455. root_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3456. intermediate_cert = load_certificate(FILETYPE_PEM, intermediate_cert_pem)
  3457. intermediate_server_cert = load_certificate(
  3458. FILETYPE_PEM, intermediate_server_cert_pem
  3459. )
  3460. def test_valid(self):
  3461. """
  3462. `verify_certificate` returns ``None`` when called with a certificate
  3463. and valid chain.
  3464. """
  3465. store = X509Store()
  3466. store.add_cert(self.root_cert)
  3467. store.add_cert(self.intermediate_cert)
  3468. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3469. assert store_ctx.verify_certificate() is None
  3470. def test_reuse(self):
  3471. """
  3472. `verify_certificate` can be called multiple times with the same
  3473. ``X509StoreContext`` instance to produce the same result.
  3474. """
  3475. store = X509Store()
  3476. store.add_cert(self.root_cert)
  3477. store.add_cert(self.intermediate_cert)
  3478. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3479. assert store_ctx.verify_certificate() is None
  3480. assert store_ctx.verify_certificate() is None
  3481. @pytest.mark.parametrize(
  3482. "root_cert, chain, verified_cert",
  3483. [
  3484. pytest.param(
  3485. root_cert,
  3486. [intermediate_cert],
  3487. intermediate_server_cert,
  3488. id="intermediate in chain",
  3489. ),
  3490. pytest.param(
  3491. root_cert,
  3492. [],
  3493. intermediate_cert,
  3494. id="empty chain",
  3495. ),
  3496. pytest.param(
  3497. root_cert,
  3498. [root_cert, intermediate_server_cert, intermediate_cert],
  3499. intermediate_server_cert,
  3500. id="extra certs in chain",
  3501. ),
  3502. ],
  3503. )
  3504. def test_verify_success_with_chain(self, root_cert, chain, verified_cert):
  3505. store = X509Store()
  3506. store.add_cert(root_cert)
  3507. store_ctx = X509StoreContext(store, verified_cert, chain=chain)
  3508. assert store_ctx.verify_certificate() is None
  3509. def test_valid_untrusted_chain_reuse(self):
  3510. """
  3511. `verify_certificate` using an untrusted chain can be called multiple
  3512. times with the same ``X509StoreContext`` instance to produce the same
  3513. result.
  3514. """
  3515. store = X509Store()
  3516. store.add_cert(self.root_cert)
  3517. chain = [self.intermediate_cert]
  3518. store_ctx = X509StoreContext(
  3519. store, self.intermediate_server_cert, chain=chain
  3520. )
  3521. assert store_ctx.verify_certificate() is None
  3522. assert store_ctx.verify_certificate() is None
  3523. def test_chain_reference(self):
  3524. """
  3525. ``X509StoreContext`` properly keeps references to the untrusted chain
  3526. certificates.
  3527. """
  3528. store = X509Store()
  3529. store.add_cert(self.root_cert)
  3530. chain = [load_certificate(FILETYPE_PEM, intermediate_cert_pem)]
  3531. store_ctx = X509StoreContext(
  3532. store, self.intermediate_server_cert, chain=chain
  3533. )
  3534. del chain
  3535. assert store_ctx.verify_certificate() is None
  3536. @pytest.mark.parametrize(
  3537. "root_cert, chain, verified_cert",
  3538. [
  3539. pytest.param(
  3540. root_cert,
  3541. [],
  3542. intermediate_server_cert,
  3543. id="intermediate missing",
  3544. ),
  3545. pytest.param(
  3546. None,
  3547. [intermediate_cert],
  3548. intermediate_server_cert,
  3549. id="no trusted root",
  3550. ),
  3551. pytest.param(
  3552. None,
  3553. [root_cert, intermediate_cert],
  3554. intermediate_server_cert,
  3555. id="untrusted root, full chain is available",
  3556. ),
  3557. pytest.param(
  3558. intermediate_cert,
  3559. [root_cert, intermediate_cert],
  3560. intermediate_server_cert,
  3561. id="untrusted root, intermediate is trusted and in chain",
  3562. ),
  3563. ],
  3564. )
  3565. def test_verify_fail_with_chain(self, root_cert, chain, verified_cert):
  3566. store = X509Store()
  3567. if root_cert:
  3568. store.add_cert(root_cert)
  3569. store_ctx = X509StoreContext(store, verified_cert, chain=chain)
  3570. with pytest.raises(X509StoreContextError):
  3571. store_ctx.verify_certificate()
  3572. @pytest.mark.parametrize(
  3573. "chain, expected_error",
  3574. [
  3575. pytest.param(
  3576. [intermediate_cert, "This is not a certificate"],
  3577. TypeError,
  3578. id="non-certificate in chain",
  3579. ),
  3580. pytest.param(
  3581. 42,
  3582. TypeError,
  3583. id="non-list chain",
  3584. ),
  3585. ],
  3586. )
  3587. def test_untrusted_chain_wrong_args(self, chain, expected_error):
  3588. """
  3589. Creating ``X509StoreContext`` with wrong chain raises an exception.
  3590. """
  3591. store = X509Store()
  3592. store.add_cert(self.root_cert)
  3593. with pytest.raises(expected_error):
  3594. X509StoreContext(store, self.intermediate_server_cert, chain=chain)
  3595. def test_failure_building_untrusted_chain_raises(self, monkeypatch):
  3596. """
  3597. Creating ``X509StoreContext`` raises ``OpenSSL.crypto.Error`` when
  3598. the underlying lib fails to add the certificate to the stack.
  3599. """
  3600. monkeypatch.setattr(_lib, "sk_X509_push", lambda _stack, _x509: -1)
  3601. store = X509Store()
  3602. store.add_cert(self.root_cert)
  3603. chain = [self.intermediate_cert]
  3604. with pytest.raises(Error):
  3605. X509StoreContext(store, self.intermediate_server_cert, chain=chain)
  3606. def test_trusted_self_signed(self):
  3607. """
  3608. `verify_certificate` returns ``None`` when called with a self-signed
  3609. certificate and itself in the chain.
  3610. """
  3611. store = X509Store()
  3612. store.add_cert(self.root_cert)
  3613. store_ctx = X509StoreContext(store, self.root_cert)
  3614. assert store_ctx.verify_certificate() is None
  3615. def test_untrusted_self_signed(self):
  3616. """
  3617. `verify_certificate` raises error when a self-signed certificate is
  3618. verified without itself in the chain.
  3619. """
  3620. store = X509Store()
  3621. store_ctx = X509StoreContext(store, self.root_cert)
  3622. with pytest.raises(X509StoreContextError) as exc:
  3623. store_ctx.verify_certificate()
  3624. assert exc.value.args[0][2] == "self signed certificate"
  3625. assert exc.value.certificate.get_subject().CN == "Testing Root CA"
  3626. def test_invalid_chain_no_root(self):
  3627. """
  3628. `verify_certificate` raises error when a root certificate is missing
  3629. from the chain.
  3630. """
  3631. store = X509Store()
  3632. store.add_cert(self.intermediate_cert)
  3633. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3634. with pytest.raises(X509StoreContextError) as exc:
  3635. store_ctx.verify_certificate()
  3636. assert exc.value.args[0][2] == "unable to get issuer certificate"
  3637. assert exc.value.certificate.get_subject().CN == "intermediate"
  3638. def test_invalid_chain_no_intermediate(self):
  3639. """
  3640. `verify_certificate` raises error when an intermediate certificate is
  3641. missing from the chain.
  3642. """
  3643. store = X509Store()
  3644. store.add_cert(self.root_cert)
  3645. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3646. with pytest.raises(X509StoreContextError) as exc:
  3647. store_ctx.verify_certificate()
  3648. assert exc.value.args[0][2] == "unable to get local issuer certificate"
  3649. assert exc.value.certificate.get_subject().CN == "intermediate-service"
  3650. def test_modification_pre_verify(self):
  3651. """
  3652. `verify_certificate` can use a store context modified after
  3653. instantiation.
  3654. """
  3655. store_bad = X509Store()
  3656. store_bad.add_cert(self.intermediate_cert)
  3657. store_good = X509Store()
  3658. store_good.add_cert(self.root_cert)
  3659. store_good.add_cert(self.intermediate_cert)
  3660. store_ctx = X509StoreContext(store_bad, self.intermediate_server_cert)
  3661. with pytest.raises(X509StoreContextError) as exc:
  3662. store_ctx.verify_certificate()
  3663. assert exc.value.args[0][2] == "unable to get issuer certificate"
  3664. assert exc.value.certificate.get_subject().CN == "intermediate"
  3665. store_ctx.set_store(store_good)
  3666. assert store_ctx.verify_certificate() is None
  3667. def test_verify_with_time(self):
  3668. """
  3669. `verify_certificate` raises error when the verification time is
  3670. set at notAfter.
  3671. """
  3672. store = X509Store()
  3673. store.add_cert(self.root_cert)
  3674. store.add_cert(self.intermediate_cert)
  3675. expire_time = self.intermediate_server_cert.get_notAfter()
  3676. expire_datetime = datetime.strptime(
  3677. expire_time.decode("utf-8"), "%Y%m%d%H%M%SZ"
  3678. )
  3679. store.set_time(expire_datetime)
  3680. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3681. with pytest.raises(X509StoreContextError) as exc:
  3682. store_ctx.verify_certificate()
  3683. assert exc.value.args[0][2] == "certificate has expired"
  3684. def test_get_verified_chain(self):
  3685. """
  3686. `get_verified_chain` returns the verified chain.
  3687. """
  3688. store = X509Store()
  3689. store.add_cert(self.root_cert)
  3690. store.add_cert(self.intermediate_cert)
  3691. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3692. chain = store_ctx.get_verified_chain()
  3693. assert len(chain) == 3
  3694. intermediate_subject = self.intermediate_server_cert.get_subject()
  3695. assert chain[0].get_subject() == intermediate_subject
  3696. assert chain[1].get_subject() == self.intermediate_cert.get_subject()
  3697. assert chain[2].get_subject() == self.root_cert.get_subject()
  3698. # Test reuse
  3699. chain = store_ctx.get_verified_chain()
  3700. assert len(chain) == 3
  3701. assert chain[0].get_subject() == intermediate_subject
  3702. assert chain[1].get_subject() == self.intermediate_cert.get_subject()
  3703. assert chain[2].get_subject() == self.root_cert.get_subject()
  3704. def test_get_verified_chain_invalid_chain_no_root(self):
  3705. """
  3706. `get_verified_chain` raises error when cert verification fails.
  3707. """
  3708. store = X509Store()
  3709. store.add_cert(self.intermediate_cert)
  3710. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3711. with pytest.raises(X509StoreContextError) as exc:
  3712. store_ctx.get_verified_chain()
  3713. assert exc.value.args[0][2] == "unable to get issuer certificate"
  3714. assert exc.value.certificate.get_subject().CN == "intermediate"
  3715. @pytest.fixture
  3716. def root_ca_file(self, tmpdir):
  3717. return self._create_ca_file(tmpdir, "root_ca_hash_dir", self.root_cert)
  3718. @pytest.fixture
  3719. def intermediate_ca_file(self, tmpdir):
  3720. return self._create_ca_file(
  3721. tmpdir, "intermediate_ca_hash_dir", self.intermediate_cert
  3722. )
  3723. @staticmethod
  3724. def _create_ca_file(base_path, hash_directory, cacert):
  3725. ca_hash = "{:08x}.0".format(cacert.subject_name_hash())
  3726. cafile = base_path.join(hash_directory, ca_hash)
  3727. cafile.write_binary(
  3728. dump_certificate(FILETYPE_PEM, cacert), ensure=True
  3729. )
  3730. return cafile
  3731. def test_verify_with_ca_file_location(self, root_ca_file):
  3732. store = X509Store()
  3733. store.load_locations(str(root_ca_file))
  3734. store_ctx = X509StoreContext(store, self.intermediate_cert)
  3735. store_ctx.verify_certificate()
  3736. def test_verify_with_ca_path_location(self, root_ca_file):
  3737. store = X509Store()
  3738. store.load_locations(None, str(root_ca_file.dirname))
  3739. store_ctx = X509StoreContext(store, self.intermediate_cert)
  3740. store_ctx.verify_certificate()
  3741. def test_verify_with_cafile_and_capath(
  3742. self, root_ca_file, intermediate_ca_file
  3743. ):
  3744. store = X509Store()
  3745. store.load_locations(
  3746. cafile=str(root_ca_file), capath=str(intermediate_ca_file.dirname)
  3747. )
  3748. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3749. store_ctx.verify_certificate()
  3750. def test_verify_with_multiple_ca_files(
  3751. self, root_ca_file, intermediate_ca_file
  3752. ):
  3753. store = X509Store()
  3754. store.load_locations(str(root_ca_file))
  3755. store.load_locations(str(intermediate_ca_file))
  3756. store_ctx = X509StoreContext(store, self.intermediate_server_cert)
  3757. store_ctx.verify_certificate()
  3758. def test_verify_failure_with_empty_ca_directory(self, tmpdir):
  3759. store = X509Store()
  3760. store.load_locations(None, str(tmpdir))
  3761. store_ctx = X509StoreContext(store, self.intermediate_cert)
  3762. with pytest.raises(X509StoreContextError) as exc:
  3763. store_ctx.verify_certificate()
  3764. assert exc.value.args[0][2] == "unable to get local issuer certificate"
  3765. class TestSignVerify(object):
  3766. """
  3767. Tests for `OpenSSL.crypto.sign` and `OpenSSL.crypto.verify`.
  3768. """
  3769. def test_sign_verify(self):
  3770. """
  3771. `sign` generates a cryptographic signature which `verify` can check.
  3772. """
  3773. content = (
  3774. b"It was a bright cold day in April, and the clocks were striking "
  3775. b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
  3776. b"effort to escape the vile wind, slipped quickly through the "
  3777. b"glass doors of Victory Mansions, though not quickly enough to "
  3778. b"prevent a swirl of gritty dust from entering along with him."
  3779. )
  3780. # sign the content with this private key
  3781. priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
  3782. # verify the content with this cert
  3783. good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3784. # certificate unrelated to priv_key, used to trigger an error
  3785. bad_cert = load_certificate(FILETYPE_PEM, server_cert_pem)
  3786. for digest in ["md5", "sha1"]:
  3787. sig = sign(priv_key, content, digest)
  3788. # Verify the signature of content, will throw an exception if
  3789. # error.
  3790. verify(good_cert, sig, content, digest)
  3791. # This should fail because the certificate doesn't match the
  3792. # private key that was used to sign the content.
  3793. with pytest.raises(Error):
  3794. verify(bad_cert, sig, content, digest)
  3795. # This should fail because we've "tainted" the content after
  3796. # signing it.
  3797. with pytest.raises(Error):
  3798. verify(good_cert, sig, content + b"tainted", digest)
  3799. # test that unknown digest types fail
  3800. with pytest.raises(ValueError):
  3801. sign(priv_key, content, "strange-digest")
  3802. with pytest.raises(ValueError):
  3803. verify(good_cert, sig, content, "strange-digest")
  3804. def test_sign_verify_with_text(self):
  3805. """
  3806. `sign` generates a cryptographic signature which
  3807. `verify` can check. Deprecation warnings raised because using
  3808. text instead of bytes as content
  3809. """
  3810. content = (
  3811. b"It was a bright cold day in April, and the clocks were striking "
  3812. b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
  3813. b"effort to escape the vile wind, slipped quickly through the "
  3814. b"glass doors of Victory Mansions, though not quickly enough to "
  3815. b"prevent a swirl of gritty dust from entering along with him."
  3816. ).decode("ascii")
  3817. priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
  3818. cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3819. for digest in ["md5", "sha1"]:
  3820. with pytest.warns(DeprecationWarning) as w:
  3821. simplefilter("always")
  3822. sig = sign(priv_key, content, digest)
  3823. assert "{0} for data is no longer accepted, use bytes".format(
  3824. WARNING_TYPE_EXPECTED
  3825. ) == str(w[-1].message)
  3826. with pytest.warns(DeprecationWarning) as w:
  3827. simplefilter("always")
  3828. verify(cert, sig, content, digest)
  3829. assert "{0} for data is no longer accepted, use bytes".format(
  3830. WARNING_TYPE_EXPECTED
  3831. ) == str(w[-1].message)
  3832. def test_sign_verify_ecdsa(self):
  3833. """
  3834. `sign` generates a cryptographic signature which `verify` can check.
  3835. ECDSA Signatures in the X9.62 format may have variable length,
  3836. different from the length of the private key.
  3837. """
  3838. content = (
  3839. b"It was a bright cold day in April, and the clocks were striking "
  3840. b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
  3841. b"effort to escape the vile wind, slipped quickly through the "
  3842. b"glass doors of Victory Mansions, though not quickly enough to "
  3843. b"prevent a swirl of gritty dust from entering along with him."
  3844. )
  3845. priv_key = load_privatekey(FILETYPE_PEM, ec_root_key_pem)
  3846. cert = load_certificate(FILETYPE_PEM, ec_root_cert_pem)
  3847. sig = sign(priv_key, content, "sha1")
  3848. verify(cert, sig, content, "sha1")
  3849. def test_sign_nulls(self):
  3850. """
  3851. `sign` produces a signature for a string with embedded nulls.
  3852. """
  3853. content = b"Watch out! \0 Did you see it?"
  3854. priv_key = load_privatekey(FILETYPE_PEM, root_key_pem)
  3855. good_cert = load_certificate(FILETYPE_PEM, root_cert_pem)
  3856. sig = sign(priv_key, content, "sha1")
  3857. verify(good_cert, sig, content, "sha1")
  3858. def test_sign_with_large_key(self):
  3859. """
  3860. `sign` produces a signature for a string when using a long key.
  3861. """
  3862. content = (
  3863. b"It was a bright cold day in April, and the clocks were striking "
  3864. b"thirteen. Winston Smith, his chin nuzzled into his breast in an "
  3865. b"effort to escape the vile wind, slipped quickly through the "
  3866. b"glass doors of Victory Mansions, though not quickly enough to "
  3867. b"prevent a swirl of gritty dust from entering along with him."
  3868. )
  3869. priv_key = load_privatekey(FILETYPE_PEM, large_key_pem)
  3870. sign(priv_key, content, "sha1")
  3871. class TestEllipticCurve(object):
  3872. """
  3873. Tests for `_EllipticCurve`, `get_elliptic_curve`, and
  3874. `get_elliptic_curves`.
  3875. """
  3876. def test_set(self):
  3877. """
  3878. `get_elliptic_curves` returns a `set`.
  3879. """
  3880. assert isinstance(get_elliptic_curves(), set)
  3881. def test_a_curve(self):
  3882. """
  3883. `get_elliptic_curve` can be used to retrieve a particular supported
  3884. curve.
  3885. """
  3886. curves = get_elliptic_curves()
  3887. curve = next(iter(curves))
  3888. assert curve.name == get_elliptic_curve(curve.name).name
  3889. def test_not_a_curve(self):
  3890. """
  3891. `get_elliptic_curve` raises `ValueError` if called with a name which
  3892. does not identify a supported curve.
  3893. """
  3894. with pytest.raises(ValueError):
  3895. get_elliptic_curve(u"this curve was just invented")
  3896. def test_repr(self):
  3897. """
  3898. The string representation of a curve object includes simply states the
  3899. object is a curve and what its name is.
  3900. """
  3901. curves = get_elliptic_curves()
  3902. curve = next(iter(curves))
  3903. assert "<Curve %r>" % (curve.name,) == repr(curve)
  3904. def test_to_EC_KEY(self):
  3905. """
  3906. The curve object can export a version of itself as an EC_KEY* via the
  3907. private `_EllipticCurve._to_EC_KEY`.
  3908. """
  3909. curves = get_elliptic_curves()
  3910. curve = next(iter(curves))
  3911. # It's not easy to assert anything about this object. However, see
  3912. # leakcheck/crypto.py for a test that demonstrates it at least does
  3913. # not leak memory.
  3914. curve._to_EC_KEY()
  3915. class EllipticCurveFactory(object):
  3916. """
  3917. A helper to get the names of two curves.
  3918. """
  3919. def __init__(self):
  3920. curves = iter(get_elliptic_curves())
  3921. self.curve_name = next(curves).name
  3922. self.another_curve_name = next(curves).name
  3923. class TestEllipticCurveEquality(EqualityTestsMixin):
  3924. """
  3925. Tests `_EllipticCurve`'s implementation of ``==`` and ``!=``.
  3926. """
  3927. curve_factory = EllipticCurveFactory()
  3928. if curve_factory.curve_name is None:
  3929. skip = "There are no curves available there can be no curve objects."
  3930. def anInstance(self):
  3931. """
  3932. Get the curve object for an arbitrary curve supported by the system.
  3933. """
  3934. return get_elliptic_curve(self.curve_factory.curve_name)
  3935. def anotherInstance(self):
  3936. """
  3937. Get the curve object for an arbitrary curve supported by the system -
  3938. but not the one returned by C{anInstance}.
  3939. """
  3940. return get_elliptic_curve(self.curve_factory.another_curve_name)
  3941. class TestEllipticCurveHash(object):
  3942. """
  3943. Tests for `_EllipticCurve`'s implementation of hashing (thus use as
  3944. an item in a `dict` or `set`).
  3945. """
  3946. curve_factory = EllipticCurveFactory()
  3947. if curve_factory.curve_name is None:
  3948. skip = "There are no curves available there can be no curve objects."
  3949. def test_contains(self):
  3950. """
  3951. The ``in`` operator reports that a `set` containing a curve does
  3952. contain that curve.
  3953. """
  3954. curve = get_elliptic_curve(self.curve_factory.curve_name)
  3955. curves = set([curve])
  3956. assert curve in curves
  3957. def test_does_not_contain(self):
  3958. """
  3959. The ``in`` operator reports that a `set` not containing a curve
  3960. does not contain that curve.
  3961. """
  3962. curve = get_elliptic_curve(self.curve_factory.curve_name)
  3963. curves = set(
  3964. [get_elliptic_curve(self.curve_factory.another_curve_name)]
  3965. )
  3966. assert curve not in curves