ocsp.c 198 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /*
  5. * Implementation of OCSP services, for both client and server.
  6. * (XXX, really, mostly just for client right now, but intended to do both.)
  7. */
  8. #include "prerror.h"
  9. #include "prprf.h"
  10. #include "plarena.h"
  11. #include "prnetdb.h"
  12. #include "seccomon.h"
  13. #include "secitem.h"
  14. #include "secoidt.h"
  15. #include "secasn1.h"
  16. #include "secder.h"
  17. #include "cert.h"
  18. #include "certi.h"
  19. #include "xconst.h"
  20. #include "secerr.h"
  21. #include "secoid.h"
  22. #include "hasht.h"
  23. #include "sechash.h"
  24. #include "secasn1.h"
  25. #include "plbase64.h"
  26. #include "keyhi.h"
  27. #include "cryptohi.h"
  28. #include "ocsp.h"
  29. #include "ocspti.h"
  30. #include "ocspi.h"
  31. #include "genname.h"
  32. #include "certxutl.h"
  33. #include "pk11func.h" /* for PK11_HashBuf */
  34. #include <stdarg.h>
  35. #include <plhash.h>
  36. #define DEFAULT_OCSP_CACHE_SIZE 1000
  37. #define DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 1 * 60 * 60L
  38. #define DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT 24 * 60 * 60L
  39. #define DEFAULT_OSCP_TIMEOUT_SECONDS 60
  40. #define MICROSECONDS_PER_SECOND 1000000L
  41. typedef struct OCSPCacheItemStr OCSPCacheItem;
  42. typedef struct OCSPCacheDataStr OCSPCacheData;
  43. struct OCSPCacheItemStr {
  44. /* LRU linking */
  45. OCSPCacheItem *moreRecent;
  46. OCSPCacheItem *lessRecent;
  47. /* key */
  48. CERTOCSPCertID *certID;
  49. /* CertID's arena also used to allocate "this" cache item */
  50. /* cache control information */
  51. PRTime nextFetchAttemptTime;
  52. /* Cached contents. Use a separate arena, because lifetime is different */
  53. PLArenaPool *certStatusArena; /* NULL means: no cert status cached */
  54. ocspCertStatus certStatus;
  55. /* This may contain an error code when no OCSP response is available. */
  56. SECErrorCodes missingResponseError;
  57. PRPackedBool haveThisUpdate;
  58. PRPackedBool haveNextUpdate;
  59. PRTime thisUpdate;
  60. PRTime nextUpdate;
  61. };
  62. struct OCSPCacheDataStr {
  63. PLHashTable *entries;
  64. PRUint32 numberOfEntries;
  65. OCSPCacheItem *MRUitem; /* most recently used cache item */
  66. OCSPCacheItem *LRUitem; /* least recently used cache item */
  67. };
  68. static struct OCSPGlobalStruct {
  69. PRMonitor *monitor;
  70. const SEC_HttpClientFcn *defaultHttpClientFcn;
  71. PRInt32 maxCacheEntries;
  72. PRUint32 minimumSecondsToNextFetchAttempt;
  73. PRUint32 maximumSecondsToNextFetchAttempt;
  74. PRUint32 timeoutSeconds;
  75. OCSPCacheData cache;
  76. SEC_OcspFailureMode ocspFailureMode;
  77. CERT_StringFromCertFcn alternateOCSPAIAFcn;
  78. PRBool forcePost;
  79. } OCSP_Global = { NULL,
  80. NULL,
  81. DEFAULT_OCSP_CACHE_SIZE,
  82. DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT,
  83. DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT,
  84. DEFAULT_OSCP_TIMEOUT_SECONDS,
  85. { NULL, 0, NULL, NULL },
  86. ocspMode_FailureIsVerificationFailure,
  87. NULL,
  88. PR_FALSE };
  89. /* Forward declarations */
  90. static SECItem *
  91. ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena,
  92. CERTOCSPRequest *request,
  93. const char *location,
  94. const char *method,
  95. PRTime time,
  96. PRBool addServiceLocator,
  97. void *pwArg,
  98. CERTOCSPRequest **pRequest);
  99. static SECStatus
  100. ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle,
  101. CERTOCSPCertID *certID,
  102. CERTCertificate *cert,
  103. PRTime time,
  104. void *pwArg,
  105. PRBool *certIDWasConsumed,
  106. SECStatus *rv_ocsp);
  107. static SECStatus
  108. ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle,
  109. CERTOCSPCertID *certID,
  110. CERTCertificate *cert,
  111. PRTime time,
  112. void *pwArg,
  113. const SECItem *encodedResponse,
  114. CERTOCSPResponse **pDecodedResponse,
  115. CERTOCSPSingleResponse **pSingle);
  116. static SECStatus
  117. ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time);
  118. static CERTOCSPCertID *
  119. cert_DupOCSPCertID(const CERTOCSPCertID *src);
  120. #ifndef DEBUG
  121. #define OCSP_TRACE(msg)
  122. #define OCSP_TRACE_TIME(msg, time)
  123. #define OCSP_TRACE_CERT(cert)
  124. #define OCSP_TRACE_CERTID(certid)
  125. #else
  126. #define OCSP_TRACE(msg) ocsp_Trace msg
  127. #define OCSP_TRACE_TIME(msg, time) ocsp_dumpStringWithTime(msg, time)
  128. #define OCSP_TRACE_CERT(cert) dumpCertificate(cert)
  129. #define OCSP_TRACE_CERTID(certid) dumpCertID(certid)
  130. #if defined(XP_UNIX) || defined(XP_WIN32) || defined(XP_BEOS) || \
  131. defined(XP_MACOSX)
  132. #define NSS_HAVE_GETENV 1
  133. #endif
  134. static PRBool
  135. wantOcspTrace(void)
  136. {
  137. static PRBool firstTime = PR_TRUE;
  138. static PRBool wantTrace = PR_FALSE;
  139. #ifdef NSS_HAVE_GETENV
  140. if (firstTime) {
  141. char *ev = PR_GetEnvSecure("NSS_TRACE_OCSP");
  142. if (ev && ev[0]) {
  143. wantTrace = PR_TRUE;
  144. }
  145. firstTime = PR_FALSE;
  146. }
  147. #endif
  148. return wantTrace;
  149. }
  150. static void
  151. ocsp_Trace(const char *format, ...)
  152. {
  153. char buf[2000];
  154. va_list args;
  155. if (!wantOcspTrace())
  156. return;
  157. va_start(args, format);
  158. PR_vsnprintf(buf, sizeof(buf), format, args);
  159. va_end(args);
  160. PR_LogPrint("%s", buf);
  161. }
  162. static void
  163. ocsp_dumpStringWithTime(const char *str, PRTime time)
  164. {
  165. PRExplodedTime timePrintable;
  166. char timestr[256];
  167. if (!wantOcspTrace())
  168. return;
  169. PR_ExplodeTime(time, PR_GMTParameters, &timePrintable);
  170. if (PR_FormatTime(timestr, 256, "%a %b %d %H:%M:%S %Y", &timePrintable)) {
  171. ocsp_Trace("OCSP %s %s\n", str, timestr);
  172. }
  173. }
  174. static void
  175. printHexString(const char *prefix, SECItem *hexval)
  176. {
  177. unsigned int i;
  178. char *hexbuf = NULL;
  179. for (i = 0; i < hexval->len; i++) {
  180. if (i != hexval->len - 1) {
  181. hexbuf = PR_sprintf_append(hexbuf, "%02x:", hexval->data[i]);
  182. } else {
  183. hexbuf = PR_sprintf_append(hexbuf, "%02x", hexval->data[i]);
  184. }
  185. }
  186. if (hexbuf) {
  187. ocsp_Trace("%s %s\n", prefix, hexbuf);
  188. PR_smprintf_free(hexbuf);
  189. }
  190. }
  191. static void
  192. dumpCertificate(CERTCertificate *cert)
  193. {
  194. if (!wantOcspTrace())
  195. return;
  196. ocsp_Trace("OCSP ----------------\n");
  197. ocsp_Trace("OCSP ## SUBJECT: %s\n", cert->subjectName);
  198. {
  199. PRTime timeBefore, timeAfter;
  200. PRExplodedTime beforePrintable, afterPrintable;
  201. char beforestr[256], afterstr[256];
  202. PRStatus rv1, rv2;
  203. DER_DecodeTimeChoice(&timeBefore, &cert->validity.notBefore);
  204. DER_DecodeTimeChoice(&timeAfter, &cert->validity.notAfter);
  205. PR_ExplodeTime(timeBefore, PR_GMTParameters, &beforePrintable);
  206. PR_ExplodeTime(timeAfter, PR_GMTParameters, &afterPrintable);
  207. rv1 = PR_FormatTime(beforestr, 256, "%a %b %d %H:%M:%S %Y",
  208. &beforePrintable);
  209. rv2 = PR_FormatTime(afterstr, 256, "%a %b %d %H:%M:%S %Y",
  210. &afterPrintable);
  211. ocsp_Trace("OCSP ## VALIDITY: %s to %s\n", rv1 ? beforestr : "",
  212. rv2 ? afterstr : "");
  213. }
  214. ocsp_Trace("OCSP ## ISSUER: %s\n", cert->issuerName);
  215. printHexString("OCSP ## SERIAL NUMBER:", &cert->serialNumber);
  216. }
  217. static void
  218. dumpCertID(CERTOCSPCertID *certID)
  219. {
  220. if (!wantOcspTrace())
  221. return;
  222. printHexString("OCSP certID issuer", &certID->issuerNameHash);
  223. printHexString("OCSP certID serial", &certID->serialNumber);
  224. }
  225. #endif
  226. SECStatus
  227. SEC_RegisterDefaultHttpClient(const SEC_HttpClientFcn *fcnTable)
  228. {
  229. if (!OCSP_Global.monitor) {
  230. PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  231. return SECFailure;
  232. }
  233. PR_EnterMonitor(OCSP_Global.monitor);
  234. OCSP_Global.defaultHttpClientFcn = fcnTable;
  235. PR_ExitMonitor(OCSP_Global.monitor);
  236. return SECSuccess;
  237. }
  238. SECStatus
  239. CERT_RegisterAlternateOCSPAIAInfoCallBack(
  240. CERT_StringFromCertFcn newCallback,
  241. CERT_StringFromCertFcn *oldCallback)
  242. {
  243. CERT_StringFromCertFcn old;
  244. if (!OCSP_Global.monitor) {
  245. PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  246. return SECFailure;
  247. }
  248. PR_EnterMonitor(OCSP_Global.monitor);
  249. old = OCSP_Global.alternateOCSPAIAFcn;
  250. OCSP_Global.alternateOCSPAIAFcn = newCallback;
  251. PR_ExitMonitor(OCSP_Global.monitor);
  252. if (oldCallback)
  253. *oldCallback = old;
  254. return SECSuccess;
  255. }
  256. static PLHashNumber PR_CALLBACK
  257. ocsp_CacheKeyHashFunction(const void *key)
  258. {
  259. CERTOCSPCertID *cid = (CERTOCSPCertID *)key;
  260. PLHashNumber hash = 0;
  261. unsigned int i;
  262. unsigned char *walk;
  263. /* a very simple hash calculation for the initial coding phase */
  264. walk = (unsigned char *)cid->issuerNameHash.data;
  265. for (i = 0; i < cid->issuerNameHash.len; ++i, ++walk) {
  266. hash += *walk;
  267. }
  268. walk = (unsigned char *)cid->issuerKeyHash.data;
  269. for (i = 0; i < cid->issuerKeyHash.len; ++i, ++walk) {
  270. hash += *walk;
  271. }
  272. walk = (unsigned char *)cid->serialNumber.data;
  273. for (i = 0; i < cid->serialNumber.len; ++i, ++walk) {
  274. hash += *walk;
  275. }
  276. return hash;
  277. }
  278. static PRIntn PR_CALLBACK
  279. ocsp_CacheKeyCompareFunction(const void *v1, const void *v2)
  280. {
  281. CERTOCSPCertID *cid1 = (CERTOCSPCertID *)v1;
  282. CERTOCSPCertID *cid2 = (CERTOCSPCertID *)v2;
  283. return (SECEqual == SECITEM_CompareItem(&cid1->issuerNameHash,
  284. &cid2->issuerNameHash) &&
  285. SECEqual == SECITEM_CompareItem(&cid1->issuerKeyHash,
  286. &cid2->issuerKeyHash) &&
  287. SECEqual == SECITEM_CompareItem(&cid1->serialNumber,
  288. &cid2->serialNumber));
  289. }
  290. static SECStatus
  291. ocsp_CopyRevokedInfo(PLArenaPool *arena, ocspCertStatus *dest,
  292. ocspRevokedInfo *src)
  293. {
  294. SECStatus rv = SECFailure;
  295. void *mark;
  296. mark = PORT_ArenaMark(arena);
  297. dest->certStatusInfo.revokedInfo =
  298. (ocspRevokedInfo *)PORT_ArenaZAlloc(arena, sizeof(ocspRevokedInfo));
  299. if (!dest->certStatusInfo.revokedInfo) {
  300. goto loser;
  301. }
  302. rv = SECITEM_CopyItem(arena,
  303. &dest->certStatusInfo.revokedInfo->revocationTime,
  304. &src->revocationTime);
  305. if (rv != SECSuccess) {
  306. goto loser;
  307. }
  308. if (src->revocationReason) {
  309. dest->certStatusInfo.revokedInfo->revocationReason =
  310. SECITEM_ArenaDupItem(arena, src->revocationReason);
  311. if (!dest->certStatusInfo.revokedInfo->revocationReason) {
  312. goto loser;
  313. }
  314. } else {
  315. dest->certStatusInfo.revokedInfo->revocationReason = NULL;
  316. }
  317. PORT_ArenaUnmark(arena, mark);
  318. return SECSuccess;
  319. loser:
  320. PORT_ArenaRelease(arena, mark);
  321. return SECFailure;
  322. }
  323. static SECStatus
  324. ocsp_CopyCertStatus(PLArenaPool *arena, ocspCertStatus *dest,
  325. ocspCertStatus *src)
  326. {
  327. SECStatus rv = SECFailure;
  328. dest->certStatusType = src->certStatusType;
  329. switch (src->certStatusType) {
  330. case ocspCertStatus_good:
  331. dest->certStatusInfo.goodInfo =
  332. SECITEM_ArenaDupItem(arena, src->certStatusInfo.goodInfo);
  333. if (dest->certStatusInfo.goodInfo != NULL) {
  334. rv = SECSuccess;
  335. }
  336. break;
  337. case ocspCertStatus_revoked:
  338. rv = ocsp_CopyRevokedInfo(arena, dest,
  339. src->certStatusInfo.revokedInfo);
  340. break;
  341. case ocspCertStatus_unknown:
  342. dest->certStatusInfo.unknownInfo =
  343. SECITEM_ArenaDupItem(arena, src->certStatusInfo.unknownInfo);
  344. if (dest->certStatusInfo.unknownInfo != NULL) {
  345. rv = SECSuccess;
  346. }
  347. break;
  348. case ocspCertStatus_other:
  349. default:
  350. PORT_Assert(src->certStatusType == ocspCertStatus_other);
  351. dest->certStatusInfo.otherInfo =
  352. SECITEM_ArenaDupItem(arena, src->certStatusInfo.otherInfo);
  353. if (dest->certStatusInfo.otherInfo != NULL) {
  354. rv = SECSuccess;
  355. }
  356. break;
  357. }
  358. return rv;
  359. }
  360. static void
  361. ocsp_AddCacheItemToLinkedList(OCSPCacheData *cache, OCSPCacheItem *new_most_recent)
  362. {
  363. PR_EnterMonitor(OCSP_Global.monitor);
  364. if (!cache->LRUitem) {
  365. cache->LRUitem = new_most_recent;
  366. }
  367. new_most_recent->lessRecent = cache->MRUitem;
  368. new_most_recent->moreRecent = NULL;
  369. if (cache->MRUitem) {
  370. cache->MRUitem->moreRecent = new_most_recent;
  371. }
  372. cache->MRUitem = new_most_recent;
  373. PR_ExitMonitor(OCSP_Global.monitor);
  374. }
  375. static void
  376. ocsp_RemoveCacheItemFromLinkedList(OCSPCacheData *cache, OCSPCacheItem *item)
  377. {
  378. PR_EnterMonitor(OCSP_Global.monitor);
  379. if (!item->lessRecent && !item->moreRecent) {
  380. /*
  381. * Fail gracefully on attempts to remove an item from the list,
  382. * which is currently not part of the list.
  383. * But check for the edge case it is the single entry in the list.
  384. */
  385. if (item == cache->LRUitem &&
  386. item == cache->MRUitem) {
  387. /* remove the single entry */
  388. PORT_Assert(cache->numberOfEntries == 1);
  389. PORT_Assert(item->moreRecent == NULL);
  390. cache->MRUitem = NULL;
  391. cache->LRUitem = NULL;
  392. }
  393. PR_ExitMonitor(OCSP_Global.monitor);
  394. return;
  395. }
  396. PORT_Assert(cache->numberOfEntries > 1);
  397. if (item == cache->LRUitem) {
  398. PORT_Assert(item != cache->MRUitem);
  399. PORT_Assert(item->lessRecent == NULL);
  400. PORT_Assert(item->moreRecent != NULL);
  401. PORT_Assert(item->moreRecent->lessRecent == item);
  402. cache->LRUitem = item->moreRecent;
  403. cache->LRUitem->lessRecent = NULL;
  404. } else if (item == cache->MRUitem) {
  405. PORT_Assert(item->moreRecent == NULL);
  406. PORT_Assert(item->lessRecent != NULL);
  407. PORT_Assert(item->lessRecent->moreRecent == item);
  408. cache->MRUitem = item->lessRecent;
  409. cache->MRUitem->moreRecent = NULL;
  410. } else {
  411. /* remove an entry in the middle of the list */
  412. PORT_Assert(item->moreRecent != NULL);
  413. PORT_Assert(item->lessRecent != NULL);
  414. PORT_Assert(item->lessRecent->moreRecent == item);
  415. PORT_Assert(item->moreRecent->lessRecent == item);
  416. item->moreRecent->lessRecent = item->lessRecent;
  417. item->lessRecent->moreRecent = item->moreRecent;
  418. }
  419. item->lessRecent = NULL;
  420. item->moreRecent = NULL;
  421. PR_ExitMonitor(OCSP_Global.monitor);
  422. }
  423. static void
  424. ocsp_MakeCacheEntryMostRecent(OCSPCacheData *cache, OCSPCacheItem *new_most_recent)
  425. {
  426. OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent THREADID %p\n",
  427. PR_GetCurrentThread()));
  428. PR_EnterMonitor(OCSP_Global.monitor);
  429. if (cache->MRUitem == new_most_recent) {
  430. OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent ALREADY MOST\n"));
  431. PR_ExitMonitor(OCSP_Global.monitor);
  432. return;
  433. }
  434. OCSP_TRACE(("OCSP ocsp_MakeCacheEntryMostRecent NEW entry\n"));
  435. ocsp_RemoveCacheItemFromLinkedList(cache, new_most_recent);
  436. ocsp_AddCacheItemToLinkedList(cache, new_most_recent);
  437. PR_ExitMonitor(OCSP_Global.monitor);
  438. }
  439. static PRBool
  440. ocsp_IsCacheDisabled(void)
  441. {
  442. /*
  443. * maxCacheEntries == 0 means unlimited cache entries
  444. * maxCacheEntries < 0 means cache is disabled
  445. */
  446. PRBool retval;
  447. PR_EnterMonitor(OCSP_Global.monitor);
  448. retval = (OCSP_Global.maxCacheEntries < 0);
  449. PR_ExitMonitor(OCSP_Global.monitor);
  450. return retval;
  451. }
  452. static OCSPCacheItem *
  453. ocsp_FindCacheEntry(OCSPCacheData *cache, CERTOCSPCertID *certID)
  454. {
  455. OCSPCacheItem *found_ocsp_item = NULL;
  456. OCSP_TRACE(("OCSP ocsp_FindCacheEntry\n"));
  457. OCSP_TRACE_CERTID(certID);
  458. PR_EnterMonitor(OCSP_Global.monitor);
  459. if (ocsp_IsCacheDisabled())
  460. goto loser;
  461. found_ocsp_item = (OCSPCacheItem *)PL_HashTableLookup(
  462. cache->entries, certID);
  463. if (!found_ocsp_item)
  464. goto loser;
  465. OCSP_TRACE(("OCSP ocsp_FindCacheEntry FOUND!\n"));
  466. ocsp_MakeCacheEntryMostRecent(cache, found_ocsp_item);
  467. loser:
  468. PR_ExitMonitor(OCSP_Global.monitor);
  469. return found_ocsp_item;
  470. }
  471. static void
  472. ocsp_FreeCacheItem(OCSPCacheItem *item)
  473. {
  474. OCSP_TRACE(("OCSP ocsp_FreeCacheItem\n"));
  475. if (item->certStatusArena) {
  476. PORT_FreeArena(item->certStatusArena, PR_FALSE);
  477. }
  478. if (item->certID->poolp) {
  479. /* freeing this poolp arena will also free item */
  480. PORT_FreeArena(item->certID->poolp, PR_FALSE);
  481. }
  482. }
  483. static void
  484. ocsp_RemoveCacheItem(OCSPCacheData *cache, OCSPCacheItem *item)
  485. {
  486. /* The item we're removing could be either the least recently used item,
  487. * or it could be an item that couldn't get updated with newer status info
  488. * because of an allocation failure, or it could get removed because we're
  489. * cleaning up.
  490. */
  491. OCSP_TRACE(("OCSP ocsp_RemoveCacheItem, THREADID %p\n", PR_GetCurrentThread()));
  492. PR_EnterMonitor(OCSP_Global.monitor);
  493. ocsp_RemoveCacheItemFromLinkedList(cache, item);
  494. #ifdef DEBUG
  495. {
  496. PRBool couldRemoveFromHashTable = PL_HashTableRemove(cache->entries,
  497. item->certID);
  498. PORT_Assert(couldRemoveFromHashTable);
  499. }
  500. #else
  501. PL_HashTableRemove(cache->entries, item->certID);
  502. #endif
  503. --cache->numberOfEntries;
  504. ocsp_FreeCacheItem(item);
  505. PR_ExitMonitor(OCSP_Global.monitor);
  506. }
  507. static void
  508. ocsp_CheckCacheSize(OCSPCacheData *cache)
  509. {
  510. OCSP_TRACE(("OCSP ocsp_CheckCacheSize\n"));
  511. PR_EnterMonitor(OCSP_Global.monitor);
  512. if (OCSP_Global.maxCacheEntries > 0) {
  513. /* Cache is not disabled. Number of cache entries is limited.
  514. * The monitor ensures that maxCacheEntries remains positive.
  515. */
  516. while (cache->numberOfEntries >
  517. (PRUint32)OCSP_Global.maxCacheEntries) {
  518. ocsp_RemoveCacheItem(cache, cache->LRUitem);
  519. }
  520. }
  521. PR_ExitMonitor(OCSP_Global.monitor);
  522. }
  523. SECStatus
  524. CERT_ClearOCSPCache(void)
  525. {
  526. OCSP_TRACE(("OCSP CERT_ClearOCSPCache\n"));
  527. PR_EnterMonitor(OCSP_Global.monitor);
  528. while (OCSP_Global.cache.numberOfEntries > 0) {
  529. ocsp_RemoveCacheItem(&OCSP_Global.cache,
  530. OCSP_Global.cache.LRUitem);
  531. }
  532. PR_ExitMonitor(OCSP_Global.monitor);
  533. return SECSuccess;
  534. }
  535. static SECStatus
  536. ocsp_CreateCacheItemAndConsumeCertID(OCSPCacheData *cache,
  537. CERTOCSPCertID *certID,
  538. OCSPCacheItem **pCacheItem)
  539. {
  540. PLArenaPool *arena;
  541. void *mark;
  542. PLHashEntry *new_hash_entry;
  543. OCSPCacheItem *item;
  544. PORT_Assert(pCacheItem != NULL);
  545. *pCacheItem = NULL;
  546. PR_EnterMonitor(OCSP_Global.monitor);
  547. arena = certID->poolp;
  548. mark = PORT_ArenaMark(arena);
  549. /* ZAlloc will init all Bools to False and all Pointers to NULL
  550. and all error codes to zero/good. */
  551. item = (OCSPCacheItem *)PORT_ArenaZAlloc(certID->poolp,
  552. sizeof(OCSPCacheItem));
  553. if (!item) {
  554. goto loser;
  555. }
  556. item->certID = certID;
  557. new_hash_entry = PL_HashTableAdd(cache->entries, item->certID,
  558. item);
  559. if (!new_hash_entry) {
  560. goto loser;
  561. }
  562. ++cache->numberOfEntries;
  563. PORT_ArenaUnmark(arena, mark);
  564. ocsp_AddCacheItemToLinkedList(cache, item);
  565. *pCacheItem = item;
  566. PR_ExitMonitor(OCSP_Global.monitor);
  567. return SECSuccess;
  568. loser:
  569. PORT_ArenaRelease(arena, mark);
  570. PR_ExitMonitor(OCSP_Global.monitor);
  571. return SECFailure;
  572. }
  573. static SECStatus
  574. ocsp_SetCacheItemResponse(OCSPCacheItem *item,
  575. const CERTOCSPSingleResponse *response)
  576. {
  577. if (item->certStatusArena) {
  578. PORT_FreeArena(item->certStatusArena, PR_FALSE);
  579. item->certStatusArena = NULL;
  580. }
  581. item->haveThisUpdate = item->haveNextUpdate = PR_FALSE;
  582. if (response) {
  583. SECStatus rv;
  584. item->certStatusArena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  585. if (item->certStatusArena == NULL) {
  586. return SECFailure;
  587. }
  588. rv = ocsp_CopyCertStatus(item->certStatusArena, &item->certStatus,
  589. response->certStatus);
  590. if (rv != SECSuccess) {
  591. PORT_FreeArena(item->certStatusArena, PR_FALSE);
  592. item->certStatusArena = NULL;
  593. return rv;
  594. }
  595. item->missingResponseError = 0;
  596. rv = DER_GeneralizedTimeToTime(&item->thisUpdate,
  597. &response->thisUpdate);
  598. item->haveThisUpdate = (rv == SECSuccess);
  599. if (response->nextUpdate) {
  600. rv = DER_GeneralizedTimeToTime(&item->nextUpdate,
  601. response->nextUpdate);
  602. item->haveNextUpdate = (rv == SECSuccess);
  603. } else {
  604. item->haveNextUpdate = PR_FALSE;
  605. }
  606. }
  607. return SECSuccess;
  608. }
  609. static void
  610. ocsp_FreshenCacheItemNextFetchAttemptTime(OCSPCacheItem *cacheItem)
  611. {
  612. PRTime now;
  613. PRTime earliestAllowedNextFetchAttemptTime;
  614. PRTime latestTimeWhenResponseIsConsideredFresh;
  615. OCSP_TRACE(("OCSP ocsp_FreshenCacheItemNextFetchAttemptTime\n"));
  616. PR_EnterMonitor(OCSP_Global.monitor);
  617. now = PR_Now();
  618. OCSP_TRACE_TIME("now:", now);
  619. if (cacheItem->haveThisUpdate) {
  620. OCSP_TRACE_TIME("thisUpdate:", cacheItem->thisUpdate);
  621. latestTimeWhenResponseIsConsideredFresh = cacheItem->thisUpdate +
  622. OCSP_Global.maximumSecondsToNextFetchAttempt *
  623. MICROSECONDS_PER_SECOND;
  624. OCSP_TRACE_TIME("latestTimeWhenResponseIsConsideredFresh:",
  625. latestTimeWhenResponseIsConsideredFresh);
  626. } else {
  627. latestTimeWhenResponseIsConsideredFresh = now +
  628. OCSP_Global.minimumSecondsToNextFetchAttempt *
  629. MICROSECONDS_PER_SECOND;
  630. OCSP_TRACE_TIME("no thisUpdate, "
  631. "latestTimeWhenResponseIsConsideredFresh:",
  632. latestTimeWhenResponseIsConsideredFresh);
  633. }
  634. if (cacheItem->haveNextUpdate) {
  635. OCSP_TRACE_TIME("have nextUpdate:", cacheItem->nextUpdate);
  636. }
  637. if (cacheItem->haveNextUpdate &&
  638. cacheItem->nextUpdate < latestTimeWhenResponseIsConsideredFresh) {
  639. latestTimeWhenResponseIsConsideredFresh = cacheItem->nextUpdate;
  640. OCSP_TRACE_TIME("nextUpdate is smaller than latestFresh, setting "
  641. "latestTimeWhenResponseIsConsideredFresh:",
  642. latestTimeWhenResponseIsConsideredFresh);
  643. }
  644. earliestAllowedNextFetchAttemptTime = now +
  645. OCSP_Global.minimumSecondsToNextFetchAttempt *
  646. MICROSECONDS_PER_SECOND;
  647. OCSP_TRACE_TIME("earliestAllowedNextFetchAttemptTime:",
  648. earliestAllowedNextFetchAttemptTime);
  649. if (latestTimeWhenResponseIsConsideredFresh <
  650. earliestAllowedNextFetchAttemptTime) {
  651. latestTimeWhenResponseIsConsideredFresh =
  652. earliestAllowedNextFetchAttemptTime;
  653. OCSP_TRACE_TIME("latest < earliest, setting latest to:",
  654. latestTimeWhenResponseIsConsideredFresh);
  655. }
  656. cacheItem->nextFetchAttemptTime =
  657. latestTimeWhenResponseIsConsideredFresh;
  658. OCSP_TRACE_TIME("nextFetchAttemptTime",
  659. latestTimeWhenResponseIsConsideredFresh);
  660. PR_ExitMonitor(OCSP_Global.monitor);
  661. }
  662. static PRBool
  663. ocsp_IsCacheItemFresh(OCSPCacheItem *cacheItem)
  664. {
  665. PRTime now;
  666. PRBool fresh;
  667. now = PR_Now();
  668. fresh = cacheItem->nextFetchAttemptTime > now;
  669. /* Work around broken OCSP responders that return unknown responses for
  670. * certificates, especially certificates that were just recently issued.
  671. */
  672. if (fresh && cacheItem->certStatusArena &&
  673. cacheItem->certStatus.certStatusType == ocspCertStatus_unknown) {
  674. fresh = PR_FALSE;
  675. }
  676. OCSP_TRACE(("OCSP ocsp_IsCacheItemFresh: %d\n", fresh));
  677. return fresh;
  678. }
  679. /*
  680. * Status in *certIDWasConsumed will always be correct, regardless of
  681. * return value.
  682. * If the caller is unable to transfer ownership of certID,
  683. * then the caller must set certIDWasConsumed to NULL,
  684. * and this function will potentially duplicate the certID object.
  685. */
  686. static SECStatus
  687. ocsp_CreateOrUpdateCacheEntry(OCSPCacheData *cache,
  688. CERTOCSPCertID *certID,
  689. CERTOCSPSingleResponse *single,
  690. PRBool *certIDWasConsumed)
  691. {
  692. SECStatus rv;
  693. OCSPCacheItem *cacheItem;
  694. OCSP_TRACE(("OCSP ocsp_CreateOrUpdateCacheEntry\n"));
  695. if (certIDWasConsumed)
  696. *certIDWasConsumed = PR_FALSE;
  697. PR_EnterMonitor(OCSP_Global.monitor);
  698. PORT_Assert(OCSP_Global.maxCacheEntries >= 0);
  699. cacheItem = ocsp_FindCacheEntry(cache, certID);
  700. /* Don't replace an unknown or revoked entry with an error entry, even if
  701. * the existing entry is expired. Instead, we'll continue to use the
  702. * existing (possibly expired) cache entry until we receive a valid signed
  703. * response to replace it.
  704. */
  705. if (!single && cacheItem && cacheItem->certStatusArena &&
  706. (cacheItem->certStatus.certStatusType == ocspCertStatus_revoked ||
  707. cacheItem->certStatus.certStatusType == ocspCertStatus_unknown)) {
  708. PR_ExitMonitor(OCSP_Global.monitor);
  709. return SECSuccess;
  710. }
  711. if (!cacheItem) {
  712. CERTOCSPCertID *myCertID;
  713. if (certIDWasConsumed) {
  714. myCertID = certID;
  715. *certIDWasConsumed = PR_TRUE;
  716. } else {
  717. myCertID = cert_DupOCSPCertID(certID);
  718. if (!myCertID) {
  719. PR_ExitMonitor(OCSP_Global.monitor);
  720. PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
  721. return SECFailure;
  722. }
  723. }
  724. rv = ocsp_CreateCacheItemAndConsumeCertID(cache, myCertID,
  725. &cacheItem);
  726. if (rv != SECSuccess) {
  727. PR_ExitMonitor(OCSP_Global.monitor);
  728. return rv;
  729. }
  730. }
  731. if (single) {
  732. PRTime thisUpdate;
  733. rv = DER_GeneralizedTimeToTime(&thisUpdate, &single->thisUpdate);
  734. if (!cacheItem->haveThisUpdate ||
  735. (rv == SECSuccess && cacheItem->thisUpdate < thisUpdate)) {
  736. rv = ocsp_SetCacheItemResponse(cacheItem, single);
  737. if (rv != SECSuccess) {
  738. ocsp_RemoveCacheItem(cache, cacheItem);
  739. PR_ExitMonitor(OCSP_Global.monitor);
  740. return rv;
  741. }
  742. } else {
  743. OCSP_TRACE(("Not caching response because the response is not "
  744. "newer than the cache"));
  745. }
  746. } else {
  747. cacheItem->missingResponseError = PORT_GetError();
  748. if (cacheItem->certStatusArena) {
  749. PORT_FreeArena(cacheItem->certStatusArena, PR_FALSE);
  750. cacheItem->certStatusArena = NULL;
  751. }
  752. }
  753. ocsp_FreshenCacheItemNextFetchAttemptTime(cacheItem);
  754. ocsp_CheckCacheSize(cache);
  755. PR_ExitMonitor(OCSP_Global.monitor);
  756. return SECSuccess;
  757. }
  758. extern SECStatus
  759. CERT_SetOCSPFailureMode(SEC_OcspFailureMode ocspFailureMode)
  760. {
  761. switch (ocspFailureMode) {
  762. case ocspMode_FailureIsVerificationFailure:
  763. case ocspMode_FailureIsNotAVerificationFailure:
  764. break;
  765. default:
  766. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  767. return SECFailure;
  768. }
  769. PR_EnterMonitor(OCSP_Global.monitor);
  770. OCSP_Global.ocspFailureMode = ocspFailureMode;
  771. PR_ExitMonitor(OCSP_Global.monitor);
  772. return SECSuccess;
  773. }
  774. SECStatus
  775. CERT_OCSPCacheSettings(PRInt32 maxCacheEntries,
  776. PRUint32 minimumSecondsToNextFetchAttempt,
  777. PRUint32 maximumSecondsToNextFetchAttempt)
  778. {
  779. if (minimumSecondsToNextFetchAttempt > maximumSecondsToNextFetchAttempt ||
  780. maxCacheEntries < -1) {
  781. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  782. return SECFailure;
  783. }
  784. PR_EnterMonitor(OCSP_Global.monitor);
  785. if (maxCacheEntries < 0) {
  786. OCSP_Global.maxCacheEntries = -1; /* disable cache */
  787. } else if (maxCacheEntries == 0) {
  788. OCSP_Global.maxCacheEntries = 0; /* unlimited cache entries */
  789. } else {
  790. OCSP_Global.maxCacheEntries = maxCacheEntries;
  791. }
  792. if (minimumSecondsToNextFetchAttempt <
  793. OCSP_Global.minimumSecondsToNextFetchAttempt ||
  794. maximumSecondsToNextFetchAttempt <
  795. OCSP_Global.maximumSecondsToNextFetchAttempt) {
  796. /*
  797. * Ensure our existing cache entries are not used longer than the
  798. * new settings allow, we're lazy and just clear the cache
  799. */
  800. CERT_ClearOCSPCache();
  801. }
  802. OCSP_Global.minimumSecondsToNextFetchAttempt =
  803. minimumSecondsToNextFetchAttempt;
  804. OCSP_Global.maximumSecondsToNextFetchAttempt =
  805. maximumSecondsToNextFetchAttempt;
  806. ocsp_CheckCacheSize(&OCSP_Global.cache);
  807. PR_ExitMonitor(OCSP_Global.monitor);
  808. return SECSuccess;
  809. }
  810. SECStatus
  811. CERT_SetOCSPTimeout(PRUint32 seconds)
  812. {
  813. /* no locking, see bug 406120 */
  814. OCSP_Global.timeoutSeconds = seconds;
  815. return SECSuccess;
  816. }
  817. /* this function is called at NSS initialization time */
  818. SECStatus
  819. OCSP_InitGlobal(void)
  820. {
  821. SECStatus rv = SECFailure;
  822. if (OCSP_Global.monitor == NULL) {
  823. OCSP_Global.monitor = PR_NewMonitor();
  824. }
  825. if (!OCSP_Global.monitor)
  826. return SECFailure;
  827. PR_EnterMonitor(OCSP_Global.monitor);
  828. if (!OCSP_Global.cache.entries) {
  829. OCSP_Global.cache.entries =
  830. PL_NewHashTable(0,
  831. ocsp_CacheKeyHashFunction,
  832. ocsp_CacheKeyCompareFunction,
  833. PL_CompareValues,
  834. NULL,
  835. NULL);
  836. OCSP_Global.ocspFailureMode = ocspMode_FailureIsVerificationFailure;
  837. OCSP_Global.cache.numberOfEntries = 0;
  838. OCSP_Global.cache.MRUitem = NULL;
  839. OCSP_Global.cache.LRUitem = NULL;
  840. } else {
  841. /*
  842. * NSS might call this function twice while attempting to init.
  843. * But it's not allowed to call this again after any activity.
  844. */
  845. PORT_Assert(OCSP_Global.cache.numberOfEntries == 0);
  846. PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
  847. }
  848. if (OCSP_Global.cache.entries)
  849. rv = SECSuccess;
  850. PR_ExitMonitor(OCSP_Global.monitor);
  851. return rv;
  852. }
  853. SECStatus
  854. OCSP_ShutdownGlobal(void)
  855. {
  856. if (!OCSP_Global.monitor)
  857. return SECSuccess;
  858. PR_EnterMonitor(OCSP_Global.monitor);
  859. if (OCSP_Global.cache.entries) {
  860. CERT_ClearOCSPCache();
  861. PL_HashTableDestroy(OCSP_Global.cache.entries);
  862. OCSP_Global.cache.entries = NULL;
  863. }
  864. PORT_Assert(OCSP_Global.cache.numberOfEntries == 0);
  865. OCSP_Global.cache.MRUitem = NULL;
  866. OCSP_Global.cache.LRUitem = NULL;
  867. OCSP_Global.defaultHttpClientFcn = NULL;
  868. OCSP_Global.maxCacheEntries = DEFAULT_OCSP_CACHE_SIZE;
  869. OCSP_Global.minimumSecondsToNextFetchAttempt =
  870. DEFAULT_MINIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT;
  871. OCSP_Global.maximumSecondsToNextFetchAttempt =
  872. DEFAULT_MAXIMUM_SECONDS_TO_NEXT_OCSP_FETCH_ATTEMPT;
  873. OCSP_Global.ocspFailureMode =
  874. ocspMode_FailureIsVerificationFailure;
  875. PR_ExitMonitor(OCSP_Global.monitor);
  876. PR_DestroyMonitor(OCSP_Global.monitor);
  877. OCSP_Global.monitor = NULL;
  878. return SECSuccess;
  879. }
  880. /*
  881. * A return value of NULL means:
  882. * The application did not register it's own HTTP client.
  883. */
  884. const SEC_HttpClientFcn *
  885. SEC_GetRegisteredHttpClient(void)
  886. {
  887. const SEC_HttpClientFcn *retval;
  888. if (!OCSP_Global.monitor) {
  889. PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  890. return NULL;
  891. }
  892. PR_EnterMonitor(OCSP_Global.monitor);
  893. retval = OCSP_Global.defaultHttpClientFcn;
  894. PR_ExitMonitor(OCSP_Global.monitor);
  895. return retval;
  896. }
  897. /*
  898. * The following structure is only used internally. It is allocated when
  899. * someone turns on OCSP checking, and hangs off of the status-configuration
  900. * structure in the certdb structure. We use it to keep configuration
  901. * information specific to OCSP checking.
  902. */
  903. typedef struct ocspCheckingContextStr {
  904. PRBool useDefaultResponder;
  905. char *defaultResponderURI;
  906. char *defaultResponderNickname;
  907. CERTCertificate *defaultResponderCert;
  908. } ocspCheckingContext;
  909. SEC_ASN1_MKSUB(SEC_AnyTemplate)
  910. SEC_ASN1_MKSUB(SEC_IntegerTemplate)
  911. SEC_ASN1_MKSUB(SEC_NullTemplate)
  912. SEC_ASN1_MKSUB(SEC_OctetStringTemplate)
  913. SEC_ASN1_MKSUB(SEC_PointerToAnyTemplate)
  914. SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)
  915. SEC_ASN1_MKSUB(SEC_SequenceOfAnyTemplate)
  916. SEC_ASN1_MKSUB(SEC_PointerToGeneralizedTimeTemplate)
  917. SEC_ASN1_MKSUB(SEC_PointerToEnumeratedTemplate)
  918. /*
  919. * Forward declarations of sub-types, so I can lay out the types in the
  920. * same order as the ASN.1 is laid out in the OCSP spec itself.
  921. *
  922. * These are in alphabetical order (case-insensitive); please keep it that way!
  923. */
  924. extern const SEC_ASN1Template ocsp_CertIDTemplate[];
  925. extern const SEC_ASN1Template ocsp_PointerToSignatureTemplate[];
  926. extern const SEC_ASN1Template ocsp_PointerToResponseBytesTemplate[];
  927. extern const SEC_ASN1Template ocsp_ResponseDataTemplate[];
  928. extern const SEC_ASN1Template ocsp_RevokedInfoTemplate[];
  929. extern const SEC_ASN1Template ocsp_SingleRequestTemplate[];
  930. extern const SEC_ASN1Template ocsp_SingleResponseTemplate[];
  931. extern const SEC_ASN1Template ocsp_TBSRequestTemplate[];
  932. /*
  933. * Request-related templates...
  934. */
  935. /*
  936. * OCSPRequest ::= SEQUENCE {
  937. * tbsRequest TBSRequest,
  938. * optionalSignature [0] EXPLICIT Signature OPTIONAL }
  939. */
  940. static const SEC_ASN1Template ocsp_OCSPRequestTemplate[] = {
  941. { SEC_ASN1_SEQUENCE,
  942. 0, NULL, sizeof(CERTOCSPRequest) },
  943. { SEC_ASN1_POINTER,
  944. offsetof(CERTOCSPRequest, tbsRequest),
  945. ocsp_TBSRequestTemplate },
  946. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  947. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0,
  948. offsetof(CERTOCSPRequest, optionalSignature),
  949. ocsp_PointerToSignatureTemplate },
  950. { 0 }
  951. };
  952. /*
  953. * TBSRequest ::= SEQUENCE {
  954. * version [0] EXPLICIT Version DEFAULT v1,
  955. * requestorName [1] EXPLICIT GeneralName OPTIONAL,
  956. * requestList SEQUENCE OF Request,
  957. * requestExtensions [2] EXPLICIT Extensions OPTIONAL }
  958. *
  959. * Version ::= INTEGER { v1(0) }
  960. *
  961. * Note: this should be static but the AIX compiler doesn't like it (because it
  962. * was forward-declared above); it is not meant to be exported, but this
  963. * is the only way it will compile.
  964. */
  965. const SEC_ASN1Template ocsp_TBSRequestTemplate[] = {
  966. { SEC_ASN1_SEQUENCE,
  967. 0, NULL, sizeof(ocspTBSRequest) },
  968. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */
  969. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0,
  970. offsetof(ocspTBSRequest, version),
  971. SEC_ASN1_SUB(SEC_IntegerTemplate) },
  972. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  973. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1,
  974. offsetof(ocspTBSRequest, derRequestorName),
  975. SEC_ASN1_SUB(SEC_PointerToAnyTemplate) },
  976. { SEC_ASN1_SEQUENCE_OF,
  977. offsetof(ocspTBSRequest, requestList),
  978. ocsp_SingleRequestTemplate },
  979. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  980. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 2,
  981. offsetof(ocspTBSRequest, requestExtensions),
  982. CERT_SequenceOfCertExtensionTemplate },
  983. { 0 }
  984. };
  985. /*
  986. * Signature ::= SEQUENCE {
  987. * signatureAlgorithm AlgorithmIdentifier,
  988. * signature BIT STRING,
  989. * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
  990. */
  991. static const SEC_ASN1Template ocsp_SignatureTemplate[] = {
  992. { SEC_ASN1_SEQUENCE,
  993. 0, NULL, sizeof(ocspSignature) },
  994. { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
  995. offsetof(ocspSignature, signatureAlgorithm),
  996. SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
  997. { SEC_ASN1_BIT_STRING,
  998. offsetof(ocspSignature, signature) },
  999. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1000. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0,
  1001. offsetof(ocspSignature, derCerts),
  1002. SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) },
  1003. { 0 }
  1004. };
  1005. /*
  1006. * This template is just an extra level to use in an explicitly-tagged
  1007. * reference to a Signature.
  1008. *
  1009. * Note: this should be static but the AIX compiler doesn't like it (because it
  1010. * was forward-declared above); it is not meant to be exported, but this
  1011. * is the only way it will compile.
  1012. */
  1013. const SEC_ASN1Template ocsp_PointerToSignatureTemplate[] = {
  1014. { SEC_ASN1_POINTER, 0, ocsp_SignatureTemplate }
  1015. };
  1016. /*
  1017. * Request ::= SEQUENCE {
  1018. * reqCert CertID,
  1019. * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
  1020. *
  1021. * Note: this should be static but the AIX compiler doesn't like it (because it
  1022. * was forward-declared above); it is not meant to be exported, but this
  1023. * is the only way it will compile.
  1024. */
  1025. const SEC_ASN1Template ocsp_SingleRequestTemplate[] = {
  1026. { SEC_ASN1_SEQUENCE,
  1027. 0, NULL, sizeof(ocspSingleRequest) },
  1028. { SEC_ASN1_POINTER,
  1029. offsetof(ocspSingleRequest, reqCert),
  1030. ocsp_CertIDTemplate },
  1031. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1032. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0,
  1033. offsetof(ocspSingleRequest, singleRequestExtensions),
  1034. CERT_SequenceOfCertExtensionTemplate },
  1035. { 0 }
  1036. };
  1037. /*
  1038. * This data structure and template (CertID) is used by both OCSP
  1039. * requests and responses. It is the only one that is shared.
  1040. *
  1041. * CertID ::= SEQUENCE {
  1042. * hashAlgorithm AlgorithmIdentifier,
  1043. * issuerNameHash OCTET STRING, -- Hash of Issuer DN
  1044. * issuerKeyHash OCTET STRING, -- Hash of Issuer public key
  1045. * serialNumber CertificateSerialNumber }
  1046. *
  1047. * CertificateSerialNumber ::= INTEGER
  1048. *
  1049. * Note: this should be static but the AIX compiler doesn't like it (because it
  1050. * was forward-declared above); it is not meant to be exported, but this
  1051. * is the only way it will compile.
  1052. */
  1053. const SEC_ASN1Template ocsp_CertIDTemplate[] = {
  1054. { SEC_ASN1_SEQUENCE,
  1055. 0, NULL, sizeof(CERTOCSPCertID) },
  1056. { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
  1057. offsetof(CERTOCSPCertID, hashAlgorithm),
  1058. SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
  1059. { SEC_ASN1_OCTET_STRING,
  1060. offsetof(CERTOCSPCertID, issuerNameHash) },
  1061. { SEC_ASN1_OCTET_STRING,
  1062. offsetof(CERTOCSPCertID, issuerKeyHash) },
  1063. { SEC_ASN1_INTEGER,
  1064. offsetof(CERTOCSPCertID, serialNumber) },
  1065. { 0 }
  1066. };
  1067. /*
  1068. * Response-related templates...
  1069. */
  1070. /*
  1071. * OCSPResponse ::= SEQUENCE {
  1072. * responseStatus OCSPResponseStatus,
  1073. * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
  1074. */
  1075. const SEC_ASN1Template ocsp_OCSPResponseTemplate[] = {
  1076. { SEC_ASN1_SEQUENCE,
  1077. 0, NULL, sizeof(CERTOCSPResponse) },
  1078. { SEC_ASN1_ENUMERATED,
  1079. offsetof(CERTOCSPResponse, responseStatus) },
  1080. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1081. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 0,
  1082. offsetof(CERTOCSPResponse, responseBytes),
  1083. ocsp_PointerToResponseBytesTemplate },
  1084. { 0 }
  1085. };
  1086. /*
  1087. * ResponseBytes ::= SEQUENCE {
  1088. * responseType OBJECT IDENTIFIER,
  1089. * response OCTET STRING }
  1090. */
  1091. const SEC_ASN1Template ocsp_ResponseBytesTemplate[] = {
  1092. { SEC_ASN1_SEQUENCE,
  1093. 0, NULL, sizeof(ocspResponseBytes) },
  1094. { SEC_ASN1_OBJECT_ID,
  1095. offsetof(ocspResponseBytes, responseType) },
  1096. { SEC_ASN1_OCTET_STRING,
  1097. offsetof(ocspResponseBytes, response) },
  1098. { 0 }
  1099. };
  1100. /*
  1101. * This template is just an extra level to use in an explicitly-tagged
  1102. * reference to a ResponseBytes.
  1103. *
  1104. * Note: this should be static but the AIX compiler doesn't like it (because it
  1105. * was forward-declared above); it is not meant to be exported, but this
  1106. * is the only way it will compile.
  1107. */
  1108. const SEC_ASN1Template ocsp_PointerToResponseBytesTemplate[] = {
  1109. { SEC_ASN1_POINTER, 0, ocsp_ResponseBytesTemplate }
  1110. };
  1111. /*
  1112. * BasicOCSPResponse ::= SEQUENCE {
  1113. * tbsResponseData ResponseData,
  1114. * signatureAlgorithm AlgorithmIdentifier,
  1115. * signature BIT STRING,
  1116. * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
  1117. */
  1118. static const SEC_ASN1Template ocsp_BasicOCSPResponseTemplate[] = {
  1119. { SEC_ASN1_SEQUENCE,
  1120. 0, NULL, sizeof(ocspBasicOCSPResponse) },
  1121. { SEC_ASN1_ANY | SEC_ASN1_SAVE,
  1122. offsetof(ocspBasicOCSPResponse, tbsResponseDataDER) },
  1123. { SEC_ASN1_POINTER,
  1124. offsetof(ocspBasicOCSPResponse, tbsResponseData),
  1125. ocsp_ResponseDataTemplate },
  1126. { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
  1127. offsetof(ocspBasicOCSPResponse, responseSignature.signatureAlgorithm),
  1128. SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
  1129. { SEC_ASN1_BIT_STRING,
  1130. offsetof(ocspBasicOCSPResponse, responseSignature.signature) },
  1131. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1132. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0,
  1133. offsetof(ocspBasicOCSPResponse, responseSignature.derCerts),
  1134. SEC_ASN1_SUB(SEC_SequenceOfAnyTemplate) },
  1135. { 0 }
  1136. };
  1137. /*
  1138. * ResponseData ::= SEQUENCE {
  1139. * version [0] EXPLICIT Version DEFAULT v1,
  1140. * responderID ResponderID,
  1141. * producedAt GeneralizedTime,
  1142. * responses SEQUENCE OF SingleResponse,
  1143. * responseExtensions [1] EXPLICIT Extensions OPTIONAL }
  1144. *
  1145. * Note: this should be static but the AIX compiler doesn't like it (because it
  1146. * was forward-declared above); it is not meant to be exported, but this
  1147. * is the only way it will compile.
  1148. */
  1149. const SEC_ASN1Template ocsp_ResponseDataTemplate[] = {
  1150. { SEC_ASN1_SEQUENCE,
  1151. 0, NULL, sizeof(ocspResponseData) },
  1152. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT | /* XXX DER_DEFAULT */
  1153. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0,
  1154. offsetof(ocspResponseData, version),
  1155. SEC_ASN1_SUB(SEC_IntegerTemplate) },
  1156. { SEC_ASN1_ANY,
  1157. offsetof(ocspResponseData, derResponderID) },
  1158. { SEC_ASN1_GENERALIZED_TIME,
  1159. offsetof(ocspResponseData, producedAt) },
  1160. { SEC_ASN1_SEQUENCE_OF,
  1161. offsetof(ocspResponseData, responses),
  1162. ocsp_SingleResponseTemplate },
  1163. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1164. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1,
  1165. offsetof(ocspResponseData, responseExtensions),
  1166. CERT_SequenceOfCertExtensionTemplate },
  1167. { 0 }
  1168. };
  1169. /*
  1170. * ResponderID ::= CHOICE {
  1171. * byName [1] EXPLICIT Name,
  1172. * byKey [2] EXPLICIT KeyHash }
  1173. *
  1174. * KeyHash ::= OCTET STRING -- SHA-1 hash of responder's public key
  1175. * (excluding the tag and length fields)
  1176. *
  1177. * XXX Because the ASN.1 encoder and decoder currently do not provide
  1178. * a way to automatically handle a CHOICE, we need to do it in two
  1179. * steps, looking at the type tag and feeding the exact choice back
  1180. * to the ASN.1 code. Hopefully that will change someday and this
  1181. * can all be simplified down into a single template. Anyway, for
  1182. * now we list each choice as its own template:
  1183. */
  1184. const SEC_ASN1Template ocsp_ResponderIDByNameTemplate[] = {
  1185. { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1,
  1186. offsetof(ocspResponderID, responderIDValue.name),
  1187. CERT_NameTemplate }
  1188. };
  1189. const SEC_ASN1Template ocsp_ResponderIDByKeyTemplate[] = {
  1190. { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC |
  1191. SEC_ASN1_XTRN | 2,
  1192. offsetof(ocspResponderID, responderIDValue.keyHash),
  1193. SEC_ASN1_SUB(SEC_OctetStringTemplate) }
  1194. };
  1195. static const SEC_ASN1Template ocsp_ResponderIDOtherTemplate[] = {
  1196. { SEC_ASN1_ANY,
  1197. offsetof(ocspResponderID, responderIDValue.other) }
  1198. };
  1199. /* Decode choice container, but leave x509 name object encoded */
  1200. static const SEC_ASN1Template ocsp_ResponderIDDerNameTemplate[] = {
  1201. { SEC_ASN1_EXPLICIT | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC |
  1202. SEC_ASN1_XTRN | 1,
  1203. 0, SEC_ASN1_SUB(SEC_AnyTemplate) }
  1204. };
  1205. /*
  1206. * SingleResponse ::= SEQUENCE {
  1207. * certID CertID,
  1208. * certStatus CertStatus,
  1209. * thisUpdate GeneralizedTime,
  1210. * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
  1211. * singleExtensions [1] EXPLICIT Extensions OPTIONAL }
  1212. *
  1213. * Note: this should be static but the AIX compiler doesn't like it (because it
  1214. * was forward-declared above); it is not meant to be exported, but this
  1215. * is the only way it will compile.
  1216. */
  1217. const SEC_ASN1Template ocsp_SingleResponseTemplate[] = {
  1218. { SEC_ASN1_SEQUENCE,
  1219. 0, NULL, sizeof(CERTOCSPSingleResponse) },
  1220. { SEC_ASN1_POINTER,
  1221. offsetof(CERTOCSPSingleResponse, certID),
  1222. ocsp_CertIDTemplate },
  1223. { SEC_ASN1_ANY,
  1224. offsetof(CERTOCSPSingleResponse, derCertStatus) },
  1225. { SEC_ASN1_GENERALIZED_TIME,
  1226. offsetof(CERTOCSPSingleResponse, thisUpdate) },
  1227. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1228. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0,
  1229. offsetof(CERTOCSPSingleResponse, nextUpdate),
  1230. SEC_ASN1_SUB(SEC_PointerToGeneralizedTimeTemplate) },
  1231. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1232. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1,
  1233. offsetof(CERTOCSPSingleResponse, singleExtensions),
  1234. CERT_SequenceOfCertExtensionTemplate },
  1235. { 0 }
  1236. };
  1237. /*
  1238. * CertStatus ::= CHOICE {
  1239. * good [0] IMPLICIT NULL,
  1240. * revoked [1] IMPLICIT RevokedInfo,
  1241. * unknown [2] IMPLICIT UnknownInfo }
  1242. *
  1243. * Because the ASN.1 encoder and decoder currently do not provide
  1244. * a way to automatically handle a CHOICE, we need to do it in two
  1245. * steps, looking at the type tag and feeding the exact choice back
  1246. * to the ASN.1 code. Hopefully that will change someday and this
  1247. * can all be simplified down into a single template. Anyway, for
  1248. * now we list each choice as its own template:
  1249. */
  1250. static const SEC_ASN1Template ocsp_CertStatusGoodTemplate[] = {
  1251. { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 0,
  1252. offsetof(ocspCertStatus, certStatusInfo.goodInfo),
  1253. SEC_ASN1_SUB(SEC_NullTemplate) }
  1254. };
  1255. static const SEC_ASN1Template ocsp_CertStatusRevokedTemplate[] = {
  1256. { SEC_ASN1_POINTER | SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC | 1,
  1257. offsetof(ocspCertStatus, certStatusInfo.revokedInfo),
  1258. ocsp_RevokedInfoTemplate }
  1259. };
  1260. static const SEC_ASN1Template ocsp_CertStatusUnknownTemplate[] = {
  1261. { SEC_ASN1_POINTER | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 2,
  1262. offsetof(ocspCertStatus, certStatusInfo.unknownInfo),
  1263. SEC_ASN1_SUB(SEC_NullTemplate) }
  1264. };
  1265. static const SEC_ASN1Template ocsp_CertStatusOtherTemplate[] = {
  1266. { SEC_ASN1_POINTER | SEC_ASN1_XTRN,
  1267. offsetof(ocspCertStatus, certStatusInfo.otherInfo),
  1268. SEC_ASN1_SUB(SEC_AnyTemplate) }
  1269. };
  1270. /*
  1271. * RevokedInfo ::= SEQUENCE {
  1272. * revocationTime GeneralizedTime,
  1273. * revocationReason [0] EXPLICIT CRLReason OPTIONAL }
  1274. *
  1275. * Note: this should be static but the AIX compiler doesn't like it (because it
  1276. * was forward-declared above); it is not meant to be exported, but this
  1277. * is the only way it will compile.
  1278. */
  1279. const SEC_ASN1Template ocsp_RevokedInfoTemplate[] = {
  1280. { SEC_ASN1_SEQUENCE,
  1281. 0, NULL, sizeof(ocspRevokedInfo) },
  1282. { SEC_ASN1_GENERALIZED_TIME,
  1283. offsetof(ocspRevokedInfo, revocationTime) },
  1284. { SEC_ASN1_OPTIONAL | SEC_ASN1_EXPLICIT |
  1285. SEC_ASN1_CONSTRUCTED | SEC_ASN1_CONTEXT_SPECIFIC |
  1286. SEC_ASN1_XTRN | 0,
  1287. offsetof(ocspRevokedInfo, revocationReason),
  1288. SEC_ASN1_SUB(SEC_PointerToEnumeratedTemplate) },
  1289. { 0 }
  1290. };
  1291. /*
  1292. * OCSP-specific extension templates:
  1293. */
  1294. /*
  1295. * ServiceLocator ::= SEQUENCE {
  1296. * issuer Name,
  1297. * locator AuthorityInfoAccessSyntax OPTIONAL }
  1298. */
  1299. static const SEC_ASN1Template ocsp_ServiceLocatorTemplate[] = {
  1300. { SEC_ASN1_SEQUENCE,
  1301. 0, NULL, sizeof(ocspServiceLocator) },
  1302. { SEC_ASN1_POINTER,
  1303. offsetof(ocspServiceLocator, issuer),
  1304. CERT_NameTemplate },
  1305. { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY,
  1306. offsetof(ocspServiceLocator, locator) },
  1307. { 0 }
  1308. };
  1309. /*
  1310. * REQUEST SUPPORT FUNCTIONS (encode/create/decode/destroy):
  1311. */
  1312. /*
  1313. * FUNCTION: CERT_EncodeOCSPRequest
  1314. * DER encodes an OCSP Request, possibly adding a signature as well.
  1315. * XXX Signing is not yet supported, however; see comments in code.
  1316. * INPUTS:
  1317. * PLArenaPool *arena
  1318. * The return value is allocated from here.
  1319. * If a NULL is passed in, allocation is done from the heap instead.
  1320. * CERTOCSPRequest *request
  1321. * The request to be encoded.
  1322. * void *pwArg
  1323. * Pointer to argument for password prompting, if needed. (Definitely
  1324. * not needed if not signing.)
  1325. * RETURN:
  1326. * Returns a NULL on error and a pointer to the SECItem with the
  1327. * encoded value otherwise. Any error is likely to be low-level
  1328. * (e.g. no memory).
  1329. */
  1330. SECItem *
  1331. CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request,
  1332. void *pwArg)
  1333. {
  1334. SECStatus rv;
  1335. /* XXX All of these should generate errors if they fail. */
  1336. PORT_Assert(request);
  1337. PORT_Assert(request->tbsRequest);
  1338. if (request->tbsRequest->extensionHandle != NULL) {
  1339. rv = CERT_FinishExtensions(request->tbsRequest->extensionHandle);
  1340. request->tbsRequest->extensionHandle = NULL;
  1341. if (rv != SECSuccess)
  1342. return NULL;
  1343. }
  1344. /*
  1345. * XXX When signed requests are supported and request->optionalSignature
  1346. * is not NULL:
  1347. * - need to encode tbsRequest->requestorName
  1348. * - need to encode tbsRequest
  1349. * - need to sign that encoded result (using cert in sig), filling in the
  1350. * request->optionalSignature structure with the result, the signing
  1351. * algorithm and (perhaps?) the cert (and its chain?) in derCerts
  1352. */
  1353. return SEC_ASN1EncodeItem(arena, NULL, request, ocsp_OCSPRequestTemplate);
  1354. }
  1355. /*
  1356. * FUNCTION: CERT_DecodeOCSPRequest
  1357. * Decode a DER encoded OCSP Request.
  1358. * INPUTS:
  1359. * SECItem *src
  1360. * Pointer to a SECItem holding DER encoded OCSP Request.
  1361. * RETURN:
  1362. * Returns a pointer to a CERTOCSPRequest containing the decoded request.
  1363. * On error, returns NULL. Most likely error is trouble decoding
  1364. * (SEC_ERROR_OCSP_MALFORMED_REQUEST), or low-level problem (no memory).
  1365. */
  1366. CERTOCSPRequest *
  1367. CERT_DecodeOCSPRequest(const SECItem *src)
  1368. {
  1369. PLArenaPool *arena = NULL;
  1370. SECStatus rv = SECFailure;
  1371. CERTOCSPRequest *dest = NULL;
  1372. int i;
  1373. SECItem newSrc;
  1374. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1375. if (arena == NULL) {
  1376. goto loser;
  1377. }
  1378. dest = (CERTOCSPRequest *)PORT_ArenaZAlloc(arena,
  1379. sizeof(CERTOCSPRequest));
  1380. if (dest == NULL) {
  1381. goto loser;
  1382. }
  1383. dest->arena = arena;
  1384. /* copy the DER into the arena, since Quick DER returns data that points
  1385. into the DER input, which may get freed by the caller */
  1386. rv = SECITEM_CopyItem(arena, &newSrc, src);
  1387. if (rv != SECSuccess) {
  1388. goto loser;
  1389. }
  1390. rv = SEC_QuickDERDecodeItem(arena, dest, ocsp_OCSPRequestTemplate, &newSrc);
  1391. if (rv != SECSuccess) {
  1392. if (PORT_GetError() == SEC_ERROR_BAD_DER)
  1393. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST);
  1394. goto loser;
  1395. }
  1396. /*
  1397. * XXX I would like to find a way to get rid of the necessity
  1398. * of doing this copying of the arena pointer.
  1399. */
  1400. for (i = 0; dest->tbsRequest->requestList[i] != NULL; i++) {
  1401. dest->tbsRequest->requestList[i]->arena = arena;
  1402. }
  1403. return dest;
  1404. loser:
  1405. if (arena != NULL) {
  1406. PORT_FreeArena(arena, PR_FALSE);
  1407. }
  1408. return NULL;
  1409. }
  1410. SECStatus
  1411. CERT_DestroyOCSPCertID(CERTOCSPCertID *certID)
  1412. {
  1413. if (certID && certID->poolp) {
  1414. PORT_FreeArena(certID->poolp, PR_FALSE);
  1415. return SECSuccess;
  1416. }
  1417. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1418. return SECFailure;
  1419. }
  1420. /*
  1421. * Digest data using the specified algorithm.
  1422. * The necessary storage for the digest data is allocated. If "fill" is
  1423. * non-null, the data is put there, otherwise a SECItem is allocated.
  1424. * Allocation from "arena" if it is non-null, heap otherwise. Any problem
  1425. * results in a NULL being returned (and an appropriate error set).
  1426. */
  1427. SECItem *
  1428. ocsp_DigestValue(PLArenaPool *arena, SECOidTag digestAlg,
  1429. SECItem *fill, const SECItem *src)
  1430. {
  1431. const SECHashObject *digestObject;
  1432. SECItem *result = NULL;
  1433. void *mark = NULL;
  1434. void *digestBuff = NULL;
  1435. if (arena != NULL) {
  1436. mark = PORT_ArenaMark(arena);
  1437. }
  1438. digestObject = HASH_GetHashObjectByOidTag(digestAlg);
  1439. if (digestObject == NULL) {
  1440. goto loser;
  1441. }
  1442. if (fill == NULL || fill->data == NULL) {
  1443. result = SECITEM_AllocItem(arena, fill, digestObject->length);
  1444. if (result == NULL) {
  1445. goto loser;
  1446. }
  1447. digestBuff = result->data;
  1448. } else {
  1449. if (fill->len < digestObject->length) {
  1450. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1451. goto loser;
  1452. }
  1453. digestBuff = fill->data;
  1454. }
  1455. if (PK11_HashBuf(digestAlg, digestBuff,
  1456. src->data, src->len) != SECSuccess) {
  1457. goto loser;
  1458. }
  1459. if (arena != NULL) {
  1460. PORT_ArenaUnmark(arena, mark);
  1461. }
  1462. if (result == NULL) {
  1463. result = fill;
  1464. }
  1465. return result;
  1466. loser:
  1467. if (arena != NULL) {
  1468. PORT_ArenaRelease(arena, mark);
  1469. } else {
  1470. if (result != NULL) {
  1471. SECITEM_FreeItem(result, (fill == NULL) ? PR_TRUE : PR_FALSE);
  1472. }
  1473. }
  1474. return (NULL);
  1475. }
  1476. /*
  1477. * Digest the cert's subject public key using the specified algorithm.
  1478. * The necessary storage for the digest data is allocated. If "fill" is
  1479. * non-null, the data is put there, otherwise a SECItem is allocated.
  1480. * Allocation from "arena" if it is non-null, heap otherwise. Any problem
  1481. * results in a NULL being returned (and an appropriate error set).
  1482. */
  1483. SECItem *
  1484. CERT_GetSubjectPublicKeyDigest(PLArenaPool *arena, const CERTCertificate *cert,
  1485. SECOidTag digestAlg, SECItem *fill)
  1486. {
  1487. SECItem spk;
  1488. /*
  1489. * Copy just the length and data pointer (nothing needs to be freed)
  1490. * of the subject public key so we can convert the length from bits
  1491. * to bytes, which is what the digest function expects.
  1492. */
  1493. spk = cert->subjectPublicKeyInfo.subjectPublicKey;
  1494. DER_ConvertBitString(&spk);
  1495. return ocsp_DigestValue(arena, digestAlg, fill, &spk);
  1496. }
  1497. /*
  1498. * Digest the cert's subject name using the specified algorithm.
  1499. */
  1500. SECItem *
  1501. CERT_GetSubjectNameDigest(PLArenaPool *arena, const CERTCertificate *cert,
  1502. SECOidTag digestAlg, SECItem *fill)
  1503. {
  1504. SECItem name;
  1505. /*
  1506. * Copy just the length and data pointer (nothing needs to be freed)
  1507. * of the subject name
  1508. */
  1509. name = cert->derSubject;
  1510. return ocsp_DigestValue(arena, digestAlg, fill, &name);
  1511. }
  1512. /*
  1513. * Create and fill-in a CertID. This function fills in the hash values
  1514. * (issuerNameHash and issuerKeyHash), and is hardwired to use SHA1.
  1515. * Someday it might need to be more flexible about hash algorithm, but
  1516. * for now we have no intention/need to create anything else.
  1517. *
  1518. * Error causes a null to be returned; most likely cause is trouble
  1519. * finding the certificate issuer (SEC_ERROR_UNKNOWN_ISSUER).
  1520. * Other errors are low-level problems (no memory, bad database, etc.).
  1521. */
  1522. static CERTOCSPCertID *
  1523. ocsp_CreateCertID(PLArenaPool *arena, CERTCertificate *cert, PRTime time)
  1524. {
  1525. CERTOCSPCertID *certID;
  1526. CERTCertificate *issuerCert = NULL;
  1527. void *mark = PORT_ArenaMark(arena);
  1528. SECStatus rv;
  1529. PORT_Assert(arena != NULL);
  1530. certID = PORT_ArenaZNew(arena, CERTOCSPCertID);
  1531. if (certID == NULL) {
  1532. goto loser;
  1533. }
  1534. rv = SECOID_SetAlgorithmID(arena, &certID->hashAlgorithm, SEC_OID_SHA1,
  1535. NULL);
  1536. if (rv != SECSuccess) {
  1537. goto loser;
  1538. }
  1539. issuerCert = CERT_FindCertIssuer(cert, time, certUsageAnyCA);
  1540. if (issuerCert == NULL) {
  1541. goto loser;
  1542. }
  1543. if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_SHA1,
  1544. &(certID->issuerNameHash)) == NULL) {
  1545. goto loser;
  1546. }
  1547. certID->issuerSHA1NameHash.data = certID->issuerNameHash.data;
  1548. certID->issuerSHA1NameHash.len = certID->issuerNameHash.len;
  1549. if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_MD5,
  1550. &(certID->issuerMD5NameHash)) == NULL) {
  1551. goto loser;
  1552. }
  1553. if (CERT_GetSubjectNameDigest(arena, issuerCert, SEC_OID_MD2,
  1554. &(certID->issuerMD2NameHash)) == NULL) {
  1555. goto loser;
  1556. }
  1557. if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_SHA1,
  1558. &certID->issuerKeyHash) == NULL) {
  1559. goto loser;
  1560. }
  1561. certID->issuerSHA1KeyHash.data = certID->issuerKeyHash.data;
  1562. certID->issuerSHA1KeyHash.len = certID->issuerKeyHash.len;
  1563. /* cache the other two hash algorithms as well */
  1564. if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_MD5,
  1565. &certID->issuerMD5KeyHash) == NULL) {
  1566. goto loser;
  1567. }
  1568. if (CERT_GetSubjectPublicKeyDigest(arena, issuerCert, SEC_OID_MD2,
  1569. &certID->issuerMD2KeyHash) == NULL) {
  1570. goto loser;
  1571. }
  1572. /* now we are done with issuerCert */
  1573. CERT_DestroyCertificate(issuerCert);
  1574. issuerCert = NULL;
  1575. rv = SECITEM_CopyItem(arena, &certID->serialNumber, &cert->serialNumber);
  1576. if (rv != SECSuccess) {
  1577. goto loser;
  1578. }
  1579. PORT_ArenaUnmark(arena, mark);
  1580. return certID;
  1581. loser:
  1582. if (issuerCert != NULL) {
  1583. CERT_DestroyCertificate(issuerCert);
  1584. }
  1585. PORT_ArenaRelease(arena, mark);
  1586. return NULL;
  1587. }
  1588. CERTOCSPCertID *
  1589. CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time)
  1590. {
  1591. PLArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1592. CERTOCSPCertID *certID;
  1593. PORT_Assert(arena != NULL);
  1594. if (!arena)
  1595. return NULL;
  1596. certID = ocsp_CreateCertID(arena, cert, time);
  1597. if (!certID) {
  1598. PORT_FreeArena(arena, PR_FALSE);
  1599. return NULL;
  1600. }
  1601. certID->poolp = arena;
  1602. return certID;
  1603. }
  1604. static CERTOCSPCertID *
  1605. cert_DupOCSPCertID(const CERTOCSPCertID *src)
  1606. {
  1607. CERTOCSPCertID *dest;
  1608. PLArenaPool *arena = NULL;
  1609. if (!src) {
  1610. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1611. return NULL;
  1612. }
  1613. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1614. if (!arena)
  1615. goto loser;
  1616. dest = PORT_ArenaZNew(arena, CERTOCSPCertID);
  1617. if (!dest)
  1618. goto loser;
  1619. #define DUPHELP(element) \
  1620. if (src->element.data && \
  1621. SECITEM_CopyItem(arena, &dest->element, &src->element) != \
  1622. SECSuccess) { \
  1623. goto loser; \
  1624. }
  1625. DUPHELP(hashAlgorithm.algorithm)
  1626. DUPHELP(hashAlgorithm.parameters)
  1627. DUPHELP(issuerNameHash)
  1628. DUPHELP(issuerKeyHash)
  1629. DUPHELP(serialNumber)
  1630. DUPHELP(issuerSHA1NameHash)
  1631. DUPHELP(issuerMD5NameHash)
  1632. DUPHELP(issuerMD2NameHash)
  1633. DUPHELP(issuerSHA1KeyHash)
  1634. DUPHELP(issuerMD5KeyHash)
  1635. DUPHELP(issuerMD2KeyHash)
  1636. dest->poolp = arena;
  1637. return dest;
  1638. loser:
  1639. if (arena)
  1640. PORT_FreeArena(arena, PR_FALSE);
  1641. PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
  1642. return NULL;
  1643. }
  1644. /*
  1645. * Callback to set Extensions in request object
  1646. */
  1647. void
  1648. SetSingleReqExts(void *object, CERTCertExtension **exts)
  1649. {
  1650. ocspSingleRequest *singleRequest =
  1651. (ocspSingleRequest *)object;
  1652. singleRequest->singleRequestExtensions = exts;
  1653. }
  1654. /*
  1655. * Add the Service Locator extension to the singleRequestExtensions
  1656. * for the given singleRequest.
  1657. *
  1658. * All errors are internal or low-level problems (e.g. no memory).
  1659. */
  1660. static SECStatus
  1661. ocsp_AddServiceLocatorExtension(ocspSingleRequest *singleRequest,
  1662. CERTCertificate *cert)
  1663. {
  1664. ocspServiceLocator *serviceLocator = NULL;
  1665. void *extensionHandle = NULL;
  1666. SECStatus rv = SECFailure;
  1667. serviceLocator = PORT_ZNew(ocspServiceLocator);
  1668. if (serviceLocator == NULL)
  1669. goto loser;
  1670. /*
  1671. * Normally it would be a bad idea to do a direct reference like
  1672. * this rather than allocate and copy the name *or* at least dup
  1673. * a reference of the cert. But all we need is to be able to read
  1674. * the issuer name during the encoding we are about to do, so a
  1675. * copy is just a waste of time.
  1676. */
  1677. serviceLocator->issuer = &cert->issuer;
  1678. rv = CERT_FindCertExtension(cert, SEC_OID_X509_AUTH_INFO_ACCESS,
  1679. &serviceLocator->locator);
  1680. if (rv != SECSuccess) {
  1681. if (PORT_GetError() != SEC_ERROR_EXTENSION_NOT_FOUND)
  1682. goto loser;
  1683. }
  1684. /* prepare for following loser gotos */
  1685. rv = SECFailure;
  1686. PORT_SetError(0);
  1687. extensionHandle = cert_StartExtensions(singleRequest,
  1688. singleRequest->arena, SetSingleReqExts);
  1689. if (extensionHandle == NULL)
  1690. goto loser;
  1691. rv = CERT_EncodeAndAddExtension(extensionHandle,
  1692. SEC_OID_PKIX_OCSP_SERVICE_LOCATOR,
  1693. serviceLocator, PR_FALSE,
  1694. ocsp_ServiceLocatorTemplate);
  1695. loser:
  1696. if (extensionHandle != NULL) {
  1697. /*
  1698. * Either way we have to finish out the extension context (so it gets
  1699. * freed). But careful not to override any already-set bad status.
  1700. */
  1701. SECStatus tmprv = CERT_FinishExtensions(extensionHandle);
  1702. if (rv == SECSuccess)
  1703. rv = tmprv;
  1704. }
  1705. /*
  1706. * Finally, free the serviceLocator structure itself and we are done.
  1707. */
  1708. if (serviceLocator != NULL) {
  1709. if (serviceLocator->locator.data != NULL)
  1710. SECITEM_FreeItem(&serviceLocator->locator, PR_FALSE);
  1711. PORT_Free(serviceLocator);
  1712. }
  1713. return rv;
  1714. }
  1715. /*
  1716. * Creates an array of ocspSingleRequest based on a list of certs.
  1717. * Note that the code which later compares the request list with the
  1718. * response expects this array to be in the exact same order as the
  1719. * certs are found in the list. It would be harder to change that
  1720. * order than preserve it, but since the requirement is not obvious,
  1721. * it deserves to be mentioned.
  1722. *
  1723. * Any problem causes a null return and error set:
  1724. * SEC_ERROR_UNKNOWN_ISSUER
  1725. * Other errors are low-level problems (no memory, bad database, etc.).
  1726. */
  1727. static ocspSingleRequest **
  1728. ocsp_CreateSingleRequestList(PLArenaPool *arena, CERTCertList *certList,
  1729. PRTime time, PRBool includeLocator)
  1730. {
  1731. ocspSingleRequest **requestList = NULL;
  1732. CERTCertListNode *node = NULL;
  1733. int i, count;
  1734. void *mark = PORT_ArenaMark(arena);
  1735. node = CERT_LIST_HEAD(certList);
  1736. for (count = 0; !CERT_LIST_END(node, certList); count++) {
  1737. node = CERT_LIST_NEXT(node);
  1738. }
  1739. if (count == 0)
  1740. goto loser;
  1741. requestList = PORT_ArenaNewArray(arena, ocspSingleRequest *, count + 1);
  1742. if (requestList == NULL)
  1743. goto loser;
  1744. node = CERT_LIST_HEAD(certList);
  1745. for (i = 0; !CERT_LIST_END(node, certList); i++) {
  1746. requestList[i] = PORT_ArenaZNew(arena, ocspSingleRequest);
  1747. if (requestList[i] == NULL)
  1748. goto loser;
  1749. OCSP_TRACE(("OCSP CERT_CreateOCSPRequest %s\n", node->cert->subjectName));
  1750. requestList[i]->arena = arena;
  1751. requestList[i]->reqCert = ocsp_CreateCertID(arena, node->cert, time);
  1752. if (requestList[i]->reqCert == NULL)
  1753. goto loser;
  1754. if (includeLocator == PR_TRUE) {
  1755. SECStatus rv;
  1756. rv = ocsp_AddServiceLocatorExtension(requestList[i], node->cert);
  1757. if (rv != SECSuccess)
  1758. goto loser;
  1759. }
  1760. node = CERT_LIST_NEXT(node);
  1761. }
  1762. PORT_Assert(i == count);
  1763. PORT_ArenaUnmark(arena, mark);
  1764. requestList[i] = NULL;
  1765. return requestList;
  1766. loser:
  1767. PORT_ArenaRelease(arena, mark);
  1768. return NULL;
  1769. }
  1770. static ocspSingleRequest **
  1771. ocsp_CreateRequestFromCert(PLArenaPool *arena,
  1772. CERTOCSPCertID *certID,
  1773. CERTCertificate *singleCert,
  1774. PRTime time,
  1775. PRBool includeLocator)
  1776. {
  1777. ocspSingleRequest **requestList = NULL;
  1778. void *mark = PORT_ArenaMark(arena);
  1779. PORT_Assert(certID != NULL && singleCert != NULL);
  1780. /* meaning of value 2: one entry + one end marker */
  1781. requestList = PORT_ArenaNewArray(arena, ocspSingleRequest *, 2);
  1782. if (requestList == NULL)
  1783. goto loser;
  1784. requestList[0] = PORT_ArenaZNew(arena, ocspSingleRequest);
  1785. if (requestList[0] == NULL)
  1786. goto loser;
  1787. requestList[0]->arena = arena;
  1788. /* certID will live longer than the request */
  1789. requestList[0]->reqCert = certID;
  1790. if (includeLocator == PR_TRUE) {
  1791. SECStatus rv;
  1792. rv = ocsp_AddServiceLocatorExtension(requestList[0], singleCert);
  1793. if (rv != SECSuccess)
  1794. goto loser;
  1795. }
  1796. PORT_ArenaUnmark(arena, mark);
  1797. requestList[1] = NULL;
  1798. return requestList;
  1799. loser:
  1800. PORT_ArenaRelease(arena, mark);
  1801. return NULL;
  1802. }
  1803. static CERTOCSPRequest *
  1804. ocsp_prepareEmptyOCSPRequest(void)
  1805. {
  1806. PLArenaPool *arena = NULL;
  1807. CERTOCSPRequest *request = NULL;
  1808. ocspTBSRequest *tbsRequest = NULL;
  1809. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  1810. if (arena == NULL) {
  1811. goto loser;
  1812. }
  1813. request = PORT_ArenaZNew(arena, CERTOCSPRequest);
  1814. if (request == NULL) {
  1815. goto loser;
  1816. }
  1817. request->arena = arena;
  1818. tbsRequest = PORT_ArenaZNew(arena, ocspTBSRequest);
  1819. if (tbsRequest == NULL) {
  1820. goto loser;
  1821. }
  1822. request->tbsRequest = tbsRequest;
  1823. /* version 1 is the default, so we need not fill in a version number */
  1824. return request;
  1825. loser:
  1826. if (arena != NULL) {
  1827. PORT_FreeArena(arena, PR_FALSE);
  1828. }
  1829. return NULL;
  1830. }
  1831. CERTOCSPRequest *
  1832. cert_CreateSingleCertOCSPRequest(CERTOCSPCertID *certID,
  1833. CERTCertificate *singleCert,
  1834. PRTime time,
  1835. PRBool addServiceLocator,
  1836. CERTCertificate *signerCert)
  1837. {
  1838. CERTOCSPRequest *request;
  1839. OCSP_TRACE(("OCSP cert_CreateSingleCertOCSPRequest %s\n", singleCert->subjectName));
  1840. /* XXX Support for signerCert may be implemented later,
  1841. * see also the comment in CERT_CreateOCSPRequest.
  1842. */
  1843. if (signerCert != NULL) {
  1844. PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
  1845. return NULL;
  1846. }
  1847. request = ocsp_prepareEmptyOCSPRequest();
  1848. if (!request)
  1849. return NULL;
  1850. /*
  1851. * Version 1 is the default, so we need not fill in a version number.
  1852. * Now create the list of single requests, one for each cert.
  1853. */
  1854. request->tbsRequest->requestList =
  1855. ocsp_CreateRequestFromCert(request->arena,
  1856. certID,
  1857. singleCert,
  1858. time,
  1859. addServiceLocator);
  1860. if (request->tbsRequest->requestList == NULL) {
  1861. PORT_FreeArena(request->arena, PR_FALSE);
  1862. return NULL;
  1863. }
  1864. return request;
  1865. }
  1866. /*
  1867. * FUNCTION: CERT_CreateOCSPRequest
  1868. * Creates a CERTOCSPRequest, requesting the status of the certs in
  1869. * the given list.
  1870. * INPUTS:
  1871. * CERTCertList *certList
  1872. * A list of certs for which status will be requested.
  1873. * Note that all of these certificates should have the same issuer,
  1874. * or it's expected the response will be signed by a trusted responder.
  1875. * If the certs need to be broken up into multiple requests, that
  1876. * must be handled by the caller (and thus by having multiple calls
  1877. * to this routine), who knows about where the request(s) are being
  1878. * sent and whether there are any trusted responders in place.
  1879. * PRTime time
  1880. * Indicates the time for which the certificate status is to be
  1881. * determined -- this may be used in the search for the cert's issuer
  1882. * but has no effect on the request itself.
  1883. * PRBool addServiceLocator
  1884. * If true, the Service Locator extension should be added to the
  1885. * single request(s) for each cert.
  1886. * CERTCertificate *signerCert
  1887. * If non-NULL, means sign the request using this cert. Otherwise,
  1888. * do not sign.
  1889. * XXX note that request signing is not yet supported; see comment in code
  1890. * RETURN:
  1891. * A pointer to a CERTOCSPRequest structure containing an OCSP request
  1892. * for the cert list. On error, null is returned, with an error set
  1893. * indicating the reason. This is likely SEC_ERROR_UNKNOWN_ISSUER.
  1894. * (The issuer is needed to create a request for the certificate.)
  1895. * Other errors are low-level problems (no memory, bad database, etc.).
  1896. */
  1897. CERTOCSPRequest *
  1898. CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time,
  1899. PRBool addServiceLocator,
  1900. CERTCertificate *signerCert)
  1901. {
  1902. CERTOCSPRequest *request = NULL;
  1903. if (!certList) {
  1904. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  1905. return NULL;
  1906. }
  1907. /*
  1908. * XXX When we are prepared to put signing of requests back in,
  1909. * we will need to allocate a signature
  1910. * structure for the request, fill in the "derCerts" field in it,
  1911. * save the signerCert there, as well as fill in the "requestorName"
  1912. * field of the tbsRequest.
  1913. */
  1914. if (signerCert != NULL) {
  1915. PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
  1916. return NULL;
  1917. }
  1918. request = ocsp_prepareEmptyOCSPRequest();
  1919. if (!request)
  1920. return NULL;
  1921. /*
  1922. * Now create the list of single requests, one for each cert.
  1923. */
  1924. request->tbsRequest->requestList =
  1925. ocsp_CreateSingleRequestList(request->arena,
  1926. certList,
  1927. time,
  1928. addServiceLocator);
  1929. if (request->tbsRequest->requestList == NULL) {
  1930. PORT_FreeArena(request->arena, PR_FALSE);
  1931. return NULL;
  1932. }
  1933. return request;
  1934. }
  1935. /*
  1936. * FUNCTION: CERT_AddOCSPAcceptableResponses
  1937. * Add the AcceptableResponses extension to an OCSP Request.
  1938. * INPUTS:
  1939. * CERTOCSPRequest *request
  1940. * The request to which the extension should be added.
  1941. * ...
  1942. * A list (of one or more) of SECOidTag -- each of the response types
  1943. * to be added. The last OID *must* be SEC_OID_PKIX_OCSP_BASIC_RESPONSE.
  1944. * (This marks the end of the list, and it must be specified because a
  1945. * client conforming to the OCSP standard is required to handle the basic
  1946. * response type.) The OIDs are not checked in any way.
  1947. * RETURN:
  1948. * SECSuccess if the extension is added; SECFailure if anything goes wrong.
  1949. * All errors are internal or low-level problems (e.g. no memory).
  1950. */
  1951. void
  1952. SetRequestExts(void *object, CERTCertExtension **exts)
  1953. {
  1954. CERTOCSPRequest *request = (CERTOCSPRequest *)object;
  1955. request->tbsRequest->requestExtensions = exts;
  1956. }
  1957. #if defined(__GNUC__) && !defined(NSS_NO_GCC48)
  1958. #pragma GCC diagnostic push
  1959. #pragma GCC diagnostic ignored "-Wvarargs"
  1960. #endif
  1961. SECStatus
  1962. CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request,
  1963. SECOidTag responseType0, ...)
  1964. {
  1965. void *extHandle;
  1966. va_list ap;
  1967. int i, count;
  1968. SECOidTag responseType;
  1969. SECOidData *responseOid;
  1970. SECItem **acceptableResponses = NULL;
  1971. SECStatus rv = SECFailure;
  1972. extHandle = request->tbsRequest->extensionHandle;
  1973. if (extHandle == NULL) {
  1974. extHandle = cert_StartExtensions(request, request->arena, SetRequestExts);
  1975. if (extHandle == NULL)
  1976. goto loser;
  1977. }
  1978. /* Count number of OIDS going into the extension value. */
  1979. count = 1;
  1980. if (responseType0 != SEC_OID_PKIX_OCSP_BASIC_RESPONSE) {
  1981. va_start(ap, responseType0);
  1982. do {
  1983. count++;
  1984. responseType = va_arg(ap, SECOidTag);
  1985. } while (responseType != SEC_OID_PKIX_OCSP_BASIC_RESPONSE);
  1986. va_end(ap);
  1987. }
  1988. acceptableResponses = PORT_NewArray(SECItem *, count + 1);
  1989. if (acceptableResponses == NULL)
  1990. goto loser;
  1991. i = 0;
  1992. responseOid = SECOID_FindOIDByTag(responseType0);
  1993. acceptableResponses[i++] = &(responseOid->oid);
  1994. if (count > 1) {
  1995. va_start(ap, responseType0);
  1996. for (; i < count; i++) {
  1997. responseType = va_arg(ap, SECOidTag);
  1998. responseOid = SECOID_FindOIDByTag(responseType);
  1999. acceptableResponses[i] = &(responseOid->oid);
  2000. }
  2001. va_end(ap);
  2002. }
  2003. acceptableResponses[i] = NULL;
  2004. rv = CERT_EncodeAndAddExtension(extHandle, SEC_OID_PKIX_OCSP_RESPONSE,
  2005. &acceptableResponses, PR_FALSE,
  2006. SEC_ASN1_GET(SEC_SequenceOfObjectIDTemplate));
  2007. if (rv != SECSuccess)
  2008. goto loser;
  2009. PORT_Free(acceptableResponses);
  2010. if (request->tbsRequest->extensionHandle == NULL)
  2011. request->tbsRequest->extensionHandle = extHandle;
  2012. return SECSuccess;
  2013. loser:
  2014. if (acceptableResponses != NULL)
  2015. PORT_Free(acceptableResponses);
  2016. if (extHandle != NULL)
  2017. (void)CERT_FinishExtensions(extHandle);
  2018. return rv;
  2019. }
  2020. #if defined(__GNUC__) && !defined(NSS_NO_GCC48)
  2021. #pragma GCC diagnostic pop
  2022. #endif
  2023. /*
  2024. * FUNCTION: CERT_DestroyOCSPRequest
  2025. * Frees an OCSP Request structure.
  2026. * INPUTS:
  2027. * CERTOCSPRequest *request
  2028. * Pointer to CERTOCSPRequest to be freed.
  2029. * RETURN:
  2030. * No return value; no errors.
  2031. */
  2032. void
  2033. CERT_DestroyOCSPRequest(CERTOCSPRequest *request)
  2034. {
  2035. if (request == NULL)
  2036. return;
  2037. if (request->tbsRequest != NULL) {
  2038. if (request->tbsRequest->requestorName != NULL)
  2039. CERT_DestroyGeneralNameList(request->tbsRequest->requestorName);
  2040. if (request->tbsRequest->extensionHandle != NULL)
  2041. (void)CERT_FinishExtensions(request->tbsRequest->extensionHandle);
  2042. }
  2043. if (request->optionalSignature != NULL) {
  2044. if (request->optionalSignature->cert != NULL)
  2045. CERT_DestroyCertificate(request->optionalSignature->cert);
  2046. /*
  2047. * XXX Need to free derCerts? Or do they come out of arena?
  2048. * (Currently we never fill in derCerts, which is why the
  2049. * answer is not obvious. Once we do, add any necessary code
  2050. * here and remove this comment.)
  2051. */
  2052. }
  2053. /*
  2054. * We should actually never have a request without an arena,
  2055. * but check just in case. (If there isn't one, there is not
  2056. * much we can do about it...)
  2057. */
  2058. PORT_Assert(request->arena != NULL);
  2059. if (request->arena != NULL)
  2060. PORT_FreeArena(request->arena, PR_FALSE);
  2061. }
  2062. /*
  2063. * RESPONSE SUPPORT FUNCTIONS (encode/create/decode/destroy):
  2064. */
  2065. /*
  2066. * Helper function for encoding or decoding a ResponderID -- based on the
  2067. * given type, return the associated template for that choice.
  2068. */
  2069. static const SEC_ASN1Template *
  2070. ocsp_ResponderIDTemplateByType(CERTOCSPResponderIDType responderIDType)
  2071. {
  2072. const SEC_ASN1Template *responderIDTemplate;
  2073. switch (responderIDType) {
  2074. case ocspResponderID_byName:
  2075. responderIDTemplate = ocsp_ResponderIDByNameTemplate;
  2076. break;
  2077. case ocspResponderID_byKey:
  2078. responderIDTemplate = ocsp_ResponderIDByKeyTemplate;
  2079. break;
  2080. case ocspResponderID_other:
  2081. default:
  2082. PORT_Assert(responderIDType == ocspResponderID_other);
  2083. responderIDTemplate = ocsp_ResponderIDOtherTemplate;
  2084. break;
  2085. }
  2086. return responderIDTemplate;
  2087. }
  2088. /*
  2089. * Helper function for encoding or decoding a CertStatus -- based on the
  2090. * given type, return the associated template for that choice.
  2091. */
  2092. static const SEC_ASN1Template *
  2093. ocsp_CertStatusTemplateByType(ocspCertStatusType certStatusType)
  2094. {
  2095. const SEC_ASN1Template *certStatusTemplate;
  2096. switch (certStatusType) {
  2097. case ocspCertStatus_good:
  2098. certStatusTemplate = ocsp_CertStatusGoodTemplate;
  2099. break;
  2100. case ocspCertStatus_revoked:
  2101. certStatusTemplate = ocsp_CertStatusRevokedTemplate;
  2102. break;
  2103. case ocspCertStatus_unknown:
  2104. certStatusTemplate = ocsp_CertStatusUnknownTemplate;
  2105. break;
  2106. case ocspCertStatus_other:
  2107. default:
  2108. PORT_Assert(certStatusType == ocspCertStatus_other);
  2109. certStatusTemplate = ocsp_CertStatusOtherTemplate;
  2110. break;
  2111. }
  2112. return certStatusTemplate;
  2113. }
  2114. /*
  2115. * Helper function for decoding a certStatus -- turn the actual DER tag
  2116. * into our local translation.
  2117. */
  2118. static ocspCertStatusType
  2119. ocsp_CertStatusTypeByTag(int derTag)
  2120. {
  2121. ocspCertStatusType certStatusType;
  2122. switch (derTag) {
  2123. case 0:
  2124. certStatusType = ocspCertStatus_good;
  2125. break;
  2126. case 1:
  2127. certStatusType = ocspCertStatus_revoked;
  2128. break;
  2129. case 2:
  2130. certStatusType = ocspCertStatus_unknown;
  2131. break;
  2132. default:
  2133. certStatusType = ocspCertStatus_other;
  2134. break;
  2135. }
  2136. return certStatusType;
  2137. }
  2138. /*
  2139. * Helper function for decoding SingleResponses -- they each contain
  2140. * a status which is encoded as CHOICE, which needs to be decoded "by hand".
  2141. *
  2142. * Note -- on error, this routine does not release the memory it may
  2143. * have allocated; it expects its caller to do that.
  2144. */
  2145. static SECStatus
  2146. ocsp_FinishDecodingSingleResponses(PLArenaPool *reqArena,
  2147. CERTOCSPSingleResponse **responses)
  2148. {
  2149. ocspCertStatus *certStatus;
  2150. ocspCertStatusType certStatusType;
  2151. const SEC_ASN1Template *certStatusTemplate;
  2152. int derTag;
  2153. int i;
  2154. SECStatus rv = SECFailure;
  2155. if (!reqArena) {
  2156. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  2157. return SECFailure;
  2158. }
  2159. if (responses == NULL) /* nothing to do */
  2160. return SECSuccess;
  2161. for (i = 0; responses[i] != NULL; i++) {
  2162. SECItem *newStatus;
  2163. /*
  2164. * The following assert points out internal errors (problems in
  2165. * the template definitions or in the ASN.1 decoder itself, etc.).
  2166. */
  2167. PORT_Assert(responses[i]->derCertStatus.data != NULL);
  2168. derTag = responses[i]->derCertStatus.data[0] & SEC_ASN1_TAGNUM_MASK;
  2169. certStatusType = ocsp_CertStatusTypeByTag(derTag);
  2170. certStatusTemplate = ocsp_CertStatusTemplateByType(certStatusType);
  2171. certStatus = PORT_ArenaZAlloc(reqArena, sizeof(ocspCertStatus));
  2172. if (certStatus == NULL) {
  2173. goto loser;
  2174. }
  2175. newStatus = SECITEM_ArenaDupItem(reqArena, &responses[i]->derCertStatus);
  2176. if (!newStatus) {
  2177. goto loser;
  2178. }
  2179. rv = SEC_QuickDERDecodeItem(reqArena, certStatus, certStatusTemplate,
  2180. newStatus);
  2181. if (rv != SECSuccess) {
  2182. if (PORT_GetError() == SEC_ERROR_BAD_DER)
  2183. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  2184. goto loser;
  2185. }
  2186. certStatus->certStatusType = certStatusType;
  2187. responses[i]->certStatus = certStatus;
  2188. }
  2189. return SECSuccess;
  2190. loser:
  2191. return rv;
  2192. }
  2193. /*
  2194. * Helper function for decoding a responderID -- turn the actual DER tag
  2195. * into our local translation.
  2196. */
  2197. static CERTOCSPResponderIDType
  2198. ocsp_ResponderIDTypeByTag(int derTag)
  2199. {
  2200. CERTOCSPResponderIDType responderIDType;
  2201. switch (derTag) {
  2202. case 1:
  2203. responderIDType = ocspResponderID_byName;
  2204. break;
  2205. case 2:
  2206. responderIDType = ocspResponderID_byKey;
  2207. break;
  2208. default:
  2209. responderIDType = ocspResponderID_other;
  2210. break;
  2211. }
  2212. return responderIDType;
  2213. }
  2214. /*
  2215. * Decode "src" as a BasicOCSPResponse, returning the result.
  2216. */
  2217. static ocspBasicOCSPResponse *
  2218. ocsp_DecodeBasicOCSPResponse(PLArenaPool *arena, SECItem *src)
  2219. {
  2220. void *mark;
  2221. ocspBasicOCSPResponse *basicResponse;
  2222. ocspResponseData *responseData;
  2223. ocspResponderID *responderID;
  2224. CERTOCSPResponderIDType responderIDType;
  2225. const SEC_ASN1Template *responderIDTemplate;
  2226. int derTag;
  2227. SECStatus rv;
  2228. SECItem newsrc;
  2229. mark = PORT_ArenaMark(arena);
  2230. basicResponse = PORT_ArenaZAlloc(arena, sizeof(ocspBasicOCSPResponse));
  2231. if (basicResponse == NULL) {
  2232. goto loser;
  2233. }
  2234. /* copy the DER into the arena, since Quick DER returns data that points
  2235. into the DER input, which may get freed by the caller */
  2236. rv = SECITEM_CopyItem(arena, &newsrc, src);
  2237. if (rv != SECSuccess) {
  2238. goto loser;
  2239. }
  2240. rv = SEC_QuickDERDecodeItem(arena, basicResponse,
  2241. ocsp_BasicOCSPResponseTemplate, &newsrc);
  2242. if (rv != SECSuccess) {
  2243. if (PORT_GetError() == SEC_ERROR_BAD_DER)
  2244. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  2245. goto loser;
  2246. }
  2247. responseData = basicResponse->tbsResponseData;
  2248. /*
  2249. * The following asserts point out internal errors (problems in
  2250. * the template definitions or in the ASN.1 decoder itself, etc.).
  2251. */
  2252. PORT_Assert(responseData != NULL);
  2253. PORT_Assert(responseData->derResponderID.data != NULL);
  2254. /*
  2255. * XXX Because responderID is a CHOICE, which is not currently handled
  2256. * by our ASN.1 decoder, we have to decode it "by hand".
  2257. */
  2258. derTag = responseData->derResponderID.data[0] & SEC_ASN1_TAGNUM_MASK;
  2259. responderIDType = ocsp_ResponderIDTypeByTag(derTag);
  2260. responderIDTemplate = ocsp_ResponderIDTemplateByType(responderIDType);
  2261. responderID = PORT_ArenaZAlloc(arena, sizeof(ocspResponderID));
  2262. if (responderID == NULL) {
  2263. goto loser;
  2264. }
  2265. rv = SEC_QuickDERDecodeItem(arena, responderID, responderIDTemplate,
  2266. &responseData->derResponderID);
  2267. if (rv != SECSuccess) {
  2268. if (PORT_GetError() == SEC_ERROR_BAD_DER)
  2269. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  2270. goto loser;
  2271. }
  2272. responderID->responderIDType = responderIDType;
  2273. responseData->responderID = responderID;
  2274. /*
  2275. * XXX Each SingleResponse also contains a CHOICE, which has to be
  2276. * fixed up by hand.
  2277. */
  2278. rv = ocsp_FinishDecodingSingleResponses(arena, responseData->responses);
  2279. if (rv != SECSuccess) {
  2280. goto loser;
  2281. }
  2282. PORT_ArenaUnmark(arena, mark);
  2283. return basicResponse;
  2284. loser:
  2285. PORT_ArenaRelease(arena, mark);
  2286. return NULL;
  2287. }
  2288. /*
  2289. * Decode the responseBytes based on the responseType found in "rbytes",
  2290. * leaving the resulting translated/decoded information in there as well.
  2291. */
  2292. static SECStatus
  2293. ocsp_DecodeResponseBytes(PLArenaPool *arena, ocspResponseBytes *rbytes)
  2294. {
  2295. if (rbytes == NULL) {
  2296. PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE);
  2297. return SECFailure;
  2298. }
  2299. rbytes->responseTypeTag = SECOID_FindOIDTag(&rbytes->responseType);
  2300. switch (rbytes->responseTypeTag) {
  2301. case SEC_OID_PKIX_OCSP_BASIC_RESPONSE: {
  2302. ocspBasicOCSPResponse *basicResponse;
  2303. basicResponse = ocsp_DecodeBasicOCSPResponse(arena,
  2304. &rbytes->response);
  2305. if (basicResponse == NULL)
  2306. return SECFailure;
  2307. rbytes->decodedResponse.basic = basicResponse;
  2308. } break;
  2309. /*
  2310. * Add new/future response types here.
  2311. */
  2312. default:
  2313. PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE);
  2314. return SECFailure;
  2315. }
  2316. return SECSuccess;
  2317. }
  2318. /*
  2319. * FUNCTION: CERT_DecodeOCSPResponse
  2320. * Decode a DER encoded OCSP Response.
  2321. * INPUTS:
  2322. * SECItem *src
  2323. * Pointer to a SECItem holding DER encoded OCSP Response.
  2324. * RETURN:
  2325. * Returns a pointer to a CERTOCSPResponse (the decoded OCSP Response);
  2326. * the caller is responsible for destroying it. Or NULL if error (either
  2327. * response could not be decoded (SEC_ERROR_OCSP_MALFORMED_RESPONSE),
  2328. * it was of an unexpected type (SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE),
  2329. * or a low-level or internal error occurred).
  2330. */
  2331. CERTOCSPResponse *
  2332. CERT_DecodeOCSPResponse(const SECItem *src)
  2333. {
  2334. PLArenaPool *arena = NULL;
  2335. CERTOCSPResponse *response = NULL;
  2336. SECStatus rv = SECFailure;
  2337. ocspResponseStatus sv;
  2338. SECItem newSrc;
  2339. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  2340. if (arena == NULL) {
  2341. goto loser;
  2342. }
  2343. response = (CERTOCSPResponse *)PORT_ArenaZAlloc(arena,
  2344. sizeof(CERTOCSPResponse));
  2345. if (response == NULL) {
  2346. goto loser;
  2347. }
  2348. response->arena = arena;
  2349. /* copy the DER into the arena, since Quick DER returns data that points
  2350. into the DER input, which may get freed by the caller */
  2351. rv = SECITEM_CopyItem(arena, &newSrc, src);
  2352. if (rv != SECSuccess) {
  2353. goto loser;
  2354. }
  2355. rv = SEC_QuickDERDecodeItem(arena, response, ocsp_OCSPResponseTemplate, &newSrc);
  2356. if (rv != SECSuccess) {
  2357. if (PORT_GetError() == SEC_ERROR_BAD_DER)
  2358. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  2359. goto loser;
  2360. }
  2361. sv = (ocspResponseStatus)DER_GetInteger(&response->responseStatus);
  2362. response->statusValue = sv;
  2363. if (sv != ocspResponse_successful) {
  2364. /*
  2365. * If the response status is anything but successful, then we
  2366. * are all done with decoding; the status is all there is.
  2367. */
  2368. return response;
  2369. }
  2370. /*
  2371. * A successful response contains much more information, still encoded.
  2372. * Now we need to decode that.
  2373. */
  2374. rv = ocsp_DecodeResponseBytes(arena, response->responseBytes);
  2375. if (rv != SECSuccess) {
  2376. goto loser;
  2377. }
  2378. return response;
  2379. loser:
  2380. if (arena != NULL) {
  2381. PORT_FreeArena(arena, PR_FALSE);
  2382. }
  2383. return NULL;
  2384. }
  2385. /*
  2386. * The way an OCSPResponse is defined, there are many levels to descend
  2387. * before getting to the actual response information. And along the way
  2388. * we need to check that the response *type* is recognizable, which for
  2389. * now means that it is a BasicOCSPResponse, because that is the only
  2390. * type currently defined. Rather than force all routines to perform
  2391. * a bunch of sanity checking every time they want to work on a response,
  2392. * this function isolates that and gives back the interesting part.
  2393. * Note that no copying is done, this just returns a pointer into the
  2394. * substructure of the response which is passed in.
  2395. *
  2396. * XXX This routine only works when a valid response structure is passed
  2397. * into it; this is checked with many assertions. Assuming the response
  2398. * was creating by decoding, it wouldn't make it this far without being
  2399. * okay. That is a sufficient assumption since the entire OCSP interface
  2400. * is only used internally. When this interface is officially exported,
  2401. * each assertion below will need to be followed-up with setting an error
  2402. * and returning (null).
  2403. *
  2404. * FUNCTION: ocsp_GetResponseData
  2405. * Returns ocspResponseData structure and a pointer to tbs response
  2406. * data DER from a valid ocsp response.
  2407. * INPUTS:
  2408. * CERTOCSPResponse *response
  2409. * structure of a valid ocsp response
  2410. * RETURN:
  2411. * Returns a pointer to ocspResponseData structure: decoded OCSP response
  2412. * data, and a pointer(tbsResponseDataDER) to its undecoded data DER.
  2413. */
  2414. ocspResponseData *
  2415. ocsp_GetResponseData(CERTOCSPResponse *response, SECItem **tbsResponseDataDER)
  2416. {
  2417. ocspBasicOCSPResponse *basic;
  2418. ocspResponseData *responseData;
  2419. PORT_Assert(response != NULL);
  2420. PORT_Assert(response->responseBytes != NULL);
  2421. PORT_Assert(response->responseBytes->responseTypeTag ==
  2422. SEC_OID_PKIX_OCSP_BASIC_RESPONSE);
  2423. basic = response->responseBytes->decodedResponse.basic;
  2424. PORT_Assert(basic != NULL);
  2425. responseData = basic->tbsResponseData;
  2426. PORT_Assert(responseData != NULL);
  2427. if (tbsResponseDataDER) {
  2428. *tbsResponseDataDER = &basic->tbsResponseDataDER;
  2429. PORT_Assert((*tbsResponseDataDER)->data != NULL);
  2430. PORT_Assert((*tbsResponseDataDER)->len != 0);
  2431. }
  2432. return responseData;
  2433. }
  2434. /*
  2435. * Much like the routine above, except it returns the response signature.
  2436. * Again, no copy is done.
  2437. */
  2438. ocspSignature *
  2439. ocsp_GetResponseSignature(CERTOCSPResponse *response)
  2440. {
  2441. ocspBasicOCSPResponse *basic;
  2442. PORT_Assert(response != NULL);
  2443. if (NULL == response->responseBytes) {
  2444. return NULL;
  2445. }
  2446. if (response->responseBytes->responseTypeTag !=
  2447. SEC_OID_PKIX_OCSP_BASIC_RESPONSE) {
  2448. return NULL;
  2449. }
  2450. basic = response->responseBytes->decodedResponse.basic;
  2451. PORT_Assert(basic != NULL);
  2452. return &(basic->responseSignature);
  2453. }
  2454. /*
  2455. * FUNCTION: CERT_DestroyOCSPResponse
  2456. * Frees an OCSP Response structure.
  2457. * INPUTS:
  2458. * CERTOCSPResponse *request
  2459. * Pointer to CERTOCSPResponse to be freed.
  2460. * RETURN:
  2461. * No return value; no errors.
  2462. */
  2463. void
  2464. CERT_DestroyOCSPResponse(CERTOCSPResponse *response)
  2465. {
  2466. if (response != NULL) {
  2467. ocspSignature *signature = ocsp_GetResponseSignature(response);
  2468. if (signature && signature->cert != NULL)
  2469. CERT_DestroyCertificate(signature->cert);
  2470. /*
  2471. * We should actually never have a response without an arena,
  2472. * but check just in case. (If there isn't one, there is not
  2473. * much we can do about it...)
  2474. */
  2475. PORT_Assert(response->arena != NULL);
  2476. if (response->arena != NULL) {
  2477. PORT_FreeArena(response->arena, PR_FALSE);
  2478. }
  2479. }
  2480. }
  2481. /*
  2482. * OVERALL OCSP CLIENT SUPPORT (make and send a request, verify a response):
  2483. */
  2484. /*
  2485. * Pick apart a URL, saving the important things in the passed-in pointers.
  2486. *
  2487. * We expect to find "http://<hostname>[:<port>]/[path]", though we will
  2488. * tolerate that final slash character missing, as well as beginning and
  2489. * trailing whitespace, and any-case-characters for "http". All of that
  2490. * tolerance is what complicates this routine. What we want is just to
  2491. * pick out the hostname, the port, and the path.
  2492. *
  2493. * On a successful return, the caller will need to free the output pieces
  2494. * of hostname and path, which are copies of the values found in the url.
  2495. */
  2496. static SECStatus
  2497. ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath)
  2498. {
  2499. unsigned short port = 80; /* default, in case not in url */
  2500. char *hostname = NULL;
  2501. char *path = NULL;
  2502. const char *save;
  2503. char c;
  2504. int len;
  2505. if (url == NULL)
  2506. goto loser;
  2507. /*
  2508. * Skip beginning whitespace.
  2509. */
  2510. c = *url;
  2511. while ((c == ' ' || c == '\t') && c != '\0') {
  2512. url++;
  2513. c = *url;
  2514. }
  2515. if (c == '\0')
  2516. goto loser;
  2517. /*
  2518. * Confirm, then skip, protocol. (Since we only know how to do http,
  2519. * that is all we will accept).
  2520. */
  2521. if (PORT_Strncasecmp(url, "http://", 7) != 0)
  2522. goto loser;
  2523. url += 7;
  2524. /*
  2525. * Whatever comes next is the hostname (or host IP address). We just
  2526. * save it aside and then search for its end so we can determine its
  2527. * length and copy it.
  2528. *
  2529. * XXX Note that because we treat a ':' as a terminator character
  2530. * (and below, we expect that to mean there is a port specification
  2531. * immediately following), we will not handle IPv6 addresses. That is
  2532. * apparently an acceptable limitation, for the time being. Some day,
  2533. * when there is a clear way to specify a URL with an IPv6 address that
  2534. * can be parsed unambiguously, this code should be made to do that.
  2535. */
  2536. save = url;
  2537. c = *url;
  2538. while (c != '/' && c != ':' && c != '\0' && c != ' ' && c != '\t') {
  2539. url++;
  2540. c = *url;
  2541. }
  2542. len = url - save;
  2543. hostname = PORT_Alloc(len + 1);
  2544. if (hostname == NULL)
  2545. goto loser;
  2546. PORT_Memcpy(hostname, save, len);
  2547. hostname[len] = '\0';
  2548. /*
  2549. * Now we figure out if there was a port specified or not.
  2550. * If so, we need to parse it (as a number) and skip it.
  2551. */
  2552. if (c == ':') {
  2553. url++;
  2554. port = (unsigned short)PORT_Atoi(url);
  2555. c = *url;
  2556. while (c != '/' && c != '\0' && c != ' ' && c != '\t') {
  2557. if (c < '0' || c > '9')
  2558. goto loser;
  2559. url++;
  2560. c = *url;
  2561. }
  2562. }
  2563. /*
  2564. * Last thing to find is a path. There *should* be a slash,
  2565. * if nothing else -- but if there is not we provide one.
  2566. */
  2567. if (c == '/') {
  2568. save = url;
  2569. while (c != '\0' && c != ' ' && c != '\t') {
  2570. url++;
  2571. c = *url;
  2572. }
  2573. len = url - save;
  2574. path = PORT_Alloc(len + 1);
  2575. if (path == NULL)
  2576. goto loser;
  2577. PORT_Memcpy(path, save, len);
  2578. path[len] = '\0';
  2579. } else {
  2580. path = PORT_Strdup("/");
  2581. if (path == NULL)
  2582. goto loser;
  2583. }
  2584. *pHostname = hostname;
  2585. *pPort = port;
  2586. *pPath = path;
  2587. return SECSuccess;
  2588. loser:
  2589. if (hostname != NULL)
  2590. PORT_Free(hostname);
  2591. PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION);
  2592. return SECFailure;
  2593. }
  2594. /*
  2595. * Open a socket to the specified host on the specified port, and return it.
  2596. * The host is either a hostname or an IP address.
  2597. */
  2598. static PRFileDesc *
  2599. ocsp_ConnectToHost(const char *host, PRUint16 port)
  2600. {
  2601. PRFileDesc *sock = NULL;
  2602. PRIntervalTime timeout;
  2603. PRNetAddr addr;
  2604. char *netdbbuf = NULL;
  2605. sock = PR_NewTCPSocket();
  2606. if (sock == NULL)
  2607. goto loser;
  2608. /* XXX Some day need a way to set (and get?) the following value */
  2609. timeout = PR_SecondsToInterval(30);
  2610. /*
  2611. * If the following converts an IP address string in "dot notation"
  2612. * into a PRNetAddr. If it fails, we assume that is because we do not
  2613. * have such an address, but instead a host *name*. In that case we
  2614. * then lookup the host by name. Using the NSPR function this way
  2615. * means we do not have to have our own logic for distinguishing a
  2616. * valid numerical IP address from a hostname.
  2617. */
  2618. if (PR_StringToNetAddr(host, &addr) != PR_SUCCESS) {
  2619. PRIntn hostIndex;
  2620. PRHostEnt hostEntry;
  2621. netdbbuf = PORT_Alloc(PR_NETDB_BUF_SIZE);
  2622. if (netdbbuf == NULL)
  2623. goto loser;
  2624. if (PR_GetHostByName(host, netdbbuf, PR_NETDB_BUF_SIZE,
  2625. &hostEntry) != PR_SUCCESS)
  2626. goto loser;
  2627. hostIndex = 0;
  2628. do {
  2629. hostIndex = PR_EnumerateHostEnt(hostIndex, &hostEntry, port, &addr);
  2630. if (hostIndex <= 0)
  2631. goto loser;
  2632. } while (PR_Connect(sock, &addr, timeout) != PR_SUCCESS);
  2633. PORT_Free(netdbbuf);
  2634. } else {
  2635. /*
  2636. * First put the port into the address, then connect.
  2637. */
  2638. if (PR_InitializeNetAddr(PR_IpAddrNull, port, &addr) != PR_SUCCESS)
  2639. goto loser;
  2640. if (PR_Connect(sock, &addr, timeout) != PR_SUCCESS)
  2641. goto loser;
  2642. }
  2643. return sock;
  2644. loser:
  2645. if (sock != NULL)
  2646. PR_Close(sock);
  2647. if (netdbbuf != NULL)
  2648. PORT_Free(netdbbuf);
  2649. return NULL;
  2650. }
  2651. /*
  2652. * Sends an encoded OCSP request to the server identified by "location",
  2653. * and returns the socket on which it was sent (so can listen for the reply).
  2654. * "location" is expected to be a valid URL -- an error parsing it produces
  2655. * SEC_ERROR_CERT_BAD_ACCESS_LOCATION. Other errors are likely problems
  2656. * connecting to it, or writing to it, or allocating memory, and the low-level
  2657. * errors appropriate to the problem will be set.
  2658. * if (encodedRequest == NULL)
  2659. * then location MUST already include the full request,
  2660. * including base64 and urlencode,
  2661. * and the request will be sent with GET
  2662. * if (encodedRequest != NULL)
  2663. * then the request will be sent with POST
  2664. */
  2665. static PRFileDesc *
  2666. ocsp_SendEncodedRequest(const char *location, const SECItem *encodedRequest)
  2667. {
  2668. char *hostname = NULL;
  2669. char *path = NULL;
  2670. PRUint16 port;
  2671. SECStatus rv;
  2672. PRFileDesc *sock = NULL;
  2673. PRFileDesc *returnSock = NULL;
  2674. char *header = NULL;
  2675. char portstr[16];
  2676. /*
  2677. * Take apart the location, getting the hostname, port, and path.
  2678. */
  2679. rv = ocsp_ParseURL(location, &hostname, &port, &path);
  2680. if (rv != SECSuccess)
  2681. goto loser;
  2682. PORT_Assert(hostname != NULL);
  2683. PORT_Assert(path != NULL);
  2684. sock = ocsp_ConnectToHost(hostname, port);
  2685. if (sock == NULL)
  2686. goto loser;
  2687. portstr[0] = '\0';
  2688. if (port != 80) {
  2689. PR_snprintf(portstr, sizeof(portstr), ":%d", port);
  2690. }
  2691. if (!encodedRequest) {
  2692. header = PR_smprintf("GET %s HTTP/1.0\r\n"
  2693. "Host: %s%s\r\n\r\n",
  2694. path, hostname, portstr);
  2695. if (header == NULL)
  2696. goto loser;
  2697. /*
  2698. * The NSPR documentation promises that if it can, it will write the full
  2699. * amount; this will not return a partial value expecting us to loop.
  2700. */
  2701. if (PR_Write(sock, header, (PRInt32)PORT_Strlen(header)) < 0)
  2702. goto loser;
  2703. } else {
  2704. header = PR_smprintf("POST %s HTTP/1.0\r\n"
  2705. "Host: %s%s\r\n"
  2706. "Content-Type: application/ocsp-request\r\n"
  2707. "Content-Length: %u\r\n\r\n",
  2708. path, hostname, portstr, encodedRequest->len);
  2709. if (header == NULL)
  2710. goto loser;
  2711. /*
  2712. * The NSPR documentation promises that if it can, it will write the full
  2713. * amount; this will not return a partial value expecting us to loop.
  2714. */
  2715. if (PR_Write(sock, header, (PRInt32)PORT_Strlen(header)) < 0)
  2716. goto loser;
  2717. if (PR_Write(sock, encodedRequest->data,
  2718. (PRInt32)encodedRequest->len) < 0)
  2719. goto loser;
  2720. }
  2721. returnSock = sock;
  2722. sock = NULL;
  2723. loser:
  2724. if (header != NULL)
  2725. PORT_Free(header);
  2726. if (sock != NULL)
  2727. PR_Close(sock);
  2728. if (path != NULL)
  2729. PORT_Free(path);
  2730. if (hostname != NULL)
  2731. PORT_Free(hostname);
  2732. return returnSock;
  2733. }
  2734. /*
  2735. * Read from "fd" into "buf" -- expect/attempt to read a given number of bytes
  2736. * Obviously, stop if hit end-of-stream. Timeout is passed in.
  2737. */
  2738. static int
  2739. ocsp_read(PRFileDesc *fd, char *buf, int toread, PRIntervalTime timeout)
  2740. {
  2741. int total = 0;
  2742. while (total < toread) {
  2743. PRInt32 got;
  2744. got = PR_Recv(fd, buf + total, (PRInt32)(toread - total), 0, timeout);
  2745. if (got < 0) {
  2746. if (0 == total) {
  2747. total = -1; /* report the error if we didn't read anything yet */
  2748. }
  2749. break;
  2750. } else if (got == 0) { /* EOS */
  2751. break;
  2752. }
  2753. total += got;
  2754. }
  2755. return total;
  2756. }
  2757. #define OCSP_BUFSIZE 1024
  2758. #define AbortHttpDecode(error) \
  2759. { \
  2760. if (inBuffer) \
  2761. PORT_Free(inBuffer); \
  2762. PORT_SetError(error); \
  2763. return NULL; \
  2764. }
  2765. /*
  2766. * Reads on the given socket and returns an encoded response when received.
  2767. * Properly formatted HTTP/1.0 response headers are expected to be read
  2768. * from the socket, preceding a binary-encoded OCSP response. Problems
  2769. * with parsing cause the error SEC_ERROR_OCSP_BAD_HTTP_RESPONSE to be
  2770. * set; any other problems are likely low-level i/o or memory allocation
  2771. * errors.
  2772. */
  2773. static SECItem *
  2774. ocsp_GetEncodedResponse(PLArenaPool *arena, PRFileDesc *sock)
  2775. {
  2776. /* first read HTTP status line and headers */
  2777. char *inBuffer = NULL;
  2778. PRInt32 offset = 0;
  2779. PRInt32 inBufsize = 0;
  2780. const PRInt32 bufSizeIncrement = OCSP_BUFSIZE; /* 1 KB at a time */
  2781. const PRInt32 maxBufSize = 8 * bufSizeIncrement; /* 8 KB max */
  2782. const char *CRLF = "\r\n";
  2783. const PRInt32 CRLFlen = strlen(CRLF);
  2784. const char *headerEndMark = "\r\n\r\n";
  2785. const PRInt32 markLen = strlen(headerEndMark);
  2786. const PRIntervalTime ocsptimeout =
  2787. PR_SecondsToInterval(30); /* hardcoded to 30s for now */
  2788. char *headerEnd = NULL;
  2789. PRBool EOS = PR_FALSE;
  2790. const char *httpprotocol = "HTTP/";
  2791. const PRInt32 httplen = strlen(httpprotocol);
  2792. const char *httpcode = NULL;
  2793. const char *contenttype = NULL;
  2794. PRInt32 contentlength = 0;
  2795. PRInt32 bytesRead = 0;
  2796. char *statusLineEnd = NULL;
  2797. char *space = NULL;
  2798. char *nextHeader = NULL;
  2799. SECItem *result = NULL;
  2800. /* read up to at least the end of the HTTP headers */
  2801. do {
  2802. inBufsize += bufSizeIncrement;
  2803. inBuffer = PORT_Realloc(inBuffer, inBufsize + 1);
  2804. if (NULL == inBuffer) {
  2805. AbortHttpDecode(SEC_ERROR_NO_MEMORY);
  2806. }
  2807. bytesRead = ocsp_read(sock, inBuffer + offset, bufSizeIncrement,
  2808. ocsptimeout);
  2809. if (bytesRead > 0) {
  2810. PRInt32 searchOffset = (offset - markLen) > 0 ? offset - markLen : 0;
  2811. offset += bytesRead;
  2812. *(inBuffer + offset) = '\0'; /* NULL termination */
  2813. headerEnd = strstr((const char *)inBuffer + searchOffset, headerEndMark);
  2814. if (bytesRead < bufSizeIncrement) {
  2815. /* we read less data than requested, therefore we are at
  2816. EOS or there was a read error */
  2817. EOS = PR_TRUE;
  2818. }
  2819. } else {
  2820. /* recv error or EOS */
  2821. EOS = PR_TRUE;
  2822. }
  2823. } while ((!headerEnd) && (PR_FALSE == EOS) &&
  2824. (inBufsize < maxBufSize));
  2825. if (!headerEnd) {
  2826. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2827. }
  2828. /* parse the HTTP status line */
  2829. statusLineEnd = strstr((const char *)inBuffer, CRLF);
  2830. if (!statusLineEnd) {
  2831. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2832. }
  2833. *statusLineEnd = '\0';
  2834. /* check for HTTP/ response */
  2835. space = strchr((const char *)inBuffer, ' ');
  2836. if (!space || PORT_Strncasecmp((const char *)inBuffer, httpprotocol, httplen) != 0) {
  2837. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2838. }
  2839. /* check the HTTP status code of 200 */
  2840. httpcode = space + 1;
  2841. space = strchr(httpcode, ' ');
  2842. if (!space) {
  2843. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2844. }
  2845. *space = 0;
  2846. if (0 != strcmp(httpcode, "200")) {
  2847. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2848. }
  2849. /* parse the HTTP headers in the buffer . We only care about
  2850. content-type and content-length
  2851. */
  2852. nextHeader = statusLineEnd + CRLFlen;
  2853. *headerEnd = '\0'; /* terminate */
  2854. do {
  2855. char *thisHeaderEnd = NULL;
  2856. char *value = NULL;
  2857. char *colon = strchr(nextHeader, ':');
  2858. if (!colon) {
  2859. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2860. }
  2861. *colon = '\0';
  2862. value = colon + 1;
  2863. /* jpierre - note : the following code will only handle the basic form
  2864. of HTTP/1.0 response headers, of the form "name: value" . Headers
  2865. split among multiple lines are not supported. This is not common
  2866. and should not be an issue, but it could become one in the
  2867. future */
  2868. if (*value != ' ') {
  2869. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2870. }
  2871. value++;
  2872. thisHeaderEnd = strstr(value, CRLF);
  2873. if (thisHeaderEnd) {
  2874. *thisHeaderEnd = '\0';
  2875. }
  2876. if (0 == PORT_Strcasecmp(nextHeader, "content-type")) {
  2877. contenttype = value;
  2878. } else if (0 == PORT_Strcasecmp(nextHeader, "content-length")) {
  2879. contentlength = atoi(value);
  2880. }
  2881. if (thisHeaderEnd) {
  2882. nextHeader = thisHeaderEnd + CRLFlen;
  2883. } else {
  2884. nextHeader = NULL;
  2885. }
  2886. } while (nextHeader && (nextHeader < (headerEnd + CRLFlen)));
  2887. /* check content-type */
  2888. if (!contenttype ||
  2889. (0 != PORT_Strcasecmp(contenttype, "application/ocsp-response"))) {
  2890. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2891. }
  2892. /* read the body of the OCSP response */
  2893. offset = offset - (PRInt32)(headerEnd - (const char *)inBuffer) - markLen;
  2894. if (offset) {
  2895. /* move all data to the beginning of the buffer */
  2896. PORT_Memmove(inBuffer, headerEnd + markLen, offset);
  2897. }
  2898. /* resize buffer to only what's needed to hold the current response */
  2899. inBufsize = (1 + (offset - 1) / bufSizeIncrement) * bufSizeIncrement;
  2900. while ((PR_FALSE == EOS) &&
  2901. ((contentlength == 0) || (offset < contentlength)) &&
  2902. (inBufsize < maxBufSize)) {
  2903. /* we still need to receive more body data */
  2904. inBufsize += bufSizeIncrement;
  2905. inBuffer = PORT_Realloc(inBuffer, inBufsize + 1);
  2906. if (NULL == inBuffer) {
  2907. AbortHttpDecode(SEC_ERROR_NO_MEMORY);
  2908. }
  2909. bytesRead = ocsp_read(sock, inBuffer + offset, bufSizeIncrement,
  2910. ocsptimeout);
  2911. if (bytesRead > 0) {
  2912. offset += bytesRead;
  2913. if (bytesRead < bufSizeIncrement) {
  2914. /* we read less data than requested, therefore we are at
  2915. EOS or there was a read error */
  2916. EOS = PR_TRUE;
  2917. }
  2918. } else {
  2919. /* recv error or EOS */
  2920. EOS = PR_TRUE;
  2921. }
  2922. }
  2923. if (0 == offset) {
  2924. AbortHttpDecode(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  2925. }
  2926. /*
  2927. * Now allocate the item to hold the data.
  2928. */
  2929. result = SECITEM_AllocItem(arena, NULL, offset);
  2930. if (NULL == result) {
  2931. AbortHttpDecode(SEC_ERROR_NO_MEMORY);
  2932. }
  2933. /*
  2934. * And copy the data left in the buffer.
  2935. */
  2936. PORT_Memcpy(result->data, inBuffer, offset);
  2937. /* and free the temporary buffer */
  2938. PORT_Free(inBuffer);
  2939. return result;
  2940. }
  2941. SECStatus
  2942. CERT_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath)
  2943. {
  2944. return ocsp_ParseURL(url, pHostname, pPort, pPath);
  2945. }
  2946. /*
  2947. * Limit the size of http responses we are willing to accept.
  2948. */
  2949. #define MAX_WANTED_OCSP_RESPONSE_LEN 64 * 1024
  2950. /* if (encodedRequest == NULL)
  2951. * then location MUST already include the full request,
  2952. * including base64 and urlencode,
  2953. * and the request will be sent with GET
  2954. * if (encodedRequest != NULL)
  2955. * then the request will be sent with POST
  2956. */
  2957. static SECItem *
  2958. fetchOcspHttpClientV1(PLArenaPool *arena,
  2959. const SEC_HttpClientFcnV1 *hcv1,
  2960. const char *location,
  2961. const SECItem *encodedRequest)
  2962. {
  2963. char *hostname = NULL;
  2964. char *path = NULL;
  2965. PRUint16 port;
  2966. SECItem *encodedResponse = NULL;
  2967. SEC_HTTP_SERVER_SESSION pServerSession = NULL;
  2968. SEC_HTTP_REQUEST_SESSION pRequestSession = NULL;
  2969. PRUint16 myHttpResponseCode;
  2970. const char *myHttpResponseData;
  2971. PRUint32 myHttpResponseDataLen;
  2972. if (ocsp_ParseURL(location, &hostname, &port, &path) == SECFailure) {
  2973. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST);
  2974. goto loser;
  2975. }
  2976. PORT_Assert(hostname != NULL);
  2977. PORT_Assert(path != NULL);
  2978. if ((*hcv1->createSessionFcn)(
  2979. hostname,
  2980. port,
  2981. &pServerSession) != SECSuccess) {
  2982. PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR);
  2983. goto loser;
  2984. }
  2985. /* We use a non-zero timeout, which means:
  2986. - the client will use blocking I/O
  2987. - TryFcn will not return WOULD_BLOCK nor a poll descriptor
  2988. - it's sufficient to call TryFcn once
  2989. No lock for accessing OCSP_Global.timeoutSeconds, bug 406120
  2990. */
  2991. if ((*hcv1->createFcn)(
  2992. pServerSession,
  2993. "http",
  2994. path,
  2995. encodedRequest ? "POST" : "GET",
  2996. PR_TicksPerSecond() * OCSP_Global.timeoutSeconds,
  2997. &pRequestSession) != SECSuccess) {
  2998. PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR);
  2999. goto loser;
  3000. }
  3001. if (encodedRequest &&
  3002. (*hcv1->setPostDataFcn)(
  3003. pRequestSession,
  3004. (char *)encodedRequest->data,
  3005. encodedRequest->len,
  3006. "application/ocsp-request") != SECSuccess) {
  3007. PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR);
  3008. goto loser;
  3009. }
  3010. /* we don't want result objects larger than this: */
  3011. myHttpResponseDataLen = MAX_WANTED_OCSP_RESPONSE_LEN;
  3012. OCSP_TRACE(("OCSP trySendAndReceive %s\n", location));
  3013. if ((*hcv1->trySendAndReceiveFcn)(
  3014. pRequestSession,
  3015. NULL,
  3016. &myHttpResponseCode,
  3017. NULL,
  3018. NULL,
  3019. &myHttpResponseData,
  3020. &myHttpResponseDataLen) != SECSuccess) {
  3021. PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR);
  3022. goto loser;
  3023. }
  3024. OCSP_TRACE(("OCSP trySendAndReceive result http %d\n", myHttpResponseCode));
  3025. if (myHttpResponseCode != 200) {
  3026. PORT_SetError(SEC_ERROR_OCSP_BAD_HTTP_RESPONSE);
  3027. goto loser;
  3028. }
  3029. encodedResponse = SECITEM_AllocItem(arena, NULL, myHttpResponseDataLen);
  3030. if (!encodedResponse) {
  3031. PORT_SetError(SEC_ERROR_NO_MEMORY);
  3032. goto loser;
  3033. }
  3034. PORT_Memcpy(encodedResponse->data, myHttpResponseData, myHttpResponseDataLen);
  3035. loser:
  3036. if (pRequestSession != NULL)
  3037. (*hcv1->freeFcn)(pRequestSession);
  3038. if (pServerSession != NULL)
  3039. (*hcv1->freeSessionFcn)(pServerSession);
  3040. if (path != NULL)
  3041. PORT_Free(path);
  3042. if (hostname != NULL)
  3043. PORT_Free(hostname);
  3044. return encodedResponse;
  3045. }
  3046. /*
  3047. * FUNCTION: CERT_GetEncodedOCSPResponseByMethod
  3048. * Creates and sends a request to an OCSP responder, then reads and
  3049. * returns the (encoded) response.
  3050. * INPUTS:
  3051. * PLArenaPool *arena
  3052. * Pointer to arena from which return value will be allocated.
  3053. * If NULL, result will be allocated from the heap (and thus should
  3054. * be freed via SECITEM_FreeItem).
  3055. * CERTCertList *certList
  3056. * A list of certs for which status will be requested.
  3057. * Note that all of these certificates should have the same issuer,
  3058. * or it's expected the response will be signed by a trusted responder.
  3059. * If the certs need to be broken up into multiple requests, that
  3060. * must be handled by the caller (and thus by having multiple calls
  3061. * to this routine), who knows about where the request(s) are being
  3062. * sent and whether there are any trusted responders in place.
  3063. * const char *location
  3064. * The location of the OCSP responder (a URL).
  3065. * const char *method
  3066. * The protocol method used when retrieving the OCSP response.
  3067. * Currently support: "GET" (http GET) and "POST" (http POST).
  3068. * Additionals methods for http or other protocols might be added
  3069. * in the future.
  3070. * PRTime time
  3071. * Indicates the time for which the certificate status is to be
  3072. * determined -- this may be used in the search for the cert's issuer
  3073. * but has no other bearing on the operation.
  3074. * PRBool addServiceLocator
  3075. * If true, the Service Locator extension should be added to the
  3076. * single request(s) for each cert.
  3077. * CERTCertificate *signerCert
  3078. * If non-NULL, means sign the request using this cert. Otherwise,
  3079. * do not sign.
  3080. * void *pwArg
  3081. * Pointer to argument for password prompting, if needed. (Definitely
  3082. * not needed if not signing.)
  3083. * OUTPUTS:
  3084. * CERTOCSPRequest **pRequest
  3085. * Pointer in which to store the OCSP request created for the given
  3086. * list of certificates. It is only filled in if the entire operation
  3087. * is successful and the pointer is not null -- and in that case the
  3088. * caller is then reponsible for destroying it.
  3089. * RETURN:
  3090. * Returns a pointer to the SECItem holding the response.
  3091. * On error, returns null with error set describing the reason:
  3092. * SEC_ERROR_UNKNOWN_ISSUER
  3093. * SEC_ERROR_CERT_BAD_ACCESS_LOCATION
  3094. * SEC_ERROR_OCSP_BAD_HTTP_RESPONSE
  3095. * Other errors are low-level problems (no memory, bad database, etc.).
  3096. */
  3097. SECItem *
  3098. CERT_GetEncodedOCSPResponseByMethod(PLArenaPool *arena, CERTCertList *certList,
  3099. const char *location, const char *method,
  3100. PRTime time, PRBool addServiceLocator,
  3101. CERTCertificate *signerCert, void *pwArg,
  3102. CERTOCSPRequest **pRequest)
  3103. {
  3104. CERTOCSPRequest *request;
  3105. request = CERT_CreateOCSPRequest(certList, time, addServiceLocator,
  3106. signerCert);
  3107. if (!request)
  3108. return NULL;
  3109. return ocsp_GetEncodedOCSPResponseFromRequest(arena, request, location,
  3110. method, time, addServiceLocator,
  3111. pwArg, pRequest);
  3112. }
  3113. /*
  3114. * FUNCTION: CERT_GetEncodedOCSPResponse
  3115. * Creates and sends a request to an OCSP responder, then reads and
  3116. * returns the (encoded) response.
  3117. *
  3118. * This is a legacy API that behaves identically to
  3119. * CERT_GetEncodedOCSPResponseByMethod using the "POST" method.
  3120. */
  3121. SECItem *
  3122. CERT_GetEncodedOCSPResponse(PLArenaPool *arena, CERTCertList *certList,
  3123. const char *location, PRTime time,
  3124. PRBool addServiceLocator,
  3125. CERTCertificate *signerCert, void *pwArg,
  3126. CERTOCSPRequest **pRequest)
  3127. {
  3128. return CERT_GetEncodedOCSPResponseByMethod(arena, certList, location,
  3129. "POST", time, addServiceLocator,
  3130. signerCert, pwArg, pRequest);
  3131. }
  3132. /* URL encode a buffer that consists of base64-characters, only,
  3133. * which means we can use a simple encoding logic.
  3134. *
  3135. * No output buffer size checking is performed.
  3136. * You should call the function twice, to calculate the required buffer size.
  3137. *
  3138. * If the outpufBuf parameter is NULL, the function will calculate the
  3139. * required size, including the trailing zero termination char.
  3140. *
  3141. * The function returns the number of bytes calculated or produced.
  3142. */
  3143. size_t
  3144. ocsp_UrlEncodeBase64Buf(const char *base64Buf, char *outputBuf)
  3145. {
  3146. const char *walkInput = NULL;
  3147. char *walkOutput = outputBuf;
  3148. size_t count = 0;
  3149. for (walkInput = base64Buf; *walkInput; ++walkInput) {
  3150. char c = *walkInput;
  3151. if (isspace(c))
  3152. continue;
  3153. switch (c) {
  3154. case '+':
  3155. if (outputBuf) {
  3156. strcpy(walkOutput, "%2B");
  3157. walkOutput += 3;
  3158. }
  3159. count += 3;
  3160. break;
  3161. case '/':
  3162. if (outputBuf) {
  3163. strcpy(walkOutput, "%2F");
  3164. walkOutput += 3;
  3165. }
  3166. count += 3;
  3167. break;
  3168. case '=':
  3169. if (outputBuf) {
  3170. strcpy(walkOutput, "%3D");
  3171. walkOutput += 3;
  3172. }
  3173. count += 3;
  3174. break;
  3175. default:
  3176. if (outputBuf) {
  3177. *walkOutput = *walkInput;
  3178. ++walkOutput;
  3179. }
  3180. ++count;
  3181. break;
  3182. }
  3183. }
  3184. if (outputBuf) {
  3185. *walkOutput = 0;
  3186. }
  3187. ++count;
  3188. return count;
  3189. }
  3190. enum { max_get_request_size = 255 }; /* defined by RFC2560 */
  3191. static SECItem *
  3192. cert_GetOCSPResponse(PLArenaPool *arena, const char *location,
  3193. const SECItem *encodedRequest);
  3194. static SECItem *
  3195. ocsp_GetEncodedOCSPResponseFromRequest(PLArenaPool *arena,
  3196. CERTOCSPRequest *request,
  3197. const char *location,
  3198. const char *method,
  3199. PRTime time,
  3200. PRBool addServiceLocator,
  3201. void *pwArg,
  3202. CERTOCSPRequest **pRequest)
  3203. {
  3204. SECItem *encodedRequest = NULL;
  3205. SECItem *encodedResponse = NULL;
  3206. SECStatus rv;
  3207. if (!location || !*location) /* location should be at least one byte */
  3208. goto loser;
  3209. rv = CERT_AddOCSPAcceptableResponses(request,
  3210. SEC_OID_PKIX_OCSP_BASIC_RESPONSE);
  3211. if (rv != SECSuccess)
  3212. goto loser;
  3213. encodedRequest = CERT_EncodeOCSPRequest(NULL, request, pwArg);
  3214. if (encodedRequest == NULL)
  3215. goto loser;
  3216. if (!strcmp(method, "GET")) {
  3217. encodedResponse = cert_GetOCSPResponse(arena, location, encodedRequest);
  3218. } else if (!strcmp(method, "POST")) {
  3219. encodedResponse = CERT_PostOCSPRequest(arena, location, encodedRequest);
  3220. } else {
  3221. goto loser;
  3222. }
  3223. if (encodedResponse != NULL && pRequest != NULL) {
  3224. *pRequest = request;
  3225. request = NULL; /* avoid destroying below */
  3226. }
  3227. loser:
  3228. if (request != NULL)
  3229. CERT_DestroyOCSPRequest(request);
  3230. if (encodedRequest != NULL)
  3231. SECITEM_FreeItem(encodedRequest, PR_TRUE);
  3232. return encodedResponse;
  3233. }
  3234. static SECItem *
  3235. cert_FetchOCSPResponse(PLArenaPool *arena, const char *location,
  3236. const SECItem *encodedRequest);
  3237. /* using HTTP GET method */
  3238. static SECItem *
  3239. cert_GetOCSPResponse(PLArenaPool *arena, const char *location,
  3240. const SECItem *encodedRequest)
  3241. {
  3242. char *walkOutput = NULL;
  3243. char *fullGetPath = NULL;
  3244. size_t pathLength;
  3245. PRInt32 urlEncodedBufLength;
  3246. size_t base64size;
  3247. char b64ReqBuf[max_get_request_size + 1];
  3248. size_t slashLengthIfNeeded = 0;
  3249. size_t getURLLength;
  3250. SECItem *item;
  3251. if (!location || !*location) {
  3252. return NULL;
  3253. }
  3254. pathLength = strlen(location);
  3255. if (location[pathLength - 1] != '/') {
  3256. slashLengthIfNeeded = 1;
  3257. }
  3258. /* Calculation as documented by PL_Base64Encode function.
  3259. * Use integer conversion to avoid having to use function ceil().
  3260. */
  3261. base64size = (((encodedRequest->len + 2) / 3) * 4);
  3262. if (base64size > max_get_request_size) {
  3263. return NULL;
  3264. }
  3265. memset(b64ReqBuf, 0, sizeof(b64ReqBuf));
  3266. PL_Base64Encode((const char *)encodedRequest->data, encodedRequest->len,
  3267. b64ReqBuf);
  3268. urlEncodedBufLength = ocsp_UrlEncodeBase64Buf(b64ReqBuf, NULL);
  3269. getURLLength = pathLength + urlEncodedBufLength + slashLengthIfNeeded;
  3270. /* urlEncodedBufLength already contains room for the zero terminator.
  3271. * Add another if we must add the '/' char.
  3272. */
  3273. if (arena) {
  3274. fullGetPath = (char *)PORT_ArenaAlloc(arena, getURLLength);
  3275. } else {
  3276. fullGetPath = (char *)PORT_Alloc(getURLLength);
  3277. }
  3278. if (!fullGetPath) {
  3279. return NULL;
  3280. }
  3281. strcpy(fullGetPath, location);
  3282. walkOutput = fullGetPath + pathLength;
  3283. if (walkOutput > fullGetPath && slashLengthIfNeeded) {
  3284. strcpy(walkOutput, "/");
  3285. ++walkOutput;
  3286. }
  3287. ocsp_UrlEncodeBase64Buf(b64ReqBuf, walkOutput);
  3288. item = cert_FetchOCSPResponse(arena, fullGetPath, NULL);
  3289. if (!arena) {
  3290. PORT_Free(fullGetPath);
  3291. }
  3292. return item;
  3293. }
  3294. SECItem *
  3295. CERT_PostOCSPRequest(PLArenaPool *arena, const char *location,
  3296. const SECItem *encodedRequest)
  3297. {
  3298. return cert_FetchOCSPResponse(arena, location, encodedRequest);
  3299. }
  3300. SECItem *
  3301. cert_FetchOCSPResponse(PLArenaPool *arena, const char *location,
  3302. const SECItem *encodedRequest)
  3303. {
  3304. const SEC_HttpClientFcn *registeredHttpClient;
  3305. SECItem *encodedResponse = NULL;
  3306. registeredHttpClient = SEC_GetRegisteredHttpClient();
  3307. if (registeredHttpClient && registeredHttpClient->version == 1) {
  3308. encodedResponse = fetchOcspHttpClientV1(
  3309. arena,
  3310. &registeredHttpClient->fcnTable.ftable1,
  3311. location,
  3312. encodedRequest);
  3313. } else {
  3314. /* use internal http client */
  3315. PRFileDesc *sock = ocsp_SendEncodedRequest(location, encodedRequest);
  3316. if (sock) {
  3317. encodedResponse = ocsp_GetEncodedResponse(arena, sock);
  3318. PR_Close(sock);
  3319. }
  3320. }
  3321. return encodedResponse;
  3322. }
  3323. static SECItem *
  3324. ocsp_GetEncodedOCSPResponseForSingleCert(PLArenaPool *arena,
  3325. CERTOCSPCertID *certID,
  3326. CERTCertificate *singleCert,
  3327. const char *location,
  3328. const char *method,
  3329. PRTime time,
  3330. PRBool addServiceLocator,
  3331. void *pwArg,
  3332. CERTOCSPRequest **pRequest)
  3333. {
  3334. CERTOCSPRequest *request;
  3335. request = cert_CreateSingleCertOCSPRequest(certID, singleCert, time,
  3336. addServiceLocator, NULL);
  3337. if (!request)
  3338. return NULL;
  3339. return ocsp_GetEncodedOCSPResponseFromRequest(arena, request, location,
  3340. method, time, addServiceLocator,
  3341. pwArg, pRequest);
  3342. }
  3343. /* Checks a certificate for the key usage extension of OCSP signer. */
  3344. static PRBool
  3345. ocsp_CertIsOCSPDesignatedResponder(CERTCertificate *cert)
  3346. {
  3347. SECStatus rv;
  3348. SECItem extItem;
  3349. SECItem **oids;
  3350. SECItem *oid;
  3351. SECOidTag oidTag;
  3352. PRBool retval;
  3353. CERTOidSequence *oidSeq = NULL;
  3354. extItem.data = NULL;
  3355. rv = CERT_FindCertExtension(cert, SEC_OID_X509_EXT_KEY_USAGE, &extItem);
  3356. if (rv != SECSuccess) {
  3357. goto loser;
  3358. }
  3359. oidSeq = CERT_DecodeOidSequence(&extItem);
  3360. if (oidSeq == NULL) {
  3361. goto loser;
  3362. }
  3363. oids = oidSeq->oids;
  3364. while (*oids != NULL) {
  3365. oid = *oids;
  3366. oidTag = SECOID_FindOIDTag(oid);
  3367. if (oidTag == SEC_OID_OCSP_RESPONDER) {
  3368. goto success;
  3369. }
  3370. oids++;
  3371. }
  3372. loser:
  3373. retval = PR_FALSE;
  3374. PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT);
  3375. goto done;
  3376. success:
  3377. retval = PR_TRUE;
  3378. done:
  3379. if (extItem.data != NULL) {
  3380. PORT_Free(extItem.data);
  3381. }
  3382. if (oidSeq != NULL) {
  3383. CERT_DestroyOidSequence(oidSeq);
  3384. }
  3385. return (retval);
  3386. }
  3387. #ifdef LATER /* \
  3388. * XXX This function is not currently used, but will \
  3389. * be needed later when we do revocation checking of \
  3390. * the responder certificate. Of course, it may need \
  3391. * revising then, if the cert extension interface has \
  3392. * changed. (Hopefully it will!) \
  3393. */
  3394. /* Checks a certificate to see if it has the OCSP no check extension. */
  3395. static PRBool
  3396. ocsp_CertHasNoCheckExtension(CERTCertificate *cert)
  3397. {
  3398. SECStatus rv;
  3399. rv = CERT_FindCertExtension(cert, SEC_OID_PKIX_OCSP_NO_CHECK,
  3400. NULL);
  3401. if (rv == SECSuccess) {
  3402. return PR_TRUE;
  3403. }
  3404. return PR_FALSE;
  3405. }
  3406. #endif /* LATER */
  3407. static PRBool
  3408. ocsp_matchcert(SECItem *certIndex, CERTCertificate *testCert)
  3409. {
  3410. SECItem item;
  3411. unsigned char buf[HASH_LENGTH_MAX];
  3412. item.data = buf;
  3413. item.len = SHA1_LENGTH;
  3414. if (CERT_GetSubjectPublicKeyDigest(NULL, testCert, SEC_OID_SHA1,
  3415. &item) == NULL) {
  3416. return PR_FALSE;
  3417. }
  3418. if (SECITEM_ItemsAreEqual(certIndex, &item)) {
  3419. return PR_TRUE;
  3420. }
  3421. if (CERT_GetSubjectPublicKeyDigest(NULL, testCert, SEC_OID_MD5,
  3422. &item) == NULL) {
  3423. return PR_FALSE;
  3424. }
  3425. if (SECITEM_ItemsAreEqual(certIndex, &item)) {
  3426. return PR_TRUE;
  3427. }
  3428. if (CERT_GetSubjectPublicKeyDigest(NULL, testCert, SEC_OID_MD2,
  3429. &item) == NULL) {
  3430. return PR_FALSE;
  3431. }
  3432. if (SECITEM_ItemsAreEqual(certIndex, &item)) {
  3433. return PR_TRUE;
  3434. }
  3435. return PR_FALSE;
  3436. }
  3437. static CERTCertificate *
  3438. ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle, CERTOCSPCertID *certID);
  3439. CERTCertificate *
  3440. ocsp_GetSignerCertificate(CERTCertDBHandle *handle, ocspResponseData *tbsData,
  3441. ocspSignature *signature, CERTCertificate *issuer)
  3442. {
  3443. CERTCertificate **certs = NULL;
  3444. CERTCertificate *signerCert = NULL;
  3445. SECStatus rv = SECFailure;
  3446. PRBool lookupByName = PR_TRUE;
  3447. void *certIndex = NULL;
  3448. int certCount = 0;
  3449. PORT_Assert(tbsData->responderID != NULL);
  3450. switch (tbsData->responderID->responderIDType) {
  3451. case ocspResponderID_byName:
  3452. lookupByName = PR_TRUE;
  3453. certIndex = &tbsData->derResponderID;
  3454. break;
  3455. case ocspResponderID_byKey:
  3456. lookupByName = PR_FALSE;
  3457. certIndex = &tbsData->responderID->responderIDValue.keyHash;
  3458. break;
  3459. case ocspResponderID_other:
  3460. default:
  3461. PORT_Assert(0);
  3462. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  3463. return NULL;
  3464. }
  3465. /*
  3466. * If the signature contains some certificates as well, temporarily
  3467. * import them in case they are needed for verification.
  3468. *
  3469. * Note that the result of this is that each cert in "certs" needs
  3470. * to be destroyed.
  3471. */
  3472. if (signature->derCerts != NULL) {
  3473. for (; signature->derCerts[certCount] != NULL; certCount++) {
  3474. /* just counting */
  3475. }
  3476. rv = CERT_ImportCerts(handle, certUsageStatusResponder, certCount,
  3477. signature->derCerts, &certs,
  3478. PR_FALSE, PR_FALSE, NULL);
  3479. if (rv != SECSuccess)
  3480. goto finish;
  3481. }
  3482. /*
  3483. * Now look up the certificate that did the signing.
  3484. * The signer can be specified either by name or by key hash.
  3485. */
  3486. if (lookupByName) {
  3487. SECItem *crIndex = (SECItem *)certIndex;
  3488. SECItem encodedName;
  3489. PLArenaPool *arena;
  3490. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  3491. if (arena != NULL) {
  3492. rv = SEC_QuickDERDecodeItem(arena, &encodedName,
  3493. ocsp_ResponderIDDerNameTemplate,
  3494. crIndex);
  3495. if (rv != SECSuccess) {
  3496. if (PORT_GetError() == SEC_ERROR_BAD_DER)
  3497. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  3498. } else {
  3499. signerCert = CERT_FindCertByName(handle, &encodedName);
  3500. }
  3501. PORT_FreeArena(arena, PR_FALSE);
  3502. }
  3503. } else {
  3504. /*
  3505. * The signer is either 1) a known issuer CA we passed in,
  3506. * 2) the default OCSP responder, or 3) an intermediate CA
  3507. * passed in the cert list to use. Figure out which it is.
  3508. */
  3509. int i;
  3510. CERTCertificate *responder =
  3511. ocsp_CertGetDefaultResponder(handle, NULL);
  3512. if (responder && ocsp_matchcert(certIndex, responder)) {
  3513. signerCert = CERT_DupCertificate(responder);
  3514. } else if (issuer && ocsp_matchcert(certIndex, issuer)) {
  3515. signerCert = CERT_DupCertificate(issuer);
  3516. }
  3517. for (i = 0; (signerCert == NULL) && (i < certCount); i++) {
  3518. if (ocsp_matchcert(certIndex, certs[i])) {
  3519. signerCert = CERT_DupCertificate(certs[i]);
  3520. }
  3521. }
  3522. if (signerCert == NULL) {
  3523. PORT_SetError(SEC_ERROR_UNKNOWN_CERT);
  3524. }
  3525. }
  3526. finish:
  3527. if (certs != NULL) {
  3528. CERT_DestroyCertArray(certs, certCount);
  3529. }
  3530. return signerCert;
  3531. }
  3532. SECStatus
  3533. ocsp_VerifyResponseSignature(CERTCertificate *signerCert,
  3534. ocspSignature *signature,
  3535. SECItem *tbsResponseDataDER,
  3536. void *pwArg)
  3537. {
  3538. SECKEYPublicKey *signerKey = NULL;
  3539. SECStatus rv = SECFailure;
  3540. CERTSignedData signedData;
  3541. /*
  3542. * Now get the public key from the signer's certificate; we need
  3543. * it to perform the verification.
  3544. */
  3545. signerKey = CERT_ExtractPublicKey(signerCert);
  3546. if (signerKey == NULL) {
  3547. return SECFailure;
  3548. }
  3549. /*
  3550. * We copy the signature data *pointer* and length, so that we can
  3551. * modify the length without damaging the original copy. This is a
  3552. * simple copy, not a dup, so no destroy/free is necessary.
  3553. */
  3554. signedData.signature = signature->signature;
  3555. signedData.signatureAlgorithm = signature->signatureAlgorithm;
  3556. signedData.data = *tbsResponseDataDER;
  3557. rv = CERT_VerifySignedDataWithPublicKey(&signedData, signerKey, pwArg);
  3558. if (rv != SECSuccess &&
  3559. (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE ||
  3560. PORT_GetError() == SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED)) {
  3561. PORT_SetError(SEC_ERROR_OCSP_BAD_SIGNATURE);
  3562. }
  3563. if (signerKey != NULL) {
  3564. SECKEY_DestroyPublicKey(signerKey);
  3565. }
  3566. return rv;
  3567. }
  3568. /*
  3569. * FUNCTION: CERT_VerifyOCSPResponseSignature
  3570. * Check the signature on an OCSP Response. Will also perform a
  3571. * verification of the signer's certificate. Note, however, that a
  3572. * successful verification does not make any statement about the
  3573. * signer's *authority* to provide status for the certificate(s),
  3574. * that must be checked individually for each certificate.
  3575. * INPUTS:
  3576. * CERTOCSPResponse *response
  3577. * Pointer to response structure with signature to be checked.
  3578. * CERTCertDBHandle *handle
  3579. * Pointer to CERTCertDBHandle for certificate DB to use for verification.
  3580. * void *pwArg
  3581. * Pointer to argument for password prompting, if needed.
  3582. * OUTPUTS:
  3583. * CERTCertificate **pSignerCert
  3584. * Pointer in which to store signer's certificate; only filled-in if
  3585. * non-null.
  3586. * RETURN:
  3587. * Returns SECSuccess when signature is valid, anything else means invalid.
  3588. * Possible errors set:
  3589. * SEC_ERROR_OCSP_MALFORMED_RESPONSE - unknown type of ResponderID
  3590. * SEC_ERROR_INVALID_TIME - bad format of "ProducedAt" time
  3591. * SEC_ERROR_UNKNOWN_SIGNER - signer's cert could not be found
  3592. * SEC_ERROR_BAD_SIGNATURE - the signature did not verify
  3593. * Other errors are any of the many possible failures in cert verification
  3594. * (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when
  3595. * verifying the signer's cert, or low-level problems (no memory, etc.)
  3596. */
  3597. SECStatus
  3598. CERT_VerifyOCSPResponseSignature(CERTOCSPResponse *response,
  3599. CERTCertDBHandle *handle, void *pwArg,
  3600. CERTCertificate **pSignerCert,
  3601. CERTCertificate *issuer)
  3602. {
  3603. SECItem *tbsResponseDataDER;
  3604. CERTCertificate *signerCert = NULL;
  3605. SECStatus rv = SECFailure;
  3606. PRTime producedAt;
  3607. /* ocsp_DecodeBasicOCSPResponse will fail if asn1 decoder is unable
  3608. * to properly decode tbsData (see the function and
  3609. * ocsp_BasicOCSPResponseTemplate). Thus, tbsData can not be
  3610. * equal to null */
  3611. ocspResponseData *tbsData = ocsp_GetResponseData(response,
  3612. &tbsResponseDataDER);
  3613. ocspSignature *signature = ocsp_GetResponseSignature(response);
  3614. if (!signature) {
  3615. PORT_SetError(SEC_ERROR_OCSP_BAD_SIGNATURE);
  3616. return SECFailure;
  3617. }
  3618. /*
  3619. * If this signature has already gone through verification, just
  3620. * return the cached result.
  3621. */
  3622. if (signature->wasChecked) {
  3623. if (signature->status == SECSuccess) {
  3624. if (pSignerCert != NULL)
  3625. *pSignerCert = CERT_DupCertificate(signature->cert);
  3626. } else {
  3627. PORT_SetError(signature->failureReason);
  3628. }
  3629. return signature->status;
  3630. }
  3631. signerCert = ocsp_GetSignerCertificate(handle, tbsData,
  3632. signature, issuer);
  3633. if (signerCert == NULL) {
  3634. rv = SECFailure;
  3635. if (PORT_GetError() == SEC_ERROR_UNKNOWN_CERT) {
  3636. /* Make the error a little more specific. */
  3637. PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT);
  3638. }
  3639. goto finish;
  3640. }
  3641. /*
  3642. * We could mark this true at the top of this function, or always
  3643. * below at "finish", but if the problem was just that we could not
  3644. * find the signer's cert, leave that as if the signature hasn't
  3645. * been checked in case a subsequent call might have better luck.
  3646. */
  3647. signature->wasChecked = PR_TRUE;
  3648. /*
  3649. * The function will also verify the signer certificate; we
  3650. * need to tell it *when* that certificate must be valid -- for our
  3651. * purposes we expect it to be valid when the response was signed.
  3652. * The value of "producedAt" is the signing time.
  3653. */
  3654. rv = DER_GeneralizedTimeToTime(&producedAt, &tbsData->producedAt);
  3655. if (rv != SECSuccess)
  3656. goto finish;
  3657. /*
  3658. * Just because we have a cert does not mean it is any good; check
  3659. * it for validity, trust and usage.
  3660. */
  3661. if (!ocsp_CertIsOCSPDefaultResponder(handle, signerCert)) {
  3662. SECCertUsage certUsage;
  3663. if (CERT_IsCACert(signerCert, NULL)) {
  3664. certUsage = certUsageAnyCA;
  3665. } else {
  3666. certUsage = certUsageStatusResponder;
  3667. }
  3668. rv = cert_VerifyCertWithFlags(handle, signerCert, PR_TRUE, certUsage,
  3669. producedAt, CERT_VERIFYCERT_SKIP_OCSP,
  3670. pwArg, NULL);
  3671. if (rv != SECSuccess) {
  3672. PORT_SetError(SEC_ERROR_OCSP_INVALID_SIGNING_CERT);
  3673. goto finish;
  3674. }
  3675. }
  3676. rv = ocsp_VerifyResponseSignature(signerCert, signature,
  3677. tbsResponseDataDER,
  3678. pwArg);
  3679. finish:
  3680. if (signature->wasChecked)
  3681. signature->status = rv;
  3682. if (rv != SECSuccess) {
  3683. signature->failureReason = PORT_GetError();
  3684. if (signerCert != NULL)
  3685. CERT_DestroyCertificate(signerCert);
  3686. } else {
  3687. /*
  3688. * Save signer's certificate in signature.
  3689. */
  3690. signature->cert = signerCert;
  3691. if (pSignerCert != NULL) {
  3692. /*
  3693. * Pass pointer to signer's certificate back to our caller,
  3694. * who is also now responsible for destroying it.
  3695. */
  3696. *pSignerCert = CERT_DupCertificate(signerCert);
  3697. }
  3698. }
  3699. return rv;
  3700. }
  3701. /*
  3702. * See if the request's certID and the single response's certID match.
  3703. * This can be easy or difficult, depending on whether the same hash
  3704. * algorithm was used.
  3705. */
  3706. static PRBool
  3707. ocsp_CertIDsMatch(CERTOCSPCertID *requestCertID,
  3708. CERTOCSPCertID *responseCertID)
  3709. {
  3710. PRBool match = PR_FALSE;
  3711. SECOidTag hashAlg;
  3712. SECItem *keyHash = NULL;
  3713. SECItem *nameHash = NULL;
  3714. /*
  3715. * In order to match, they must have the same issuer and the same
  3716. * serial number.
  3717. *
  3718. * We just compare the easier things first.
  3719. */
  3720. if (SECITEM_CompareItem(&requestCertID->serialNumber,
  3721. &responseCertID->serialNumber) != SECEqual) {
  3722. goto done;
  3723. }
  3724. /*
  3725. * Make sure the "parameters" are not too bogus. Since we encoded
  3726. * requestCertID->hashAlgorithm, we don't need to check it.
  3727. */
  3728. if (responseCertID->hashAlgorithm.parameters.len > 2) {
  3729. goto done;
  3730. }
  3731. if (SECITEM_CompareItem(&requestCertID->hashAlgorithm.algorithm,
  3732. &responseCertID->hashAlgorithm.algorithm) ==
  3733. SECEqual) {
  3734. /*
  3735. * If the hash algorithms match then we can do a simple compare
  3736. * of the hash values themselves.
  3737. */
  3738. if ((SECITEM_CompareItem(&requestCertID->issuerNameHash,
  3739. &responseCertID->issuerNameHash) == SECEqual) &&
  3740. (SECITEM_CompareItem(&requestCertID->issuerKeyHash,
  3741. &responseCertID->issuerKeyHash) == SECEqual)) {
  3742. match = PR_TRUE;
  3743. }
  3744. goto done;
  3745. }
  3746. hashAlg = SECOID_FindOIDTag(&responseCertID->hashAlgorithm.algorithm);
  3747. switch (hashAlg) {
  3748. case SEC_OID_SHA1:
  3749. keyHash = &requestCertID->issuerSHA1KeyHash;
  3750. nameHash = &requestCertID->issuerSHA1NameHash;
  3751. break;
  3752. case SEC_OID_MD5:
  3753. keyHash = &requestCertID->issuerMD5KeyHash;
  3754. nameHash = &requestCertID->issuerMD5NameHash;
  3755. break;
  3756. case SEC_OID_MD2:
  3757. keyHash = &requestCertID->issuerMD2KeyHash;
  3758. nameHash = &requestCertID->issuerMD2NameHash;
  3759. break;
  3760. default:
  3761. PORT_SetError(SEC_ERROR_INVALID_ALGORITHM);
  3762. return PR_FALSE;
  3763. }
  3764. if ((keyHash != NULL) &&
  3765. (SECITEM_CompareItem(nameHash,
  3766. &responseCertID->issuerNameHash) == SECEqual) &&
  3767. (SECITEM_CompareItem(keyHash,
  3768. &responseCertID->issuerKeyHash) == SECEqual)) {
  3769. match = PR_TRUE;
  3770. }
  3771. done:
  3772. return match;
  3773. }
  3774. /*
  3775. * Find the single response for the cert specified by certID.
  3776. * No copying is done; this just returns a pointer to the appropriate
  3777. * response within responses, if it is found (and null otherwise).
  3778. * This is fine, of course, since this function is internal-use only.
  3779. */
  3780. static CERTOCSPSingleResponse *
  3781. ocsp_GetSingleResponseForCertID(CERTOCSPSingleResponse **responses,
  3782. CERTCertDBHandle *handle,
  3783. CERTOCSPCertID *certID)
  3784. {
  3785. CERTOCSPSingleResponse *single;
  3786. int i;
  3787. if (responses == NULL)
  3788. return NULL;
  3789. for (i = 0; responses[i] != NULL; i++) {
  3790. single = responses[i];
  3791. if (ocsp_CertIDsMatch(certID, single->certID)) {
  3792. return single;
  3793. }
  3794. }
  3795. /*
  3796. * The OCSP server should have included a response even if it knew
  3797. * nothing about the certificate in question. Since it did not,
  3798. * this will make it look as if it had.
  3799. *
  3800. * XXX Should we make this a separate error to notice the server's
  3801. * bad behavior?
  3802. */
  3803. PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_CERT);
  3804. return NULL;
  3805. }
  3806. static ocspCheckingContext *
  3807. ocsp_GetCheckingContext(CERTCertDBHandle *handle)
  3808. {
  3809. CERTStatusConfig *statusConfig;
  3810. ocspCheckingContext *ocspcx = NULL;
  3811. statusConfig = CERT_GetStatusConfig(handle);
  3812. if (statusConfig != NULL) {
  3813. ocspcx = statusConfig->statusContext;
  3814. /*
  3815. * This is actually an internal error, because we should never
  3816. * have a good statusConfig without a good statusContext, too.
  3817. * For lack of anything better, though, we just assert and use
  3818. * the same error as if there were no statusConfig (set below).
  3819. */
  3820. PORT_Assert(ocspcx != NULL);
  3821. }
  3822. if (ocspcx == NULL)
  3823. PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED);
  3824. return ocspcx;
  3825. }
  3826. /*
  3827. * Return cert reference if the given signerCert is the default responder for
  3828. * the given certID. If not, or if any error, return NULL.
  3829. */
  3830. static CERTCertificate *
  3831. ocsp_CertGetDefaultResponder(CERTCertDBHandle *handle, CERTOCSPCertID *certID)
  3832. {
  3833. ocspCheckingContext *ocspcx;
  3834. ocspcx = ocsp_GetCheckingContext(handle);
  3835. if (ocspcx == NULL)
  3836. goto loser;
  3837. /*
  3838. * Right now we have only one default responder. It applies to
  3839. * all certs when it is used, so the check is simple and certID
  3840. * has no bearing on the answer. Someday in the future we may
  3841. * allow configuration of different responders for different
  3842. * issuers, and then we would have to use the issuer specified
  3843. * in certID to determine if signerCert is the right one.
  3844. */
  3845. if (ocspcx->useDefaultResponder) {
  3846. PORT_Assert(ocspcx->defaultResponderCert != NULL);
  3847. return ocspcx->defaultResponderCert;
  3848. }
  3849. loser:
  3850. return NULL;
  3851. }
  3852. /*
  3853. * Return true if the cert is one of the default responders configured for
  3854. * ocsp context. If not, or if any error, return false.
  3855. */
  3856. PRBool
  3857. ocsp_CertIsOCSPDefaultResponder(CERTCertDBHandle *handle, CERTCertificate *cert)
  3858. {
  3859. ocspCheckingContext *ocspcx;
  3860. ocspcx = ocsp_GetCheckingContext(handle);
  3861. if (ocspcx == NULL)
  3862. return PR_FALSE;
  3863. /*
  3864. * Right now we have only one default responder. It applies to
  3865. * all certs when it is used, so the check is simple and certID
  3866. * has no bearing on the answer. Someday in the future we may
  3867. * allow configuration of different responders for different
  3868. * issuers, and then we would have to use the issuer specified
  3869. * in certID to determine if signerCert is the right one.
  3870. */
  3871. if (ocspcx->useDefaultResponder &&
  3872. CERT_CompareCerts(ocspcx->defaultResponderCert, cert)) {
  3873. return PR_TRUE;
  3874. }
  3875. return PR_FALSE;
  3876. }
  3877. /*
  3878. * Check that the given signer certificate is authorized to sign status
  3879. * information for the given certID. Return true if it is, false if not
  3880. * (or if there is any error along the way). If false is returned because
  3881. * the signer is not authorized, the following error will be set:
  3882. * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE
  3883. * Other errors are low-level problems (no memory, bad database, etc.).
  3884. *
  3885. * There are three ways to be authorized. In the order in which we check,
  3886. * using the terms used in the OCSP spec, the signer must be one of:
  3887. * 1. A "trusted responder" -- it matches a local configuration
  3888. * of OCSP signing authority for the certificate in question.
  3889. * 2. The CA who issued the certificate in question.
  3890. * 3. A "CA designated responder", aka an "authorized responder" -- it
  3891. * must be represented by a special cert issued by the CA who issued
  3892. * the certificate in question.
  3893. */
  3894. static PRBool
  3895. ocsp_AuthorizedResponderForCertID(CERTCertDBHandle *handle,
  3896. CERTCertificate *signerCert,
  3897. CERTOCSPCertID *certID,
  3898. PRTime thisUpdate)
  3899. {
  3900. CERTCertificate *issuerCert = NULL, *defRespCert;
  3901. SECItem *keyHash = NULL;
  3902. SECItem *nameHash = NULL;
  3903. SECOidTag hashAlg;
  3904. PRBool keyHashEQ = PR_FALSE, nameHashEQ = PR_FALSE;
  3905. /*
  3906. * Check first for a trusted responder, which overrides everything else.
  3907. */
  3908. if ((defRespCert = ocsp_CertGetDefaultResponder(handle, certID)) &&
  3909. CERT_CompareCerts(defRespCert, signerCert)) {
  3910. return PR_TRUE;
  3911. }
  3912. /*
  3913. * In the other two cases, we need to do an issuer comparison.
  3914. * How we do it depends on whether the signer certificate has the
  3915. * special extension (for a designated responder) or not.
  3916. *
  3917. * First, lets check if signer of the response is the actual issuer
  3918. * of the cert. For that we will use signer cert key hash and cert subj
  3919. * name hash and will compare them with already calculated issuer key
  3920. * hash and issuer name hash. The hash algorithm is picked from response
  3921. * certID hash to avoid second hash calculation.
  3922. */
  3923. hashAlg = SECOID_FindOIDTag(&certID->hashAlgorithm.algorithm);
  3924. keyHash = CERT_GetSubjectPublicKeyDigest(NULL, signerCert, hashAlg, NULL);
  3925. if (keyHash != NULL) {
  3926. keyHashEQ =
  3927. (SECITEM_CompareItem(keyHash,
  3928. &certID->issuerKeyHash) == SECEqual);
  3929. SECITEM_FreeItem(keyHash, PR_TRUE);
  3930. }
  3931. if (keyHashEQ &&
  3932. (nameHash = CERT_GetSubjectNameDigest(NULL, signerCert,
  3933. hashAlg, NULL))) {
  3934. nameHashEQ =
  3935. (SECITEM_CompareItem(nameHash,
  3936. &certID->issuerNameHash) == SECEqual);
  3937. SECITEM_FreeItem(nameHash, PR_TRUE);
  3938. if (nameHashEQ) {
  3939. /* The issuer of the cert is the the signer of the response */
  3940. return PR_TRUE;
  3941. }
  3942. }
  3943. keyHashEQ = PR_FALSE;
  3944. nameHashEQ = PR_FALSE;
  3945. if (!ocsp_CertIsOCSPDesignatedResponder(signerCert)) {
  3946. PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE);
  3947. return PR_FALSE;
  3948. }
  3949. /*
  3950. * The signer is a designated responder. Its issuer must match
  3951. * the issuer of the cert being checked.
  3952. */
  3953. issuerCert = CERT_FindCertIssuer(signerCert, thisUpdate,
  3954. certUsageAnyCA);
  3955. if (issuerCert == NULL) {
  3956. /*
  3957. * We could leave the SEC_ERROR_UNKNOWN_ISSUER error alone,
  3958. * but the following will give slightly more information.
  3959. * Once we have an error stack, things will be much better.
  3960. */
  3961. PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE);
  3962. return PR_FALSE;
  3963. }
  3964. keyHash = CERT_GetSubjectPublicKeyDigest(NULL, issuerCert, hashAlg, NULL);
  3965. nameHash = CERT_GetSubjectNameDigest(NULL, issuerCert, hashAlg, NULL);
  3966. CERT_DestroyCertificate(issuerCert);
  3967. if (keyHash != NULL && nameHash != NULL) {
  3968. keyHashEQ =
  3969. (SECITEM_CompareItem(keyHash,
  3970. &certID->issuerKeyHash) == SECEqual);
  3971. nameHashEQ =
  3972. (SECITEM_CompareItem(nameHash,
  3973. &certID->issuerNameHash) == SECEqual);
  3974. }
  3975. if (keyHash) {
  3976. SECITEM_FreeItem(keyHash, PR_TRUE);
  3977. }
  3978. if (nameHash) {
  3979. SECITEM_FreeItem(nameHash, PR_TRUE);
  3980. }
  3981. if (keyHashEQ && nameHashEQ) {
  3982. return PR_TRUE;
  3983. }
  3984. PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE);
  3985. return PR_FALSE;
  3986. }
  3987. /*
  3988. * We need to check that a responder gives us "recent" information.
  3989. * Since a responder can pre-package responses, we need to pick an amount
  3990. * of time that is acceptable to us, and reject any response that is
  3991. * older than that.
  3992. *
  3993. * XXX This *should* be based on some configuration parameter, so that
  3994. * different usages could specify exactly what constitutes "sufficiently
  3995. * recent". But that is not going to happen right away. For now, we
  3996. * want something from within the last 24 hours. This macro defines that
  3997. * number in seconds.
  3998. */
  3999. #define OCSP_ALLOWABLE_LAPSE_SECONDS (24L * 60L * 60L)
  4000. static PRBool
  4001. ocsp_TimeIsRecent(PRTime checkTime)
  4002. {
  4003. PRTime now = PR_Now();
  4004. PRTime lapse, tmp;
  4005. LL_I2L(lapse, OCSP_ALLOWABLE_LAPSE_SECONDS);
  4006. LL_I2L(tmp, PR_USEC_PER_SEC);
  4007. LL_MUL(lapse, lapse, tmp); /* allowable lapse in microseconds */
  4008. LL_ADD(checkTime, checkTime, lapse);
  4009. if (LL_CMP(now, >, checkTime))
  4010. return PR_FALSE;
  4011. return PR_TRUE;
  4012. }
  4013. #define OCSP_SLOP (5L * 60L) /* OCSP responses are allowed to be 5 minutes \
  4014. in the future by default */
  4015. static PRUint32 ocspsloptime = OCSP_SLOP; /* seconds */
  4016. /*
  4017. * If an old response contains the revoked certificate status, we want
  4018. * to return SECSuccess so the response will be used.
  4019. */
  4020. static SECStatus
  4021. ocsp_HandleOldSingleResponse(CERTOCSPSingleResponse *single, PRTime time)
  4022. {
  4023. SECStatus rv;
  4024. ocspCertStatus *status = single->certStatus;
  4025. if (status->certStatusType == ocspCertStatus_revoked) {
  4026. rv = ocsp_CertRevokedAfter(status->certStatusInfo.revokedInfo, time);
  4027. if (rv != SECSuccess &&
  4028. PORT_GetError() == SEC_ERROR_REVOKED_CERTIFICATE) {
  4029. /*
  4030. * Return SECSuccess now. The subsequent ocsp_CertRevokedAfter
  4031. * call in ocsp_CertHasGoodStatus will cause
  4032. * ocsp_CertHasGoodStatus to fail with
  4033. * SEC_ERROR_REVOKED_CERTIFICATE.
  4034. */
  4035. return SECSuccess;
  4036. }
  4037. }
  4038. PORT_SetError(SEC_ERROR_OCSP_OLD_RESPONSE);
  4039. return SECFailure;
  4040. }
  4041. /*
  4042. * Check that this single response is okay. A return of SECSuccess means:
  4043. * 1. The signer (represented by "signerCert") is authorized to give status
  4044. * for the cert represented by the individual response in "single".
  4045. * 2. The value of thisUpdate is earlier than now.
  4046. * 3. The value of producedAt is later than or the same as thisUpdate.
  4047. * 4. If nextUpdate is given:
  4048. * - The value of nextUpdate is later than now.
  4049. * - The value of producedAt is earlier than nextUpdate.
  4050. * Else if no nextUpdate:
  4051. * - The value of thisUpdate is fairly recent.
  4052. * - The value of producedAt is fairly recent.
  4053. * However we do not need to perform an explicit check for this last
  4054. * constraint because it is already guaranteed by checking that
  4055. * producedAt is later than thisUpdate and thisUpdate is recent.
  4056. * Oh, and any responder is "authorized" to say that a cert is unknown to it.
  4057. *
  4058. * If any of those checks fail, SECFailure is returned and an error is set:
  4059. * SEC_ERROR_OCSP_FUTURE_RESPONSE
  4060. * SEC_ERROR_OCSP_OLD_RESPONSE
  4061. * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE
  4062. * Other errors are low-level problems (no memory, bad database, etc.).
  4063. */
  4064. static SECStatus
  4065. ocsp_VerifySingleResponse(CERTOCSPSingleResponse *single,
  4066. CERTCertDBHandle *handle,
  4067. CERTCertificate *signerCert,
  4068. PRTime producedAt)
  4069. {
  4070. CERTOCSPCertID *certID = single->certID;
  4071. PRTime now, thisUpdate, nextUpdate, tmstamp, tmp;
  4072. SECStatus rv;
  4073. OCSP_TRACE(("OCSP ocsp_VerifySingleResponse, nextUpdate: %d\n",
  4074. ((single->nextUpdate) != 0)));
  4075. /*
  4076. * If all the responder said was that the given cert was unknown to it,
  4077. * that is a valid response. Not very interesting to us, of course,
  4078. * but all this function is concerned with is validity of the response,
  4079. * not the status of the cert.
  4080. */
  4081. PORT_Assert(single->certStatus != NULL);
  4082. if (single->certStatus->certStatusType == ocspCertStatus_unknown)
  4083. return SECSuccess;
  4084. /*
  4085. * We need to extract "thisUpdate" for use below and to pass along
  4086. * to AuthorizedResponderForCertID in case it needs it for doing an
  4087. * issuer look-up.
  4088. */
  4089. rv = DER_GeneralizedTimeToTime(&thisUpdate, &single->thisUpdate);
  4090. if (rv != SECSuccess)
  4091. return rv;
  4092. /*
  4093. * First confirm that signerCert is authorized to give this status.
  4094. */
  4095. if (ocsp_AuthorizedResponderForCertID(handle, signerCert, certID,
  4096. thisUpdate) != PR_TRUE)
  4097. return SECFailure;
  4098. /*
  4099. * Now check the time stuff, as described above.
  4100. */
  4101. now = PR_Now();
  4102. /* allow slop time for future response */
  4103. LL_UI2L(tmstamp, ocspsloptime); /* get slop time in seconds */
  4104. LL_UI2L(tmp, PR_USEC_PER_SEC);
  4105. LL_MUL(tmp, tmstamp, tmp); /* convert the slop time to PRTime */
  4106. LL_ADD(tmstamp, tmp, now); /* add current time to it */
  4107. if (LL_CMP(thisUpdate, >, tmstamp) || LL_CMP(producedAt, <, thisUpdate)) {
  4108. PORT_SetError(SEC_ERROR_OCSP_FUTURE_RESPONSE);
  4109. return SECFailure;
  4110. }
  4111. if (single->nextUpdate != NULL) {
  4112. rv = DER_GeneralizedTimeToTime(&nextUpdate, single->nextUpdate);
  4113. if (rv != SECSuccess)
  4114. return rv;
  4115. LL_ADD(tmp, tmp, nextUpdate);
  4116. if (LL_CMP(tmp, <, now) || LL_CMP(producedAt, >, nextUpdate))
  4117. return ocsp_HandleOldSingleResponse(single, now);
  4118. } else if (ocsp_TimeIsRecent(thisUpdate) != PR_TRUE) {
  4119. return ocsp_HandleOldSingleResponse(single, now);
  4120. }
  4121. return SECSuccess;
  4122. }
  4123. /*
  4124. * FUNCTION: CERT_GetOCSPAuthorityInfoAccessLocation
  4125. * Get the value of the URI of the OCSP responder for the given cert.
  4126. * This is found in the (optional) Authority Information Access extension
  4127. * in the cert.
  4128. * INPUTS:
  4129. * CERTCertificate *cert
  4130. * The certificate being examined.
  4131. * RETURN:
  4132. * char *
  4133. * A copy of the URI for the OCSP method, if found. If either the
  4134. * extension is not present or it does not contain an entry for OCSP,
  4135. * SEC_ERROR_CERT_BAD_ACCESS_LOCATION will be set and a NULL returned.
  4136. * Any other error will also result in a NULL being returned.
  4137. *
  4138. * This result should be freed (via PORT_Free) when no longer in use.
  4139. */
  4140. char *
  4141. CERT_GetOCSPAuthorityInfoAccessLocation(const CERTCertificate *cert)
  4142. {
  4143. CERTGeneralName *locname = NULL;
  4144. SECItem *location = NULL;
  4145. SECItem *encodedAuthInfoAccess = NULL;
  4146. CERTAuthInfoAccess **authInfoAccess = NULL;
  4147. char *locURI = NULL;
  4148. PLArenaPool *arena = NULL;
  4149. SECStatus rv;
  4150. int i;
  4151. /*
  4152. * Allocate this one from the heap because it will get filled in
  4153. * by CERT_FindCertExtension which will also allocate from the heap,
  4154. * and we can free the entire thing on our way out.
  4155. */
  4156. encodedAuthInfoAccess = SECITEM_AllocItem(NULL, NULL, 0);
  4157. if (encodedAuthInfoAccess == NULL)
  4158. goto loser;
  4159. rv = CERT_FindCertExtension(cert, SEC_OID_X509_AUTH_INFO_ACCESS,
  4160. encodedAuthInfoAccess);
  4161. if (rv == SECFailure) {
  4162. PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION);
  4163. goto loser;
  4164. }
  4165. /*
  4166. * The rest of the things allocated in the routine will come out of
  4167. * this arena, which is temporary just for us to decode and get at the
  4168. * AIA extension. The whole thing will be destroyed on our way out,
  4169. * after we have copied the location string (url) itself (if found).
  4170. */
  4171. arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  4172. if (arena == NULL)
  4173. goto loser;
  4174. authInfoAccess = CERT_DecodeAuthInfoAccessExtension(arena,
  4175. encodedAuthInfoAccess);
  4176. if (authInfoAccess == NULL)
  4177. goto loser;
  4178. for (i = 0; authInfoAccess[i] != NULL; i++) {
  4179. if (SECOID_FindOIDTag(&authInfoAccess[i]->method) == SEC_OID_PKIX_OCSP)
  4180. locname = authInfoAccess[i]->location;
  4181. }
  4182. /*
  4183. * If we found an AIA extension, but it did not include an OCSP method,
  4184. * that should look to our caller as if we did not find the extension
  4185. * at all, because it is only an OCSP method that we care about.
  4186. * So set the same error that would be set if the AIA extension was
  4187. * not there at all.
  4188. */
  4189. if (locname == NULL) {
  4190. PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION);
  4191. goto loser;
  4192. }
  4193. /*
  4194. * The following is just a pointer back into locname (i.e. not a copy);
  4195. * thus it should not be freed.
  4196. */
  4197. location = CERT_GetGeneralNameByType(locname, certURI, PR_FALSE);
  4198. if (location == NULL) {
  4199. /*
  4200. * XXX Appears that CERT_GetGeneralNameByType does not set an
  4201. * error if there is no name by that type. For lack of anything
  4202. * better, act as if the extension was not found. In the future
  4203. * this should probably be something more like the extension was
  4204. * badly formed.
  4205. */
  4206. PORT_SetError(SEC_ERROR_CERT_BAD_ACCESS_LOCATION);
  4207. goto loser;
  4208. }
  4209. /*
  4210. * That location is really a string, but it has a specified length
  4211. * without a null-terminator. We need a real string that does have
  4212. * a null-terminator, and we need a copy of it anyway to return to
  4213. * our caller -- so allocate and copy.
  4214. */
  4215. locURI = PORT_Alloc(location->len + 1);
  4216. if (locURI == NULL) {
  4217. goto loser;
  4218. }
  4219. PORT_Memcpy(locURI, location->data, location->len);
  4220. locURI[location->len] = '\0';
  4221. loser:
  4222. if (arena != NULL)
  4223. PORT_FreeArena(arena, PR_FALSE);
  4224. if (encodedAuthInfoAccess != NULL)
  4225. SECITEM_FreeItem(encodedAuthInfoAccess, PR_TRUE);
  4226. return locURI;
  4227. }
  4228. /*
  4229. * Figure out where we should go to find out the status of the given cert
  4230. * via OCSP. If allowed to use a default responder uri and a default
  4231. * responder is set up, then that is our answer.
  4232. * If not, see if the certificate has an Authority Information Access (AIA)
  4233. * extension for OCSP, and return the value of that. Otherwise return NULL.
  4234. * We also let our caller know whether or not the responder chosen was
  4235. * a default responder or not through the output variable isDefault;
  4236. * its value has no meaning unless a good (non-null) value is returned
  4237. * for the location.
  4238. *
  4239. * The result needs to be freed (PORT_Free) when no longer in use.
  4240. */
  4241. char *
  4242. ocsp_GetResponderLocation(CERTCertDBHandle *handle, CERTCertificate *cert,
  4243. PRBool canUseDefault, PRBool *isDefault)
  4244. {
  4245. ocspCheckingContext *ocspcx = NULL;
  4246. char *ocspUrl = NULL;
  4247. if (canUseDefault) {
  4248. ocspcx = ocsp_GetCheckingContext(handle);
  4249. }
  4250. if (ocspcx != NULL && ocspcx->useDefaultResponder) {
  4251. /*
  4252. * A default responder wins out, if specified.
  4253. * XXX Someday this may be a more complicated determination based
  4254. * on the cert's issuer. (That is, we could have different default
  4255. * responders configured for different issuers.)
  4256. */
  4257. PORT_Assert(ocspcx->defaultResponderURI != NULL);
  4258. *isDefault = PR_TRUE;
  4259. return (PORT_Strdup(ocspcx->defaultResponderURI));
  4260. }
  4261. /*
  4262. * No default responder set up, so go see if we can find an AIA
  4263. * extension that has a value for OCSP, and get the url from that.
  4264. */
  4265. *isDefault = PR_FALSE;
  4266. ocspUrl = CERT_GetOCSPAuthorityInfoAccessLocation(cert);
  4267. if (!ocspUrl) {
  4268. CERT_StringFromCertFcn altFcn;
  4269. PR_EnterMonitor(OCSP_Global.monitor);
  4270. altFcn = OCSP_Global.alternateOCSPAIAFcn;
  4271. PR_ExitMonitor(OCSP_Global.monitor);
  4272. if (altFcn) {
  4273. ocspUrl = (*altFcn)(cert);
  4274. if (ocspUrl)
  4275. *isDefault = PR_TRUE;
  4276. }
  4277. }
  4278. return ocspUrl;
  4279. }
  4280. /*
  4281. * Return SECSuccess if the cert was revoked *after* "time",
  4282. * SECFailure otherwise.
  4283. */
  4284. static SECStatus
  4285. ocsp_CertRevokedAfter(ocspRevokedInfo *revokedInfo, PRTime time)
  4286. {
  4287. PRTime revokedTime;
  4288. SECStatus rv;
  4289. rv = DER_GeneralizedTimeToTime(&revokedTime, &revokedInfo->revocationTime);
  4290. if (rv != SECSuccess)
  4291. return rv;
  4292. /*
  4293. * Set the error even if we will return success; someone might care.
  4294. */
  4295. PORT_SetError(SEC_ERROR_REVOKED_CERTIFICATE);
  4296. if (LL_CMP(revokedTime, >, time))
  4297. return SECSuccess;
  4298. return SECFailure;
  4299. }
  4300. /*
  4301. * See if the cert represented in the single response had a good status
  4302. * at the specified time.
  4303. */
  4304. SECStatus
  4305. ocsp_CertHasGoodStatus(ocspCertStatus *status, PRTime time)
  4306. {
  4307. SECStatus rv;
  4308. switch (status->certStatusType) {
  4309. case ocspCertStatus_good:
  4310. rv = SECSuccess;
  4311. break;
  4312. case ocspCertStatus_revoked:
  4313. rv = ocsp_CertRevokedAfter(status->certStatusInfo.revokedInfo, time);
  4314. break;
  4315. case ocspCertStatus_unknown:
  4316. PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_CERT);
  4317. rv = SECFailure;
  4318. break;
  4319. case ocspCertStatus_other:
  4320. default:
  4321. PORT_Assert(0);
  4322. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_RESPONSE);
  4323. rv = SECFailure;
  4324. break;
  4325. }
  4326. return rv;
  4327. }
  4328. static SECStatus
  4329. ocsp_SingleResponseCertHasGoodStatus(CERTOCSPSingleResponse *single,
  4330. PRTime time)
  4331. {
  4332. return ocsp_CertHasGoodStatus(single->certStatus, time);
  4333. }
  4334. /* SECFailure means the arguments were invalid.
  4335. * On SECSuccess, the out parameters contain the OCSP status.
  4336. * rvOcsp contains the overall result of the OCSP operation.
  4337. * Depending on input parameter ignoreGlobalOcspFailureSetting,
  4338. * a soft failure might be converted into *rvOcsp=SECSuccess.
  4339. * If the cached attempt to obtain OCSP information had resulted
  4340. * in a failure, missingResponseError shows the error code of
  4341. * that failure.
  4342. * cacheFreshness is ocspMissing if no entry was found,
  4343. * ocspFresh if a fresh entry was found, or
  4344. * ocspStale if a stale entry was found.
  4345. */
  4346. SECStatus
  4347. ocsp_GetCachedOCSPResponseStatus(CERTOCSPCertID *certID,
  4348. PRTime time,
  4349. PRBool ignoreGlobalOcspFailureSetting,
  4350. SECStatus *rvOcsp,
  4351. SECErrorCodes *missingResponseError,
  4352. OCSPFreshness *cacheFreshness)
  4353. {
  4354. OCSPCacheItem *cacheItem = NULL;
  4355. if (!certID || !missingResponseError || !rvOcsp || !cacheFreshness) {
  4356. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  4357. return SECFailure;
  4358. }
  4359. *rvOcsp = SECFailure;
  4360. *missingResponseError = 0;
  4361. *cacheFreshness = ocspMissing;
  4362. PR_EnterMonitor(OCSP_Global.monitor);
  4363. cacheItem = ocsp_FindCacheEntry(&OCSP_Global.cache, certID);
  4364. if (cacheItem) {
  4365. *cacheFreshness = ocsp_IsCacheItemFresh(cacheItem) ? ocspFresh
  4366. : ocspStale;
  4367. /* having an arena means, we have a cached certStatus */
  4368. if (cacheItem->certStatusArena) {
  4369. *rvOcsp = ocsp_CertHasGoodStatus(&cacheItem->certStatus, time);
  4370. if (*rvOcsp != SECSuccess) {
  4371. *missingResponseError = PORT_GetError();
  4372. }
  4373. } else {
  4374. /*
  4375. * No status cached, the previous attempt failed.
  4376. * If OCSP is required, we never decide based on a failed attempt
  4377. * However, if OCSP is optional, a recent OCSP failure is
  4378. * an allowed good state.
  4379. */
  4380. if (*cacheFreshness == ocspFresh &&
  4381. !ignoreGlobalOcspFailureSetting &&
  4382. OCSP_Global.ocspFailureMode ==
  4383. ocspMode_FailureIsNotAVerificationFailure) {
  4384. *rvOcsp = SECSuccess;
  4385. }
  4386. *missingResponseError = cacheItem->missingResponseError;
  4387. }
  4388. }
  4389. PR_ExitMonitor(OCSP_Global.monitor);
  4390. return SECSuccess;
  4391. }
  4392. PRBool
  4393. ocsp_FetchingFailureIsVerificationFailure(void)
  4394. {
  4395. PRBool isFailure;
  4396. PR_EnterMonitor(OCSP_Global.monitor);
  4397. isFailure =
  4398. OCSP_Global.ocspFailureMode == ocspMode_FailureIsVerificationFailure;
  4399. PR_ExitMonitor(OCSP_Global.monitor);
  4400. return isFailure;
  4401. }
  4402. /*
  4403. * FUNCTION: CERT_CheckOCSPStatus
  4404. * Checks the status of a certificate via OCSP. Will only check status for
  4405. * a certificate that has an AIA (Authority Information Access) extension
  4406. * for OCSP *or* when a "default responder" is specified and enabled.
  4407. * (If no AIA extension for OCSP and no default responder in place, the
  4408. * cert is considered to have a good status and SECSuccess is returned.)
  4409. * INPUTS:
  4410. * CERTCertDBHandle *handle
  4411. * certificate DB of the cert that is being checked
  4412. * CERTCertificate *cert
  4413. * the certificate being checked
  4414. * XXX in the long term also need a boolean parameter that specifies
  4415. * whether to check the cert chain, as well; for now we check only
  4416. * the leaf (the specified certificate)
  4417. * PRTime time
  4418. * time for which status is to be determined
  4419. * void *pwArg
  4420. * argument for password prompting, if needed
  4421. * RETURN:
  4422. * Returns SECSuccess if an approved OCSP responder "knows" the cert
  4423. * *and* returns a non-revoked status for it; SECFailure otherwise,
  4424. * with an error set describing the reason:
  4425. *
  4426. * SEC_ERROR_OCSP_BAD_HTTP_RESPONSE
  4427. * SEC_ERROR_OCSP_FUTURE_RESPONSE
  4428. * SEC_ERROR_OCSP_MALFORMED_REQUEST
  4429. * SEC_ERROR_OCSP_MALFORMED_RESPONSE
  4430. * SEC_ERROR_OCSP_OLD_RESPONSE
  4431. * SEC_ERROR_OCSP_REQUEST_NEEDS_SIG
  4432. * SEC_ERROR_OCSP_SERVER_ERROR
  4433. * SEC_ERROR_OCSP_TRY_SERVER_LATER
  4434. * SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST
  4435. * SEC_ERROR_OCSP_UNAUTHORIZED_RESPONSE
  4436. * SEC_ERROR_OCSP_UNKNOWN_CERT
  4437. * SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS
  4438. * SEC_ERROR_OCSP_UNKNOWN_RESPONSE_TYPE
  4439. *
  4440. * SEC_ERROR_BAD_SIGNATURE
  4441. * SEC_ERROR_CERT_BAD_ACCESS_LOCATION
  4442. * SEC_ERROR_INVALID_TIME
  4443. * SEC_ERROR_REVOKED_CERTIFICATE
  4444. * SEC_ERROR_UNKNOWN_ISSUER
  4445. * SEC_ERROR_UNKNOWN_SIGNER
  4446. *
  4447. * Other errors are any of the many possible failures in cert verification
  4448. * (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when
  4449. * verifying the signer's cert, or low-level problems (error allocating
  4450. * memory, error performing ASN.1 decoding, etc.).
  4451. */
  4452. SECStatus
  4453. CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert,
  4454. PRTime time, void *pwArg)
  4455. {
  4456. CERTOCSPCertID *certID;
  4457. PRBool certIDWasConsumed = PR_FALSE;
  4458. SECStatus rv;
  4459. SECStatus rvOcsp;
  4460. SECErrorCodes cachedErrorCode;
  4461. OCSPFreshness cachedResponseFreshness;
  4462. OCSP_TRACE_CERT(cert);
  4463. OCSP_TRACE_TIME("## requested validity time:", time);
  4464. certID = CERT_CreateOCSPCertID(cert, time);
  4465. if (!certID)
  4466. return SECFailure;
  4467. rv = ocsp_GetCachedOCSPResponseStatus(
  4468. certID, time, PR_FALSE, /* ignoreGlobalOcspFailureSetting */
  4469. &rvOcsp, &cachedErrorCode, &cachedResponseFreshness);
  4470. if (rv != SECSuccess) {
  4471. CERT_DestroyOCSPCertID(certID);
  4472. return SECFailure;
  4473. }
  4474. if (cachedResponseFreshness == ocspFresh) {
  4475. CERT_DestroyOCSPCertID(certID);
  4476. if (rvOcsp != SECSuccess) {
  4477. PORT_SetError(cachedErrorCode);
  4478. }
  4479. return rvOcsp;
  4480. }
  4481. rv = ocsp_GetOCSPStatusFromNetwork(handle, certID, cert, time, pwArg,
  4482. &certIDWasConsumed,
  4483. &rvOcsp);
  4484. if (rv != SECSuccess) {
  4485. PRErrorCode err = PORT_GetError();
  4486. if (ocsp_FetchingFailureIsVerificationFailure()) {
  4487. PORT_SetError(err);
  4488. rvOcsp = SECFailure;
  4489. } else if (cachedResponseFreshness == ocspStale &&
  4490. (cachedErrorCode == SEC_ERROR_OCSP_UNKNOWN_CERT ||
  4491. cachedErrorCode == SEC_ERROR_REVOKED_CERTIFICATE)) {
  4492. /* If we couldn't get a response for a certificate that the OCSP
  4493. * responder previously told us was bad, then assume it is still
  4494. * bad until we hear otherwise, as it is very unlikely that the
  4495. * certificate status has changed from "revoked" to "good" and it
  4496. * is also unlikely that the certificate status has changed from
  4497. * "unknown" to "good", except for some buggy OCSP responders.
  4498. */
  4499. PORT_SetError(cachedErrorCode);
  4500. rvOcsp = SECFailure;
  4501. } else {
  4502. rvOcsp = SECSuccess;
  4503. }
  4504. }
  4505. if (!certIDWasConsumed) {
  4506. CERT_DestroyOCSPCertID(certID);
  4507. }
  4508. return rvOcsp;
  4509. }
  4510. /*
  4511. * FUNCTION: CERT_CacheOCSPResponseFromSideChannel
  4512. * First, this function checks the OCSP cache to see if a good response
  4513. * for the given certificate already exists. If it does, then the function
  4514. * returns successfully.
  4515. *
  4516. * If not, then it validates that the given OCSP response is a valid,
  4517. * good response for the given certificate and inserts it into the
  4518. * cache.
  4519. *
  4520. * This function is intended for use when OCSP responses are provided via a
  4521. * side-channel, i.e. TLS OCSP stapling (a.k.a. the status_request extension).
  4522. *
  4523. * INPUTS:
  4524. * CERTCertDBHandle *handle
  4525. * certificate DB of the cert that is being checked
  4526. * CERTCertificate *cert
  4527. * the certificate being checked
  4528. * PRTime time
  4529. * time for which status is to be determined
  4530. * SECItem *encodedResponse
  4531. * the DER encoded bytes of the OCSP response
  4532. * void *pwArg
  4533. * argument for password prompting, if needed
  4534. * RETURN:
  4535. * SECSuccess if the cert was found in the cache, or if the OCSP response was
  4536. * found to be valid and inserted into the cache. SECFailure otherwise.
  4537. */
  4538. SECStatus
  4539. CERT_CacheOCSPResponseFromSideChannel(CERTCertDBHandle *handle,
  4540. CERTCertificate *cert,
  4541. PRTime time,
  4542. const SECItem *encodedResponse,
  4543. void *pwArg)
  4544. {
  4545. CERTOCSPCertID *certID = NULL;
  4546. PRBool certIDWasConsumed = PR_FALSE;
  4547. SECStatus rv = SECFailure;
  4548. SECStatus rvOcsp = SECFailure;
  4549. SECErrorCodes dummy_error_code; /* we ignore this */
  4550. CERTOCSPResponse *decodedResponse = NULL;
  4551. CERTOCSPSingleResponse *singleResponse = NULL;
  4552. OCSPFreshness freshness;
  4553. /* The OCSP cache can be in three states regarding this certificate:
  4554. * + Good (cached, timely, 'good' response, or revoked in the future)
  4555. * + Revoked (cached, timely, but doesn't fit in the last category)
  4556. * + Miss (no knowledge)
  4557. *
  4558. * Likewise, the side-channel information can be
  4559. * + Good (timely, 'good' response, or revoked in the future)
  4560. * + Revoked (timely, but doesn't fit in the last category)
  4561. * + Invalid (bad syntax, bad signature, not timely etc)
  4562. *
  4563. * The common case is that the cache result is Good and so is the
  4564. * side-channel information. We want to save processing time in this case
  4565. * so we say that any time we see a Good result from the cache we return
  4566. * early.
  4567. *
  4568. * Cache result
  4569. * | Good Revoked Miss
  4570. * ---+--------------------------------------------
  4571. * G | noop Cache more Cache it
  4572. * S | recent result
  4573. * i |
  4574. * d |
  4575. * e |
  4576. * R | noop Cache more Cache it
  4577. * C | recent result
  4578. * h |
  4579. * a |
  4580. * n |
  4581. * n I | noop Noop Noop
  4582. * e |
  4583. * l |
  4584. *
  4585. * When we fetch from the network we might choose to cache a negative
  4586. * result when the response is invalid. This saves us hammering, uselessly,
  4587. * at a broken responder. However, side channels are commonly attacker
  4588. * controlled and so we must not cache a negative result for an Invalid
  4589. * side channel.
  4590. */
  4591. if (!cert || !encodedResponse) {
  4592. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  4593. return SECFailure;
  4594. }
  4595. certID = CERT_CreateOCSPCertID(cert, time);
  4596. if (!certID)
  4597. return SECFailure;
  4598. /* We pass PR_TRUE for ignoreGlobalOcspFailureSetting so that a cached
  4599. * error entry is not interpreted as being a 'Good' entry here.
  4600. */
  4601. rv = ocsp_GetCachedOCSPResponseStatus(
  4602. certID, time, PR_TRUE, /* ignoreGlobalOcspFailureSetting */
  4603. &rvOcsp, &dummy_error_code, &freshness);
  4604. if (rv == SECSuccess && rvOcsp == SECSuccess && freshness == ocspFresh) {
  4605. /* The cached value is good. We don't want to waste time validating
  4606. * this OCSP response. This is the first column in the table above. */
  4607. CERT_DestroyOCSPCertID(certID);
  4608. return rv;
  4609. }
  4610. /* The logic for caching the more recent response is handled in
  4611. * ocsp_CacheSingleResponse. */
  4612. rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert,
  4613. time, pwArg,
  4614. encodedResponse,
  4615. &decodedResponse,
  4616. &singleResponse);
  4617. if (rv == SECSuccess) {
  4618. rvOcsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time);
  4619. /* Cache any valid singleResponse, regardless of status. */
  4620. ocsp_CacheSingleResponse(certID, singleResponse, &certIDWasConsumed);
  4621. }
  4622. if (decodedResponse) {
  4623. CERT_DestroyOCSPResponse(decodedResponse);
  4624. }
  4625. if (!certIDWasConsumed) {
  4626. CERT_DestroyOCSPCertID(certID);
  4627. }
  4628. return rv == SECSuccess ? rvOcsp : rv;
  4629. }
  4630. /*
  4631. * Status in *certIDWasConsumed will always be correct, regardless of
  4632. * return value.
  4633. */
  4634. static SECStatus
  4635. ocsp_GetOCSPStatusFromNetwork(CERTCertDBHandle *handle,
  4636. CERTOCSPCertID *certID,
  4637. CERTCertificate *cert,
  4638. PRTime time,
  4639. void *pwArg,
  4640. PRBool *certIDWasConsumed,
  4641. SECStatus *rv_ocsp)
  4642. {
  4643. char *location = NULL;
  4644. PRBool locationIsDefault;
  4645. SECItem *encodedResponse = NULL;
  4646. CERTOCSPRequest *request = NULL;
  4647. SECStatus rv = SECFailure;
  4648. CERTOCSPResponse *decodedResponse = NULL;
  4649. CERTOCSPSingleResponse *singleResponse = NULL;
  4650. enum { stageGET,
  4651. stagePOST } currentStage;
  4652. PRBool retry = PR_FALSE;
  4653. if (!certIDWasConsumed || !rv_ocsp) {
  4654. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  4655. return SECFailure;
  4656. }
  4657. *certIDWasConsumed = PR_FALSE;
  4658. *rv_ocsp = SECFailure;
  4659. if (!OCSP_Global.monitor) {
  4660. PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  4661. return SECFailure;
  4662. }
  4663. PR_EnterMonitor(OCSP_Global.monitor);
  4664. if (OCSP_Global.forcePost) {
  4665. currentStage = stagePOST;
  4666. } else {
  4667. currentStage = stageGET;
  4668. }
  4669. PR_ExitMonitor(OCSP_Global.monitor);
  4670. /*
  4671. * The first thing we need to do is find the location of the responder.
  4672. * This will be the value of the default responder (if enabled), else
  4673. * it will come out of the AIA extension in the cert (if present).
  4674. * If we have no such location, then this cert does not "deserve" to
  4675. * be checked -- that is, we consider it a success and just return.
  4676. * The way we tell that is by looking at the error number to see if
  4677. * the problem was no AIA extension was found; any other error was
  4678. * a true failure that we unfortunately have to treat as an overall
  4679. * failure here.
  4680. */
  4681. location = ocsp_GetResponderLocation(handle, cert, PR_TRUE,
  4682. &locationIsDefault);
  4683. if (location == NULL) {
  4684. int err = PORT_GetError();
  4685. if (err == SEC_ERROR_EXTENSION_NOT_FOUND ||
  4686. err == SEC_ERROR_CERT_BAD_ACCESS_LOCATION) {
  4687. PORT_SetError(0);
  4688. *rv_ocsp = SECSuccess;
  4689. return SECSuccess;
  4690. }
  4691. return SECFailure;
  4692. }
  4693. /*
  4694. * XXX In the fullness of time, we will want/need to handle a
  4695. * certificate chain. This will be done either when a new parameter
  4696. * tells us to, or some configuration variable tells us to. In any
  4697. * case, handling it is complicated because we may need to send as
  4698. * many requests (and receive as many responses) as we have certs
  4699. * in the chain. If we are going to talk to a default responder,
  4700. * and we only support one default responder, we can put all of the
  4701. * certs together into one request. Otherwise, we must break them up
  4702. * into multiple requests. (Even if all of the requests will go to
  4703. * the same location, the signature on each response will be different,
  4704. * because each issuer is different. Carefully read the OCSP spec
  4705. * if you do not understand this.)
  4706. */
  4707. /*
  4708. * XXX If/when signing of requests is supported, that second NULL
  4709. * should be changed to be the signer certificate. Not sure if that
  4710. * should be passed into this function or retrieved via some operation
  4711. * on the handle/context.
  4712. */
  4713. do {
  4714. const char *method;
  4715. PRBool validResponseWithAccurateInfo = PR_FALSE;
  4716. retry = PR_FALSE;
  4717. *rv_ocsp = SECFailure;
  4718. if (currentStage == stageGET) {
  4719. method = "GET";
  4720. } else {
  4721. PORT_Assert(currentStage == stagePOST);
  4722. method = "POST";
  4723. }
  4724. encodedResponse =
  4725. ocsp_GetEncodedOCSPResponseForSingleCert(NULL, certID, cert,
  4726. location, method,
  4727. time, locationIsDefault,
  4728. pwArg, &request);
  4729. if (encodedResponse) {
  4730. rv = ocsp_GetDecodedVerifiedSingleResponseForID(handle, certID, cert,
  4731. time, pwArg,
  4732. encodedResponse,
  4733. &decodedResponse,
  4734. &singleResponse);
  4735. if (rv == SECSuccess) {
  4736. switch (singleResponse->certStatus->certStatusType) {
  4737. case ocspCertStatus_good:
  4738. case ocspCertStatus_revoked:
  4739. validResponseWithAccurateInfo = PR_TRUE;
  4740. break;
  4741. default:
  4742. break;
  4743. }
  4744. *rv_ocsp = ocsp_SingleResponseCertHasGoodStatus(singleResponse, time);
  4745. }
  4746. }
  4747. if (currentStage == stageGET) {
  4748. /* only accept GET response if good or revoked */
  4749. if (validResponseWithAccurateInfo) {
  4750. ocsp_CacheSingleResponse(certID, singleResponse,
  4751. certIDWasConsumed);
  4752. } else {
  4753. retry = PR_TRUE;
  4754. currentStage = stagePOST;
  4755. }
  4756. } else {
  4757. /* cache the POST respone, regardless of status */
  4758. if (!singleResponse) {
  4759. cert_RememberOCSPProcessingFailure(certID, certIDWasConsumed);
  4760. } else {
  4761. ocsp_CacheSingleResponse(certID, singleResponse,
  4762. certIDWasConsumed);
  4763. }
  4764. }
  4765. if (encodedResponse) {
  4766. SECITEM_FreeItem(encodedResponse, PR_TRUE);
  4767. encodedResponse = NULL;
  4768. }
  4769. if (request) {
  4770. CERT_DestroyOCSPRequest(request);
  4771. request = NULL;
  4772. }
  4773. if (decodedResponse) {
  4774. CERT_DestroyOCSPResponse(decodedResponse);
  4775. decodedResponse = NULL;
  4776. }
  4777. singleResponse = NULL;
  4778. } while (retry);
  4779. PORT_Free(location);
  4780. return rv;
  4781. }
  4782. /*
  4783. * FUNCTION: ocsp_GetDecodedVerifiedSingleResponseForID
  4784. * This function decodes an OCSP response and checks for a valid response
  4785. * concerning the given certificate.
  4786. *
  4787. * Note: a 'valid' response is one that parses successfully, is not an OCSP
  4788. * exception (see RFC 2560 Section 2.3), is correctly signed and is current.
  4789. * A 'good' response is a valid response that attests that the certificate
  4790. * is not currently revoked (see RFC 2560 Section 2.2).
  4791. *
  4792. * INPUTS:
  4793. * CERTCertDBHandle *handle
  4794. * certificate DB of the cert that is being checked
  4795. * CERTOCSPCertID *certID
  4796. * the cert ID corresponding to |cert|
  4797. * CERTCertificate *cert
  4798. * the certificate being checked
  4799. * PRTime time
  4800. * time for which status is to be determined
  4801. * void *pwArg
  4802. * the opaque argument to the password prompting function.
  4803. * SECItem *encodedResponse
  4804. * the DER encoded bytes of the OCSP response
  4805. * CERTOCSPResponse **pDecodedResponse
  4806. * (output) The caller must ALWAYS check for this output parameter,
  4807. * and if it's non-null, must destroy it using CERT_DestroyOCSPResponse.
  4808. * CERTOCSPSingleResponse **pSingle
  4809. * (output) on success, this points to the single response that corresponds
  4810. * to the certID parameter. Points to the inside of pDecodedResponse.
  4811. * It isn't a copy, don't free it.
  4812. * RETURN:
  4813. * SECSuccess iff the response is valid.
  4814. */
  4815. static SECStatus
  4816. ocsp_GetDecodedVerifiedSingleResponseForID(CERTCertDBHandle *handle,
  4817. CERTOCSPCertID *certID,
  4818. CERTCertificate *cert,
  4819. PRTime time,
  4820. void *pwArg,
  4821. const SECItem *encodedResponse,
  4822. CERTOCSPResponse **pDecodedResponse,
  4823. CERTOCSPSingleResponse **pSingle)
  4824. {
  4825. CERTCertificate *signerCert = NULL;
  4826. CERTCertificate *issuerCert = NULL;
  4827. SECStatus rv = SECFailure;
  4828. if (!pSingle || !pDecodedResponse) {
  4829. return SECFailure;
  4830. }
  4831. *pSingle = NULL;
  4832. *pDecodedResponse = CERT_DecodeOCSPResponse(encodedResponse);
  4833. if (!*pDecodedResponse) {
  4834. return SECFailure;
  4835. }
  4836. /*
  4837. * Okay, we at least have a response that *looks* like a response!
  4838. * Now see if the overall response status value is good or not.
  4839. * If not, we set an error and give up. (It means that either the
  4840. * server had a problem, or it didn't like something about our
  4841. * request. Either way there is nothing to do but give up.)
  4842. * Otherwise, we continue to find the actual per-cert status
  4843. * in the response.
  4844. */
  4845. if (CERT_GetOCSPResponseStatus(*pDecodedResponse) != SECSuccess) {
  4846. goto loser;
  4847. }
  4848. /*
  4849. * If we've made it this far, we expect a response with a good signature.
  4850. * So, check for that.
  4851. */
  4852. issuerCert = CERT_FindCertIssuer(cert, time, certUsageAnyCA);
  4853. rv = CERT_VerifyOCSPResponseSignature(*pDecodedResponse, handle, pwArg,
  4854. &signerCert, issuerCert);
  4855. if (rv != SECSuccess) {
  4856. goto loser;
  4857. }
  4858. PORT_Assert(signerCert != NULL); /* internal consistency check */
  4859. /* XXX probably should set error, return failure if signerCert is null */
  4860. /*
  4861. * Again, we are only doing one request for one cert.
  4862. * XXX When we handle cert chains, the following code will obviously
  4863. * have to be modified, in coordation with the code above that will
  4864. * have to determine how to make multiple requests, etc.
  4865. */
  4866. rv = ocsp_GetVerifiedSingleResponseForCertID(handle, *pDecodedResponse, certID,
  4867. signerCert, time, pSingle);
  4868. loser:
  4869. if (issuerCert != NULL)
  4870. CERT_DestroyCertificate(issuerCert);
  4871. if (signerCert != NULL)
  4872. CERT_DestroyCertificate(signerCert);
  4873. return rv;
  4874. }
  4875. /*
  4876. * FUNCTION: ocsp_CacheSingleResponse
  4877. * This function requires that the caller has checked that the response
  4878. * is valid and verified.
  4879. * The (positive or negative) valid response will be used to update the cache.
  4880. * INPUTS:
  4881. * CERTOCSPCertID *certID
  4882. * the cert ID corresponding to |cert|
  4883. * PRBool *certIDWasConsumed
  4884. * (output) on return, this is true iff |certID| was consumed by this
  4885. * function.
  4886. */
  4887. void
  4888. ocsp_CacheSingleResponse(CERTOCSPCertID *certID,
  4889. CERTOCSPSingleResponse *single,
  4890. PRBool *certIDWasConsumed)
  4891. {
  4892. if (single != NULL) {
  4893. PR_EnterMonitor(OCSP_Global.monitor);
  4894. if (OCSP_Global.maxCacheEntries >= 0) {
  4895. ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, single,
  4896. certIDWasConsumed);
  4897. /* ignore cache update failures */
  4898. }
  4899. PR_ExitMonitor(OCSP_Global.monitor);
  4900. }
  4901. }
  4902. SECStatus
  4903. ocsp_GetVerifiedSingleResponseForCertID(CERTCertDBHandle *handle,
  4904. CERTOCSPResponse *response,
  4905. CERTOCSPCertID *certID,
  4906. CERTCertificate *signerCert,
  4907. PRTime time,
  4908. CERTOCSPSingleResponse
  4909. **pSingleResponse)
  4910. {
  4911. SECStatus rv;
  4912. ocspResponseData *responseData;
  4913. PRTime producedAt;
  4914. CERTOCSPSingleResponse *single;
  4915. /*
  4916. * The ResponseData part is the real guts of the response.
  4917. */
  4918. responseData = ocsp_GetResponseData(response, NULL);
  4919. if (responseData == NULL) {
  4920. rv = SECFailure;
  4921. goto loser;
  4922. }
  4923. /*
  4924. * There is one producedAt time for the entire response (and a separate
  4925. * thisUpdate time for each individual single response). We need to
  4926. * compare them, so get the overall time to pass into the check of each
  4927. * single response.
  4928. */
  4929. rv = DER_GeneralizedTimeToTime(&producedAt, &responseData->producedAt);
  4930. if (rv != SECSuccess)
  4931. goto loser;
  4932. single = ocsp_GetSingleResponseForCertID(responseData->responses,
  4933. handle, certID);
  4934. if (single == NULL) {
  4935. rv = SECFailure;
  4936. goto loser;
  4937. }
  4938. rv = ocsp_VerifySingleResponse(single, handle, signerCert, producedAt);
  4939. if (rv != SECSuccess)
  4940. goto loser;
  4941. *pSingleResponse = single;
  4942. loser:
  4943. return rv;
  4944. }
  4945. SECStatus
  4946. CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle,
  4947. CERTOCSPResponse *response,
  4948. CERTOCSPCertID *certID,
  4949. CERTCertificate *signerCert,
  4950. PRTime time)
  4951. {
  4952. /*
  4953. * We do not update the cache, because:
  4954. *
  4955. * CERT_GetOCSPStatusForCertID is an old exported API that was introduced
  4956. * before the OCSP cache got implemented.
  4957. *
  4958. * The implementation of helper function cert_ProcessOCSPResponse
  4959. * requires the ability to transfer ownership of the the given certID to
  4960. * the cache. The external API doesn't allow us to prevent the caller from
  4961. * destroying the certID. We don't have the original certificate available,
  4962. * therefore we are unable to produce another certID object (that could
  4963. * be stored in the cache).
  4964. *
  4965. * Should we ever implement code to produce a deep copy of certID,
  4966. * then this could be changed to allow updating the cache.
  4967. * The duplication would have to be done in
  4968. * cert_ProcessOCSPResponse, if the out parameter to indicate
  4969. * a transfer of ownership is NULL.
  4970. */
  4971. return cert_ProcessOCSPResponse(handle, response, certID,
  4972. signerCert, time,
  4973. NULL, NULL);
  4974. }
  4975. /*
  4976. * The first 5 parameters match the definition of CERT_GetOCSPStatusForCertID.
  4977. */
  4978. SECStatus
  4979. cert_ProcessOCSPResponse(CERTCertDBHandle *handle,
  4980. CERTOCSPResponse *response,
  4981. CERTOCSPCertID *certID,
  4982. CERTCertificate *signerCert,
  4983. PRTime time,
  4984. PRBool *certIDWasConsumed,
  4985. SECStatus *cacheUpdateStatus)
  4986. {
  4987. SECStatus rv;
  4988. SECStatus rv_cache = SECSuccess;
  4989. CERTOCSPSingleResponse *single = NULL;
  4990. rv = ocsp_GetVerifiedSingleResponseForCertID(handle, response, certID,
  4991. signerCert, time, &single);
  4992. if (rv == SECSuccess) {
  4993. /*
  4994. * Check whether the status says revoked, and if so
  4995. * how that compares to the time value passed into this routine.
  4996. */
  4997. rv = ocsp_SingleResponseCertHasGoodStatus(single, time);
  4998. }
  4999. if (certIDWasConsumed) {
  5000. /*
  5001. * We don't have copy-of-certid implemented. In order to update
  5002. * the cache, the caller must supply an out variable
  5003. * certIDWasConsumed, allowing us to return ownership status.
  5004. */
  5005. PR_EnterMonitor(OCSP_Global.monitor);
  5006. if (OCSP_Global.maxCacheEntries >= 0) {
  5007. /* single == NULL means: remember response failure */
  5008. rv_cache =
  5009. ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID,
  5010. single, certIDWasConsumed);
  5011. }
  5012. PR_ExitMonitor(OCSP_Global.monitor);
  5013. if (cacheUpdateStatus) {
  5014. *cacheUpdateStatus = rv_cache;
  5015. }
  5016. }
  5017. return rv;
  5018. }
  5019. SECStatus
  5020. cert_RememberOCSPProcessingFailure(CERTOCSPCertID *certID,
  5021. PRBool *certIDWasConsumed)
  5022. {
  5023. SECStatus rv = SECSuccess;
  5024. PR_EnterMonitor(OCSP_Global.monitor);
  5025. if (OCSP_Global.maxCacheEntries >= 0) {
  5026. rv = ocsp_CreateOrUpdateCacheEntry(&OCSP_Global.cache, certID, NULL,
  5027. certIDWasConsumed);
  5028. }
  5029. PR_ExitMonitor(OCSP_Global.monitor);
  5030. return rv;
  5031. }
  5032. /*
  5033. * Disable status checking and destroy related structures/data.
  5034. */
  5035. static SECStatus
  5036. ocsp_DestroyStatusChecking(CERTStatusConfig *statusConfig)
  5037. {
  5038. ocspCheckingContext *statusContext;
  5039. /*
  5040. * Disable OCSP checking
  5041. */
  5042. statusConfig->statusChecker = NULL;
  5043. statusContext = statusConfig->statusContext;
  5044. PORT_Assert(statusContext != NULL);
  5045. if (statusContext == NULL)
  5046. return SECFailure;
  5047. if (statusContext->defaultResponderURI != NULL)
  5048. PORT_Free(statusContext->defaultResponderURI);
  5049. if (statusContext->defaultResponderNickname != NULL)
  5050. PORT_Free(statusContext->defaultResponderNickname);
  5051. PORT_Free(statusContext);
  5052. statusConfig->statusContext = NULL;
  5053. PORT_Free(statusConfig);
  5054. return SECSuccess;
  5055. }
  5056. /*
  5057. * FUNCTION: CERT_DisableOCSPChecking
  5058. * Turns off OCSP checking for the given certificate database.
  5059. * This routine disables OCSP checking. Though it will return
  5060. * SECFailure if OCSP checking is not enabled, it is "safe" to
  5061. * call it that way and just ignore the return value, if it is
  5062. * easier to just call it than to "remember" whether it is enabled.
  5063. * INPUTS:
  5064. * CERTCertDBHandle *handle
  5065. * Certificate database for which OCSP checking will be disabled.
  5066. * RETURN:
  5067. * Returns SECFailure if an error occurred (usually means that OCSP
  5068. * checking was not enabled or status contexts were not initialized --
  5069. * error set will be SEC_ERROR_OCSP_NOT_ENABLED); SECSuccess otherwise.
  5070. */
  5071. SECStatus
  5072. CERT_DisableOCSPChecking(CERTCertDBHandle *handle)
  5073. {
  5074. CERTStatusConfig *statusConfig;
  5075. ocspCheckingContext *statusContext;
  5076. if (handle == NULL) {
  5077. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  5078. return SECFailure;
  5079. }
  5080. statusConfig = CERT_GetStatusConfig(handle);
  5081. statusContext = ocsp_GetCheckingContext(handle);
  5082. if (statusContext == NULL)
  5083. return SECFailure;
  5084. if (statusConfig->statusChecker != CERT_CheckOCSPStatus) {
  5085. /*
  5086. * Status configuration is present, but either not currently
  5087. * enabled or not for OCSP.
  5088. */
  5089. PORT_SetError(SEC_ERROR_OCSP_NOT_ENABLED);
  5090. return SECFailure;
  5091. }
  5092. /* cache no longer necessary */
  5093. CERT_ClearOCSPCache();
  5094. /*
  5095. * This is how we disable status checking. Everything else remains
  5096. * in place in case we are enabled again.
  5097. */
  5098. statusConfig->statusChecker = NULL;
  5099. return SECSuccess;
  5100. }
  5101. /*
  5102. * Allocate and initialize the informational structures for status checking.
  5103. * This is done when some configuration of OCSP is being done or when OCSP
  5104. * checking is being turned on, whichever comes first.
  5105. */
  5106. static SECStatus
  5107. ocsp_InitStatusChecking(CERTCertDBHandle *handle)
  5108. {
  5109. CERTStatusConfig *statusConfig = NULL;
  5110. ocspCheckingContext *statusContext = NULL;
  5111. PORT_Assert(CERT_GetStatusConfig(handle) == NULL);
  5112. if (CERT_GetStatusConfig(handle) != NULL) {
  5113. /* XXX or call statusConfig->statusDestroy and continue? */
  5114. return SECFailure;
  5115. }
  5116. statusConfig = PORT_ZNew(CERTStatusConfig);
  5117. if (statusConfig == NULL)
  5118. goto loser;
  5119. statusContext = PORT_ZNew(ocspCheckingContext);
  5120. if (statusContext == NULL)
  5121. goto loser;
  5122. statusConfig->statusDestroy = ocsp_DestroyStatusChecking;
  5123. statusConfig->statusContext = statusContext;
  5124. CERT_SetStatusConfig(handle, statusConfig);
  5125. return SECSuccess;
  5126. loser:
  5127. if (statusConfig != NULL)
  5128. PORT_Free(statusConfig);
  5129. return SECFailure;
  5130. }
  5131. /*
  5132. * FUNCTION: CERT_EnableOCSPChecking
  5133. * Turns on OCSP checking for the given certificate database.
  5134. * INPUTS:
  5135. * CERTCertDBHandle *handle
  5136. * Certificate database for which OCSP checking will be enabled.
  5137. * RETURN:
  5138. * Returns SECFailure if an error occurred (likely only problem
  5139. * allocating memory); SECSuccess otherwise.
  5140. */
  5141. SECStatus
  5142. CERT_EnableOCSPChecking(CERTCertDBHandle *handle)
  5143. {
  5144. CERTStatusConfig *statusConfig;
  5145. SECStatus rv;
  5146. if (handle == NULL) {
  5147. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  5148. return SECFailure;
  5149. }
  5150. statusConfig = CERT_GetStatusConfig(handle);
  5151. if (statusConfig == NULL) {
  5152. rv = ocsp_InitStatusChecking(handle);
  5153. if (rv != SECSuccess)
  5154. return rv;
  5155. /* Get newly established value */
  5156. statusConfig = CERT_GetStatusConfig(handle);
  5157. PORT_Assert(statusConfig != NULL);
  5158. }
  5159. /*
  5160. * Setting the checker function is what really enables the checking
  5161. * when each cert verification is done.
  5162. */
  5163. statusConfig->statusChecker = CERT_CheckOCSPStatus;
  5164. return SECSuccess;
  5165. }
  5166. /*
  5167. * FUNCTION: CERT_SetOCSPDefaultResponder
  5168. * Specify the location and cert of the default responder.
  5169. * If OCSP checking is already enabled *and* use of a default responder
  5170. * is also already enabled, all OCSP checking from now on will go directly
  5171. * to the specified responder. If OCSP checking is not enabled, or if
  5172. * it is but use of a default responder is not enabled, the information
  5173. * will be recorded and take effect whenever both are enabled.
  5174. * INPUTS:
  5175. * CERTCertDBHandle *handle
  5176. * Cert database on which OCSP checking should use the default responder.
  5177. * char *url
  5178. * The location of the default responder (e.g. "http://foo.com:80/ocsp")
  5179. * Note that the location will not be tested until the first attempt
  5180. * to send a request there.
  5181. * char *name
  5182. * The nickname of the cert to trust (expected) to sign the OCSP responses.
  5183. * If the corresponding cert cannot be found, SECFailure is returned.
  5184. * RETURN:
  5185. * Returns SECFailure if an error occurred; SECSuccess otherwise.
  5186. * The most likely error is that the cert for "name" could not be found
  5187. * (probably SEC_ERROR_UNKNOWN_CERT). Other errors are low-level (no memory,
  5188. * bad database, etc.).
  5189. */
  5190. SECStatus
  5191. CERT_SetOCSPDefaultResponder(CERTCertDBHandle *handle,
  5192. const char *url, const char *name)
  5193. {
  5194. CERTCertificate *cert;
  5195. ocspCheckingContext *statusContext;
  5196. char *url_copy = NULL;
  5197. char *name_copy = NULL;
  5198. SECStatus rv;
  5199. if (handle == NULL || url == NULL || name == NULL) {
  5200. /*
  5201. * XXX When interface is exported, probably want better errors;
  5202. * perhaps different one for each parameter.
  5203. */
  5204. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  5205. return SECFailure;
  5206. }
  5207. /*
  5208. * Find the certificate for the specified nickname. Do this first
  5209. * because it seems the most likely to fail.
  5210. *
  5211. * XXX Shouldn't need that cast if the FindCertByNickname interface
  5212. * used const to convey that it does not modify the name. Maybe someday.
  5213. */
  5214. cert = CERT_FindCertByNickname(handle, (char *)name);
  5215. if (cert == NULL) {
  5216. /*
  5217. * look for the cert on an external token.
  5218. */
  5219. cert = PK11_FindCertFromNickname((char *)name, NULL);
  5220. }
  5221. if (cert == NULL)
  5222. return SECFailure;
  5223. /*
  5224. * Make a copy of the url and nickname.
  5225. */
  5226. url_copy = PORT_Strdup(url);
  5227. name_copy = PORT_Strdup(name);
  5228. if (url_copy == NULL || name_copy == NULL) {
  5229. rv = SECFailure;
  5230. goto loser;
  5231. }
  5232. statusContext = ocsp_GetCheckingContext(handle);
  5233. /*
  5234. * Allocate and init the context if it doesn't already exist.
  5235. */
  5236. if (statusContext == NULL) {
  5237. rv = ocsp_InitStatusChecking(handle);
  5238. if (rv != SECSuccess)
  5239. goto loser;
  5240. statusContext = ocsp_GetCheckingContext(handle);
  5241. PORT_Assert(statusContext != NULL); /* extreme paranoia */
  5242. }
  5243. /*
  5244. * Note -- we do not touch the status context until after all of
  5245. * the steps which could cause errors. If something goes wrong,
  5246. * we want to leave things as they were.
  5247. */
  5248. /*
  5249. * Get rid of old url and name if there.
  5250. */
  5251. if (statusContext->defaultResponderNickname != NULL)
  5252. PORT_Free(statusContext->defaultResponderNickname);
  5253. if (statusContext->defaultResponderURI != NULL)
  5254. PORT_Free(statusContext->defaultResponderURI);
  5255. /*
  5256. * And replace them with the new ones.
  5257. */
  5258. statusContext->defaultResponderURI = url_copy;
  5259. statusContext->defaultResponderNickname = name_copy;
  5260. /*
  5261. * If there was already a cert in place, get rid of it and replace it.
  5262. * Otherwise, we are not currently enabled, so we don't want to save it;
  5263. * it will get re-found and set whenever use of a default responder is
  5264. * enabled.
  5265. */
  5266. if (statusContext->defaultResponderCert != NULL) {
  5267. CERT_DestroyCertificate(statusContext->defaultResponderCert);
  5268. statusContext->defaultResponderCert = cert;
  5269. /*OCSP enabled, switching responder: clear cache*/
  5270. CERT_ClearOCSPCache();
  5271. } else {
  5272. PORT_Assert(statusContext->useDefaultResponder == PR_FALSE);
  5273. CERT_DestroyCertificate(cert);
  5274. /*OCSP currently not enabled, no need to clear cache*/
  5275. }
  5276. return SECSuccess;
  5277. loser:
  5278. CERT_DestroyCertificate(cert);
  5279. if (url_copy != NULL)
  5280. PORT_Free(url_copy);
  5281. if (name_copy != NULL)
  5282. PORT_Free(name_copy);
  5283. return rv;
  5284. }
  5285. /*
  5286. * FUNCTION: CERT_EnableOCSPDefaultResponder
  5287. * Turns on use of a default responder when OCSP checking.
  5288. * If OCSP checking is already enabled, this will make subsequent checks
  5289. * go directly to the default responder. (The location of the responder
  5290. * and the nickname of the responder cert must already be specified.)
  5291. * If OCSP checking is not enabled, this will be recorded and take effect
  5292. * whenever it is enabled.
  5293. * INPUTS:
  5294. * CERTCertDBHandle *handle
  5295. * Cert database on which OCSP checking should use the default responder.
  5296. * RETURN:
  5297. * Returns SECFailure if an error occurred; SECSuccess otherwise.
  5298. * No errors are especially likely unless the caller did not previously
  5299. * perform a successful call to SetOCSPDefaultResponder (in which case
  5300. * the error set will be SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER).
  5301. */
  5302. SECStatus
  5303. CERT_EnableOCSPDefaultResponder(CERTCertDBHandle *handle)
  5304. {
  5305. ocspCheckingContext *statusContext;
  5306. CERTCertificate *cert;
  5307. SECStatus rv;
  5308. SECCertificateUsage usage;
  5309. if (handle == NULL) {
  5310. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  5311. return SECFailure;
  5312. }
  5313. statusContext = ocsp_GetCheckingContext(handle);
  5314. if (statusContext == NULL) {
  5315. /*
  5316. * Strictly speaking, the error already set is "correct",
  5317. * but cover over it with one more helpful in this context.
  5318. */
  5319. PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER);
  5320. return SECFailure;
  5321. }
  5322. if (statusContext->defaultResponderURI == NULL) {
  5323. PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER);
  5324. return SECFailure;
  5325. }
  5326. if (statusContext->defaultResponderNickname == NULL) {
  5327. PORT_SetError(SEC_ERROR_OCSP_NO_DEFAULT_RESPONDER);
  5328. return SECFailure;
  5329. }
  5330. /*
  5331. * Find the cert for the nickname.
  5332. */
  5333. cert = CERT_FindCertByNickname(handle,
  5334. statusContext->defaultResponderNickname);
  5335. if (cert == NULL) {
  5336. cert = PK11_FindCertFromNickname(statusContext->defaultResponderNickname,
  5337. NULL);
  5338. }
  5339. /*
  5340. * We should never have trouble finding the cert, because its
  5341. * existence should have been proven by SetOCSPDefaultResponder.
  5342. */
  5343. PORT_Assert(cert != NULL);
  5344. if (cert == NULL)
  5345. return SECFailure;
  5346. /*
  5347. * Supplied cert should at least have a signing capability in order for us
  5348. * to use it as a trusted responder cert. Ability to sign is guaranteed if
  5349. * cert is validated to have any set of the usages below.
  5350. */
  5351. rv = CERT_VerifyCertificateNow(handle, cert, PR_TRUE,
  5352. certificateUsageCheckAllUsages,
  5353. NULL, &usage);
  5354. if (rv != SECSuccess || (usage & (certificateUsageSSLClient | certificateUsageSSLServer | certificateUsageSSLServerWithStepUp | certificateUsageEmailSigner | certificateUsageObjectSigner | certificateUsageStatusResponder | certificateUsageSSLCA)) == 0) {
  5355. PORT_SetError(SEC_ERROR_OCSP_RESPONDER_CERT_INVALID);
  5356. return SECFailure;
  5357. }
  5358. /*
  5359. * And hang onto it.
  5360. */
  5361. statusContext->defaultResponderCert = cert;
  5362. /* we don't allow a mix of cache entries from different responders */
  5363. CERT_ClearOCSPCache();
  5364. /*
  5365. * Finally, record the fact that we now have a default responder enabled.
  5366. */
  5367. statusContext->useDefaultResponder = PR_TRUE;
  5368. return SECSuccess;
  5369. }
  5370. /*
  5371. * FUNCTION: CERT_DisableOCSPDefaultResponder
  5372. * Turns off use of a default responder when OCSP checking.
  5373. * (Does nothing if use of a default responder is not enabled.)
  5374. * INPUTS:
  5375. * CERTCertDBHandle *handle
  5376. * Cert database on which OCSP checking should stop using a default
  5377. * responder.
  5378. * RETURN:
  5379. * Returns SECFailure if an error occurred; SECSuccess otherwise.
  5380. * Errors very unlikely (like random memory corruption...).
  5381. */
  5382. SECStatus
  5383. CERT_DisableOCSPDefaultResponder(CERTCertDBHandle *handle)
  5384. {
  5385. CERTStatusConfig *statusConfig;
  5386. ocspCheckingContext *statusContext;
  5387. CERTCertificate *tmpCert;
  5388. if (handle == NULL) {
  5389. PORT_SetError(SEC_ERROR_INVALID_ARGS);
  5390. return SECFailure;
  5391. }
  5392. statusConfig = CERT_GetStatusConfig(handle);
  5393. if (statusConfig == NULL)
  5394. return SECSuccess;
  5395. statusContext = ocsp_GetCheckingContext(handle);
  5396. PORT_Assert(statusContext != NULL);
  5397. if (statusContext == NULL)
  5398. return SECFailure;
  5399. tmpCert = statusContext->defaultResponderCert;
  5400. if (tmpCert) {
  5401. statusContext->defaultResponderCert = NULL;
  5402. CERT_DestroyCertificate(tmpCert);
  5403. /* we don't allow a mix of cache entries from different responders */
  5404. CERT_ClearOCSPCache();
  5405. }
  5406. /*
  5407. * Finally, record the fact.
  5408. */
  5409. statusContext->useDefaultResponder = PR_FALSE;
  5410. return SECSuccess;
  5411. }
  5412. SECStatus
  5413. CERT_ForcePostMethodForOCSP(PRBool forcePost)
  5414. {
  5415. if (!OCSP_Global.monitor) {
  5416. PORT_SetError(SEC_ERROR_NOT_INITIALIZED);
  5417. return SECFailure;
  5418. }
  5419. PR_EnterMonitor(OCSP_Global.monitor);
  5420. OCSP_Global.forcePost = forcePost;
  5421. PR_ExitMonitor(OCSP_Global.monitor);
  5422. return SECSuccess;
  5423. }
  5424. SECStatus
  5425. CERT_GetOCSPResponseStatus(CERTOCSPResponse *response)
  5426. {
  5427. PORT_Assert(response);
  5428. if (response->statusValue == ocspResponse_successful)
  5429. return SECSuccess;
  5430. switch (response->statusValue) {
  5431. case ocspResponse_malformedRequest:
  5432. PORT_SetError(SEC_ERROR_OCSP_MALFORMED_REQUEST);
  5433. break;
  5434. case ocspResponse_internalError:
  5435. PORT_SetError(SEC_ERROR_OCSP_SERVER_ERROR);
  5436. break;
  5437. case ocspResponse_tryLater:
  5438. PORT_SetError(SEC_ERROR_OCSP_TRY_SERVER_LATER);
  5439. break;
  5440. case ocspResponse_sigRequired:
  5441. /* XXX We *should* retry with a signature, if possible. */
  5442. PORT_SetError(SEC_ERROR_OCSP_REQUEST_NEEDS_SIG);
  5443. break;
  5444. case ocspResponse_unauthorized:
  5445. PORT_SetError(SEC_ERROR_OCSP_UNAUTHORIZED_REQUEST);
  5446. break;
  5447. case ocspResponse_unused:
  5448. default:
  5449. PORT_SetError(SEC_ERROR_OCSP_UNKNOWN_RESPONSE_STATUS);
  5450. break;
  5451. }
  5452. return SECFailure;
  5453. }