ssleay.txt 276 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030
  1. Bundle of old SSLeay documentation files [OBSOLETE!]
  2. *** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! ***
  3. OBSOLETE means that nothing in this document should be trusted. This
  4. document is provided mostly for historical purposes (it wasn't even up
  5. to date at the time SSLeay 0.8.1 was released) and as inspiration. If
  6. you copy some snippet of code from this document, please _check_ that
  7. it really is correct from all points of view. For example, you can
  8. check with the other documents in this directory tree, or by comparing
  9. with relevant parts of the include files.
  10. People have done the mistake of trusting what's written here. Please
  11. don't do that.
  12. *** WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! WARNING! ***
  13. ==== readme ========================================================
  14. This is the old 0.6.6 docuementation. Most of the cipher stuff is still
  15. relevent but I'm working (very slowly) on new documentation.
  16. The current version can be found online at
  17. http://www.cryptsoft.com/ssleay/doc
  18. ==== API.doc ========================================================
  19. SSL - SSLv2/v3/v23 etc.
  20. BIO - methods and how they plug together
  21. MEM - memory allocation callback
  22. CRYPTO - locking for threads
  23. EVP - Ciphers/Digests/signatures
  24. RSA - methods
  25. X509 - certificate retrieval
  26. X509 - validation
  27. X509 - X509v3 extensions
  28. Objects - adding object identifiers
  29. ASN.1 - parsing
  30. PEM - parsing
  31. ==== ssl/readme =====================================================
  32. 22 Jun 1996
  33. This file belongs in ../apps, but I'll leave it here because it deals
  34. with SSL :-) It is rather dated but it gives you an idea of how
  35. things work.
  36. ===
  37. 17 Jul 1995
  38. I have been changing things quite a bit and have not fully updated
  39. this file, so take what you read with a grain of salt
  40. eric
  41. ===
  42. The s_client and s_server programs can be used to test SSL capable
  43. IP/port addresses and the verification of the X509 certificates in use
  44. by these services. I strongly advise having a look at the code to get
  45. an idea of how to use the authentication under SSLeay. Any feedback
  46. on changes and improvements would be greatly accepted.
  47. This file will probably be gibberish unless you have read
  48. rfc1421, rfc1422, rfc1423 and rfc1424 which describe PEM
  49. authentication.
  50. A Brief outline (and examples) how to use them to do so.
  51. NOTE:
  52. The environment variable SSL_CIPER is used to specify the prefered
  53. cipher to use, play around with setting it's value to combinations of
  54. RC4-MD5, EXP-RC4-MD5, CBC-DES-MD5, CBC3-DES-MD5, CFB-DES-NULL
  55. in a : separated list.
  56. This directory contains 3 X509 certificates which can be used by these programs.
  57. client.pem: a file containing a certificate and private key to be used
  58. by s_client.
  59. server.pem :a file containing a certificate and private key to be used
  60. by s_server.
  61. eay1024.pem:the certificate used to sign client.pem and server.pem.
  62. This would be your CA's certificate. There is also a link
  63. from the file a8556381.0 to eay1024.PEM. The value a8556381
  64. is returned by 'x509 -hash -noout <eay1024.pem' and is the
  65. value used by X509 verification routines to 'find' this
  66. certificte when search a directory for it.
  67. [the above is not true any more, the CA cert is
  68. ../certs/testca.pem which is signed by ../certs/mincomca.pem]
  69. When testing the s_server, you may get
  70. bind: Address already in use
  71. errors. These indicate the port is still being held by the unix
  72. kernel and you are going to have to wait for it to let go of it. If
  73. this is the case, remember to use the port commands on the s_server and
  74. s_client to talk on an alternative port.
  75. =====
  76. s_client.
  77. This program can be used to connect to any IP/hostname:port that is
  78. talking SSL. Once connected, it will attempt to authenticate the
  79. certificate it was passed and if everything works as expected, a 2
  80. directional channel will be open. Any text typed will be sent to the
  81. other end. type Q<cr> to exit. Flags are as follows.
  82. -host arg : Arg is the host or IP address to connect to.
  83. -port arg : Arg is the port to connect to (https is 443).
  84. -verify arg : Turn on authentication of the server certificate.
  85. : Arg specifies the 'depth', this will covered below.
  86. -cert arg : The optional certificate to use. This certificate
  87. : will be returned to the server if the server
  88. : requests it for client authentication.
  89. -key arg : The private key that matches the certificate
  90. : specified by the -cert option. If this is not
  91. : specified (but -cert is), the -cert file will be
  92. : searched for the Private key. Both files are
  93. : assumed to be in PEM format.
  94. -CApath arg : When to look for certificates when 'verifying' the
  95. : certificate from the server.
  96. -CAfile arg : A file containing certificates to be used for
  97. : 'verifying' the server certificate.
  98. -reconnect : Once a connection has been made, drop it and
  99. : reconnect with same session-id. This is for testing :-).
  100. The '-verify n' parameter specifies not only to verify the servers
  101. certificate but to also only take notice of 'n' levels. The best way
  102. to explain is to show via examples.
  103. Given
  104. s_server -cert server.PEM is running.
  105. s_client
  106. CONNECTED
  107. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  108. issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  109. verify error:num=1:unable to get issuer certificate
  110. verify return:1
  111. CIPHER is CBC-DES-MD5
  112. What has happened is that the 'SSLeay demo server' certificate's
  113. issuer ('CA') could not be found but because verify is not on, we
  114. don't care and the connection has been made anyway. It is now 'up'
  115. using CBC-DES-MD5 mode. This is an unauthenticate secure channel.
  116. You may not be talking to the right person but the data going to them
  117. is encrypted.
  118. s_client -verify 0
  119. CONNECTED
  120. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  121. issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  122. verify error:num=1:unable to get issuer certificate
  123. verify return:1
  124. CIPHER is CBC-DES-MD5
  125. We are 'verifying' but only to depth 0, so since the 'SSLeay demo server'
  126. certificate passed the date and checksum, we are happy to proceed.
  127. s_client -verify 1
  128. CONNECTED
  129. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  130. issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  131. verify error:num=1:unable to get issuer certificate
  132. verify return:0
  133. ERROR
  134. verify error:unable to get issuer certificate
  135. In this case we failed to make the connection because we could not
  136. authenticate the certificate because we could not find the
  137. 'CA' certificate.
  138. s_client -verify 1 -CAfile eay1024.PEM
  139. CONNECTED
  140. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  141. verify return:1
  142. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  143. verify return:1
  144. CIPHER is CBC-DES-MD5
  145. We loaded the certificates from the file eay1024.PEM. Everything
  146. checked out and so we made the connection.
  147. s_client -verify 1 -CApath .
  148. CONNECTED
  149. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  150. verify return:1
  151. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  152. verify return:1
  153. CIPHER is CBC-DES-MD5
  154. We looked in out local directory for issuer certificates and 'found'
  155. a8556381.0 and so everything is ok.
  156. It is worth noting that 'CA' is a self certified certificate. If you
  157. are passed one of these, it will fail to 'verify' at depth 0 because
  158. we need to lookup the certifier of a certificate from some information
  159. that we trust and keep locally.
  160. SSL_CIPHER=CBC3-DES-MD5:RC4-MD5
  161. export SSL_CIPHER
  162. s_client -verify 10 -CApath . -reconnect
  163. CONNECTED
  164. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  165. verify return:1
  166. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  167. verify return:1
  168. drop the connection and reconnect with the same session id
  169. CIPHER is CBC3-DES-MD5
  170. This has done a full connection and then re-estabished it with the
  171. same session id but a new socket. No RSA stuff occures on the second
  172. connection. Note that we said we would prefer to use CBC3-DES-MD5
  173. encryption and so, since the server supports it, we are.
  174. =====
  175. s_server
  176. This program accepts SSL connections on a specified port
  177. Once connected, it will estabish an SSL connection and optionaly
  178. attempt to authenticate the client. A 2 directional channel will be
  179. open. Any text typed will be sent to the other end. Type Q<cr> to exit.
  180. Flags are as follows.
  181. -port arg : Arg is the port to listen on.
  182. -verify arg : Turn on authentication of the client if they have a
  183. : certificate. Arg specifies the 'depth'.
  184. -Verify arg : Turn on authentication of the client. If they don't
  185. : have a valid certificate, drop the connection.
  186. -cert arg : The certificate to use. This certificate
  187. : will be passed to the client. If it is not
  188. : specified, it will default to server.PEM
  189. -key arg : The private key that matches the certificate
  190. : specified by the -cert option. If this is not
  191. : specified (but -cert is), the -cert file will be
  192. : searched for the Private key. Both files are
  193. : assumed to be in PEM format. Default is server.PEM
  194. -CApath arg : When to look for certificates when 'verifying' the
  195. : certificate from the client.
  196. -CAfile arg : A file containing certificates to be used for
  197. : 'verifying' the client certificate.
  198. For the following 'demo' I will specify the s_server command and
  199. the s_client command and then list the output from the s_server.
  200. s_server
  201. s_client
  202. CONNECTED
  203. CIPHER is CBC-DES-MD5
  204. Everything up and running
  205. s_server -verify 0
  206. s_client
  207. CONNECTED
  208. CIPHER is CBC-DES-MD5
  209. Ok since no certificate was returned and we don't care.
  210. s_server -verify 0
  211. ./s_client -cert client.PEM
  212. CONNECTED
  213. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
  214. issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  215. verify error:num=1:unable to get issuer certificate
  216. verify return:1
  217. CIPHER is CBC-DES-MD5
  218. Ok since we were only verifying to level 0
  219. s_server -verify 4
  220. s_client -cert client.PEM
  221. CONNECTED
  222. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
  223. issuer= /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  224. verify error:num=1:unable to get issuer certificate
  225. verify return:0
  226. ERROR
  227. verify error:unable to get issuer certificate
  228. Bad because we could not authenticate the returned certificate.
  229. s_server -verify 4 -CApath .
  230. s_client -cert client.PEM
  231. CONNECTED
  232. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
  233. verify return:1
  234. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  235. verify return:1
  236. CIPHER is CBC-DES-MD5
  237. Ok because we could authenticate the returned certificate :-).
  238. s_server -Verify 0 -CApath .
  239. s_client
  240. CONNECTED
  241. ERROR
  242. SSL error:function is:REQUEST_CERTIFICATE
  243. :error is :client end did not return a certificate
  244. Error because no certificate returned.
  245. s_server -Verify 4 -CApath .
  246. s_client -cert client.PEM
  247. CONNECTED
  248. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
  249. verify return:1
  250. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  251. verify return:1
  252. CIPHER is CBC-DES-MD5
  253. Full authentication of the client.
  254. So in summary to do full authentication of both ends
  255. s_server -Verify 9 -CApath .
  256. s_client -cert client.PEM -CApath . -verify 9
  257. From the server side
  258. CONNECTED
  259. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo client
  260. verify return:1
  261. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  262. verify return:1
  263. CIPHER is CBC-DES-MD5
  264. From the client side
  265. CONNECTED
  266. depth=0 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=SSLeay demo server
  267. verify return:1
  268. depth=1 /C=AU/SOP=QLD/O=Mincom Pty. Ltd./OU=CS/CN=CA
  269. verify return:1
  270. CIPHER is CBC-DES-MD5
  271. For general probing of the 'internet https' servers for the
  272. distribution area, run
  273. s_client -host www.netscape.com -port 443 -verify 4 -CApath ../rsa/hash
  274. Then enter
  275. GET /
  276. and you should be talking to the https server on that host.
  277. www.rsa.com was refusing to respond to connections on 443 when I was
  278. testing.
  279. have fun :-).
  280. eric
  281. ==== a_verify.doc ========================================================
  282. From eay@mincom.com Fri Oct 4 18:29:06 1996
  283. Received: by orb.mincom.oz.au id AA29080
  284. (5.65c/IDA-1.4.4 for eay); Fri, 4 Oct 1996 08:29:07 +1000
  285. Date: Fri, 4 Oct 1996 08:29:06 +1000 (EST)
  286. From: Eric Young <eay@mincom.oz.au>
  287. X-Sender: eay@orb
  288. To: wplatzer <wplatzer@iaik.tu-graz.ac.at>
  289. Cc: Eric Young <eay@mincom.oz.au>, SSL Mailing List <ssl-users@mincom.com>
  290. Subject: Re: Netscape's Public Key
  291. In-Reply-To: <19961003134837.NTM0049@iaik.tu-graz.ac.at>
  292. Message-Id: <Pine.SOL.3.91.961004081346.8018K-100000@orb>
  293. Mime-Version: 1.0
  294. Content-Type: TEXT/PLAIN; charset=US-ASCII
  295. Status: RO
  296. X-Status:
  297. On Thu, 3 Oct 1996, wplatzer wrote:
  298. > I get Public Key from Netscape (Gold 3.0b4), but cannot do anything
  299. > with it... It looks like (asn1parse):
  300. >
  301. > 0:d=0 hl=3 l=180 cons: SEQUENCE
  302. > 3:d=1 hl=2 l= 96 cons: SEQUENCE
  303. > 5:d=2 hl=2 l= 92 cons: SEQUENCE
  304. > 7:d=3 hl=2 l= 13 cons: SEQUENCE
  305. > 9:d=4 hl=2 l= 9 prim: OBJECT :rsaEncryption
  306. > 20:d=4 hl=2 l= 0 prim: NULL
  307. > 22:d=3 hl=2 l= 75 prim: BIT STRING
  308. > 99:d=2 hl=2 l= 0 prim: IA5STRING :
  309. > 101:d=1 hl=2 l= 13 cons: SEQUENCE
  310. > 103:d=2 hl=2 l= 9 prim: OBJECT :md5withRSAEncryption
  311. > 114:d=2 hl=2 l= 0 prim: NULL
  312. > 116:d=1 hl=2 l= 65 prim: BIT STRING
  313. >
  314. > The first BIT STRING is the public key and the second BIT STRING is
  315. > the signature.
  316. > But a public key consists of the public exponent and the modulus. Are
  317. > both numbers in the first BIT STRING?
  318. > Is there a document simply describing this coding stuff (checking
  319. > signature, get the public key, etc.)?
  320. Minimal in SSLeay. If you want to see what the modulus and exponent are,
  321. try asn1parse -offset 25 -length 75 <key.pem
  322. asn1parse will currently stuff up on the 'length 75' part (fixed in next
  323. release) but it will print the stuff. If you are after more
  324. documentation on ASN.1, have a look at www.rsa.com and get their PKCS
  325. documents, most of my initial work on SSLeay was done using them.
  326. As for SSLeay,
  327. util/crypto.num and util/ssl.num are lists of all exported functions in
  328. the library (but not macros :-(.
  329. The ones for extracting public keys from certificates and certificate
  330. requests are EVP_PKEY * X509_REQ_extract_key(X509_REQ *req);
  331. EVP_PKEY * X509_extract_key(X509 *x509);
  332. To verify a signature on a signed ASN.1 object
  333. int X509_verify(X509 *a,EVP_PKEY *key);
  334. int X509_REQ_verify(X509_REQ *a,EVP_PKEY *key);
  335. int X509_CRL_verify(X509_CRL *a,EVP_PKEY *key);
  336. int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a,EVP_PKEY *key);
  337. I should mention that EVP_PKEY can be used to hold a public or a private key,
  338. since for things like RSA and DSS, a public key is just a subset of what
  339. is stored for the private key.
  340. To sign any of the above structures
  341. int X509_sign(X509 *a,EVP_PKEY *key,EVP_MD *md);
  342. int X509_REQ_sign(X509_REQ *a,EVP_PKEY *key,EVP_MD *md);
  343. int X509_CRL_sign(X509_CRL *a,EVP_PKEY *key,EVP_MD *md);
  344. int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *a,EVP_PKEY *key,EVP_MD *md);
  345. where md is the message digest to sign with.
  346. There are all defined in x509.h and all the _sign and _verify functions are
  347. actually macros to the ASN1_sign() and ASN1_verify() functions.
  348. These functions will put the correct algorithm identifiers in the correct
  349. places in the structures.
  350. eric
  351. --
  352. Eric Young | BOOL is tri-state according to Bill Gates.
  353. AARNet: eay@mincom.oz.au | RTFM Win32 GetMessage().
  354. ==== x509 =======================================================
  355. X509_verify()
  356. X509_sign()
  357. X509_get_version()
  358. X509_get_serialNumber()
  359. X509_get_issuer()
  360. X509_get_subject()
  361. X509_get_notBefore()
  362. X509_get_notAfter()
  363. X509_get_pubkey()
  364. X509_set_version()
  365. X509_set_serialNumber()
  366. X509_set_issuer()
  367. X509_set_subject()
  368. X509_set_notBefore()
  369. X509_set_notAfter()
  370. X509_set_pubkey()
  371. X509_get_extensions()
  372. X509_set_extensions()
  373. X509_EXTENSIONS_clear()
  374. X509_EXTENSIONS_retrieve()
  375. X509_EXTENSIONS_add()
  376. X509_EXTENSIONS_delete()
  377. ==== x509 attribute ================================================
  378. PKCS7
  379. STACK of X509_ATTRIBUTES
  380. ASN1_OBJECT
  381. STACK of ASN1_TYPE
  382. So it is
  383. p7.xa[].obj
  384. p7.xa[].data[]
  385. get_obj_by_nid(STACK , nid)
  386. get_num_by_nid(STACK , nid)
  387. get_data_by_nid(STACK , nid, index)
  388. X509_ATTRIBUTE *X509_ATTRIBUTE_new(void );
  389. void X509_ATTRIBUTE_free(X509_ATTRIBUTE *a);
  390. X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **ex,
  391. int nid, STACK *value);
  392. X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **ex,
  393. int nid, STACK *value);
  394. int X509_ATTRIBUTE_set_object(X509_ATTRIBUTE *ex,ASN1_OBJECT *obj);
  395. int X509_ATTRIBUTE_add_data(X509_ATTRIBUTE *ex, int index,
  396. ASN1_TYPE *value);
  397. ASN1_OBJECT * X509_ATTRIBUTE_get_object(X509_ATTRIBUTE *ex);
  398. int X509_ATTRIBUTE_get_num(X509_ATTRIBUTE *ne);
  399. ASN1_TYPE * X509_ATTRIBUTE_get_data(X509_ATTRIBUTE *ne,int index);
  400. ASN1_TYPE * X509_ATTRIBUTE_get_data_by_NID(X509_ATTRIBUTE *ne,
  401. ASN1_OBJECT *obj);
  402. X509_ATTRIBUTE *PKCS7_get_s_att_by_NID(PKCS7 *p7,int nid);
  403. X509_ATTRIBUTE *PKCS7_get_u_att_by_NID(PKCS7 *p7,int nid);
  404. ==== x509 v3 ========================================================
  405. The 'new' system.
  406. The X509_EXTENSION_METHOD includes extensions and attributes and/or names.
  407. Basically everthing that can be added to an X509 with an OID identifying it.
  408. It operates via 2 methods per object id.
  409. int a2i_XXX(X509 *x,char *str,int len);
  410. int i2a_XXX(BIO *bp,X509 *x);
  411. The a2i_XXX function will add the object with a value converted from the
  412. string into the X509. Len can be -1 in which case the length is calculated
  413. via strlen(str). Applications can always use direct knowledge to load and
  414. unload the relevent objects themselves.
  415. i2a_XXX will print to the passed BIO, a text representation of the
  416. relevet object. Use a memory BIO if you want it printed to a buffer :-).
  417. X509_add_by_NID(X509 *x,int nid,char *str,int len);
  418. X509_add_by_OBJ(X509 *x,ASN1_OBJECT *obj,char *str,int len);
  419. X509_print_by_name(BIO *bp,X509 *x);
  420. X509_print_by_NID(BIO *bp,X509 *x);
  421. X509_print_by_OBJ(BIO *bp,X509 *x);
  422. ==== verify ========================================================
  423. X509_verify_cert_chain(
  424. CERT_STORE *cert_store,
  425. STACK /* X509 */ *certs,
  426. int *verify_result,
  427. int (*verify_error_callback)()
  428. char *argument_to_callback, /* SSL */
  429. app_verify_callback(
  430. char *app_verify_arg, /* from SSL_CTX */
  431. STACK /* X509 */ *certs,
  432. int *verify_result,
  433. int (*verify_error_callback)()
  434. SSL *s,
  435. int X509_verify_cert(
  436. CERT_STORE *cert_store,
  437. X509 *x509,
  438. int *verify_result,
  439. int (*verify_error_callback)(),
  440. char *arg,
  441. ==== apps.doc ========================================================
  442. The applications
  443. Ok, where to begin....
  444. In the begining, when SSLeay was small (April 1995), there
  445. were but few applications, they did happily cohabit in
  446. the one bin directory. Then over time, they did multiply and grow,
  447. and they started to look like microsoft software; 500k to print 'hello world'.
  448. A new approach was needed. They were coalessed into one 'Monolithic'
  449. application, ssleay. This one program is composed of many programs that
  450. can all be compiled independantly.
  451. ssleay has 3 modes of operation.
  452. 1) If the ssleay binary has the name of one of its component programs, it
  453. executes that program and then exits. This can be achieved by using hard or
  454. symbolic links, or failing that, just renaming the binary.
  455. 2) If the first argument to ssleay is the name of one of the component
  456. programs, that program runs that program and then exits.
  457. 3) If there are no arguments, ssleay enters a 'command' mode. Each line is
  458. interpreted as a program name plus arguments. After each 'program' is run,
  459. ssleay returns to the comand line.
  460. dgst - message digests
  461. enc - encryption and base64 encoding
  462. ans1parse - 'pulls' appart ASN.1 encoded objects like certificates.
  463. dh - Diffle-Hellman parameter manipulation.
  464. rsa - RSA manipulations.
  465. crl - Certificate revokion list manipulations
  466. x509 - X509 cert fiddles, including signing.
  467. pkcs7 - pkcs7 manipulation, only DER versions right now.
  468. genrsa - generate an RSA private key.
  469. gendh - Generate a set of Diffle-Hellman parameters.
  470. req - Generate a PKCS#10 object, a certificate request.
  471. s_client - SSL client program
  472. s_server - SSL server program
  473. s_time - A SSL protocol timing program
  474. s_mult - Another SSL server, but it multiplexes
  475. connections.
  476. s_filter - under development
  477. errstr - Convert SSLeay error numbers to strings.
  478. ca - Sign certificate requests, and generate
  479. certificate revokion lists
  480. crl2pkcs7 - put a crl and certifcates into a pkcs7 object.
  481. speed - Benchmark the ciphers.
  482. verify - Check certificates
  483. hashdir - under development
  484. [ there a now a few more options, play with the program to see what they
  485. are ]
  486. ==== asn1.doc ========================================================
  487. The ASN.1 Routines.
  488. ASN.1 is a specification for how to encode structured 'data' in binary form.
  489. The approach I have take to the manipulation of structures and their encoding
  490. into ASN.1 is as follows.
  491. For each distinct structure there are 4 function of the following form
  492. TYPE *TYPE_new(void);
  493. void TYPE_free(TYPE *);
  494. TYPE *d2i_TYPE(TYPE **a,unsigned char **pp,long length);
  495. long i2d_TYPE(TYPE *a,unsigned char **pp); /* CHECK RETURN VALUE */
  496. where TYPE is the type of the 'object'. The TYPE that have these functions
  497. can be in one of 2 forms, either the internal C malloc()ed data structure
  498. or in the DER (a variant of ASN.1 encoding) binary encoding which is just
  499. an array of unsigned bytes. The 'i2d' functions converts from the internal
  500. form to the DER form and the 'd2i' functions convert from the DER form to
  501. the internal form.
  502. The 'new' function returns a malloc()ed version of the structure with all
  503. substructures either created or left as NULL pointers. For 'optional'
  504. fields, they are normally left as NULL to indicate no value. For variable
  505. size sub structures (often 'SET OF' or 'SEQUENCE OF' in ASN.1 syntax) the
  506. STACK data type is used to hold the values. Have a read of stack.doc
  507. and have a look at the relevant header files to see what I mean. If there
  508. is an error while malloc()ing the structure, NULL is returned.
  509. The 'free' function will free() all the sub components of a particular
  510. structure. If any of those sub components have been 'removed', replace
  511. them with NULL pointers, the 'free' functions are tolerant of NULL fields.
  512. The 'd2i' function copies a binary representation into a C structure. It
  513. operates as follows. 'a' is a pointer to a pointer to
  514. the structure to populate, 'pp' is a pointer to a pointer to where the DER
  515. byte string is located and 'length' is the length of the '*pp' data.
  516. If there are no errors, a pointer to the populated structure is returned.
  517. If there is an error, NULL is returned. Errors can occur because of
  518. malloc() failures but normally they will be due to syntax errors in the DER
  519. encoded data being parsed. It is also an error if there was an
  520. attempt to read more that 'length' bytes from '*p'. If
  521. everything works correctly, the value in '*p' is updated
  522. to point at the location just beyond where the DER
  523. structure was read from. In this way, chained calls to 'd2i' type
  524. functions can be made, with the pointer into the 'data' array being
  525. 'walked' along the input byte array.
  526. Depending on the value passed for 'a', different things will be done. If
  527. 'a' is NULL, a new structure will be malloc()ed and returned. If '*a' is
  528. NULL, a new structure will be malloc()ed and put into '*a' and returned.
  529. If '*a' is not NULL, the structure in '*a' will be populated, or in the
  530. case of an error, free()ed and then returned.
  531. Having these semantics means that a structure
  532. can call a 'd2i' function to populate a field and if the field is currently
  533. NULL, the structure will be created.
  534. The 'i2d' function type is used to copy a C structure to a byte array.
  535. The parameter 'a' is the structure to convert and '*p' is where to put it.
  536. As for the 'd2i' type structure, 'p' is updated to point after the last
  537. byte written. If p is NULL, no data is written. The function also returns
  538. the number of bytes written. Where this becomes useful is that if the
  539. function is called with a NULL 'p' value, the length is returned. This can
  540. then be used to malloc() an array of bytes and then the same function can
  541. be recalled passing the malloced array to be written to. e.g.
  542. int len;
  543. unsigned char *bytes,*p;
  544. len=i2d_X509(x,NULL); /* get the size of the ASN1 encoding of 'x' */
  545. if ((bytes=(unsigned char *)malloc(len)) == NULL)
  546. goto err;
  547. p=bytes;
  548. i2d_X509(x,&p);
  549. Please note that a new variable, 'p' was passed to i2d_X509. After the
  550. call to i2d_X509 p has been incremented by len bytes.
  551. Now the reason for this functional organisation is that it allows nested
  552. structures to be built up by calling these functions as required. There
  553. are various macros used to help write the general 'i2d', 'd2i', 'new' and
  554. 'free' functions. They are discussed in another file and would only be
  555. used by some-one wanting to add new structures to the library. As you
  556. might be able to guess, the process of writing ASN.1 files can be a bit CPU
  557. expensive for complex structures. I'm willing to live with this since the
  558. simpler library code make my life easier and hopefully most programs using
  559. these routines will have their execution profiles dominated by cipher or
  560. message digest routines.
  561. What follows is a list of 'TYPE' values and the corresponding ASN.1
  562. structure and where it is used.
  563. TYPE ASN.1
  564. ASN1_INTEGER INTEGER
  565. ASN1_BIT_STRING BIT STRING
  566. ASN1_OCTET_STRING OCTET STRING
  567. ASN1_OBJECT OBJECT IDENTIFIER
  568. ASN1_PRINTABLESTRING PrintableString
  569. ASN1_T61STRING T61String
  570. ASN1_IA5STRING IA5String
  571. ASN1_UTCTIME UTCTime
  572. ASN1_TYPE Any of the above mentioned types plus SEQUENCE and SET
  573. Most of the above mentioned types are actualled stored in the
  574. ASN1_BIT_STRING type and macros are used to differentiate between them.
  575. The 3 types used are
  576. typedef struct asn1_object_st
  577. {
  578. /* both null if a dynamic ASN1_OBJECT, one is
  579. * defined if a 'static' ASN1_OBJECT */
  580. char *sn,*ln;
  581. int nid;
  582. int length;
  583. unsigned char *data;
  584. } ASN1_OBJECT;
  585. This is used to store ASN1 OBJECTS. Read 'objects.doc' for details ono
  586. routines to manipulate this structure. 'sn' and 'ln' are used to hold text
  587. strings that represent the object (short name and long or lower case name).
  588. These are used by the 'OBJ' library. 'nid' is a number used by the OBJ
  589. library to uniquely identify objects. The ASN1 routines will populate the
  590. 'length' and 'data' fields which will contain the bit string representing
  591. the object.
  592. typedef struct asn1_bit_string_st
  593. {
  594. int length;
  595. int type;
  596. unsigned char *data;
  597. } ASN1_BIT_STRING;
  598. This structure is used to hold all the other base ASN1 types except for
  599. ASN1_UTCTIME (which is really just a 'char *'). Length is the number of
  600. bytes held in data and type is the ASN1 type of the object (there is a list
  601. in asn1.h).
  602. typedef struct asn1_type_st
  603. {
  604. int type;
  605. union {
  606. char *ptr;
  607. ASN1_INTEGER * integer;
  608. ASN1_BIT_STRING * bit_string;
  609. ASN1_OCTET_STRING * octet_string;
  610. ASN1_OBJECT * object;
  611. ASN1_PRINTABLESTRING * printablestring;
  612. ASN1_T61STRING * t61string;
  613. ASN1_IA5STRING * ia5string;
  614. ASN1_UTCTIME * utctime;
  615. ASN1_BIT_STRING * set;
  616. ASN1_BIT_STRING * sequence;
  617. } value;
  618. } ASN1_TYPE;
  619. This structure is used in a few places when 'any' type of object can be
  620. expected.
  621. X509 Certificate
  622. X509_CINF CertificateInfo
  623. X509_ALGOR AlgorithmIdentifier
  624. X509_NAME Name
  625. X509_NAME_ENTRY A single sub component of the name.
  626. X509_VAL Validity
  627. X509_PUBKEY SubjectPublicKeyInfo
  628. The above mentioned types are declared in x509.h. They are all quite
  629. straight forward except for the X509_NAME/X509_NAME_ENTRY pair.
  630. A X509_NAME is a STACK (see stack.doc) of X509_NAME_ENTRY's.
  631. typedef struct X509_name_entry_st
  632. {
  633. ASN1_OBJECT *object;
  634. ASN1_BIT_STRING *value;
  635. int set;
  636. int size; /* temp variable */
  637. } X509_NAME_ENTRY;
  638. The size is a temporary variable used by i2d_NAME and set is the set number
  639. for the particular NAME_ENTRY. A X509_NAME is encoded as a sequence of
  640. sequence of sets. Normally each set contains only a single item.
  641. Sometimes it contains more. Normally throughout this library there will be
  642. only one item per set. The set field contains the 'set' that this entry is
  643. a member of. So if you have just created a X509_NAME structure and
  644. populated it with X509_NAME_ENTRYs, you should then traverse the X509_NAME
  645. (which is just a STACK) and set the 'set/' field to incrementing numbers.
  646. For more details on why this is done, read the ASN.1 spec for Distinguished
  647. Names.
  648. X509_REQ CertificateRequest
  649. X509_REQ_INFO CertificateRequestInfo
  650. These are used to hold certificate requests.
  651. X509_CRL CertificateRevocationList
  652. These are used to hold a certificate revocation list
  653. RSAPrivateKey PrivateKeyInfo
  654. RSAPublicKey PublicKeyInfo
  655. Both these 'function groups' operate on 'RSA' structures (see rsa.doc).
  656. The difference is that the RSAPublicKey operations only manipulate the m
  657. and e fields in the RSA structure.
  658. DSAPrivateKey DSS private key
  659. DSAPublicKey DSS public key
  660. Both these 'function groups' operate on 'DSS' structures (see dsa.doc).
  661. The difference is that the RSAPublicKey operations only manipulate the
  662. XXX fields in the DSA structure.
  663. DHparams DHParameter
  664. This is used to hold the p and g value for The Diffie-Hellman operation.
  665. The function deal with the 'DH' strucure (see dh.doc).
  666. Now all of these function types can be used with several other functions to give
  667. quite useful set of general manipulation routines. Normally one would
  668. not uses these functions directly but use them via macros.
  669. char *ASN1_dup(int (*i2d)(),char *(*d2i)(),char *x);
  670. 'x' is the input structure case to a 'char *', 'i2d' is the 'i2d_TYPE'
  671. function for the type that 'x' is and d2i is the 'd2i_TYPE' function for the
  672. type that 'x' is. As is obvious from the parameters, this function
  673. duplicates the strucutre by transforming it into the DER form and then
  674. re-loading it into a new strucutre and returning the new strucutre. This
  675. is obviously a bit cpu intensive but when faced with a complex dynamic
  676. structure this is the simplest programming approach. There are macros for
  677. duplicating the major data types but is simple to add extras.
  678. char *ASN1_d2i_fp(char *(*new)(),char *(*d2i)(),FILE *fp,unsigned char **x);
  679. 'x' is a pointer to a pointer of the 'desired type'. new and d2i are the
  680. corresponding 'TYPE_new' and 'd2i_TYPE' functions for the type and 'fp' is
  681. an open file pointer to read from. This function reads from 'fp' as much
  682. data as it can and then uses 'd2i' to parse the bytes to load and return
  683. the parsed strucutre in 'x' (if it was non-NULL) and to actually return the
  684. strucutre. The behavior of 'x' is as per all the other d2i functions.
  685. char *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
  686. The 'BIO' is the new IO type being used in SSLeay (see bio.doc). This
  687. function is the same as ASN1_d2i_fp() except for the BIO argument.
  688. ASN1_d2i_fp() actually calls this function.
  689. int ASN1_i2d_fp(int (*i2d)(),FILE *out,unsigned char *x);
  690. 'x' is converted to bytes by 'i2d' and then written to 'out'. ASN1_i2d_fp
  691. and ASN1_d2i_fp are not really symetric since ASN1_i2d_fp will read all
  692. available data from the file pointer before parsing a single item while
  693. ASN1_i2d_fp can be used to write a sequence of data objects. To read a
  694. series of objects from a file I would sugest loading the file into a buffer
  695. and calling the relevent 'd2i' functions.
  696. char *ASN1_d2i_bio(char *(*new)(),char *(*d2i)(),BIO *fp,unsigned char **x);
  697. This function is the same as ASN1_i2d_fp() except for the BIO argument.
  698. ASN1_i2d_fp() actually calls this function.
  699. char * PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
  700. This function will read the next PEM encoded (base64) object of the same
  701. type as 'x' (loaded by the d2i function). 'name' is the name that is in
  702. the '-----BEGIN name-----' that designates the start of that object type.
  703. If the data is encrypted, 'cb' will be called to prompt for a password. If
  704. it is NULL a default function will be used to prompt from the password.
  705. 'x' is delt with as per the standard 'd2i' function interface. This
  706. function can be used to read a series of objects from a file. While any
  707. data type can be encrypted (see PEM_ASN1_write) only RSA private keys tend
  708. to be encrypted.
  709. char * PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *fp,
  710. char **x,int (*cb)());
  711. Same as PEM_ASN1_read() except using a BIO. This is called by
  712. PEM_ASN1_read().
  713. int PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,EVP_CIPHER *enc,
  714. unsigned char *kstr,int klen,int (*callback)());
  715. int PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *fp,
  716. char *x,EVP_CIPHER *enc,unsigned char *kstr,int klen,
  717. int (*callback)());
  718. int ASN1_sign(int (*i2d)(), X509_ALGOR *algor1, X509_ALGOR *algor2,
  719. ASN1_BIT_STRING *signature, char *data, RSA *rsa, EVP_MD *type);
  720. int ASN1_verify(int (*i2d)(), X509_ALGOR *algor1,
  721. ASN1_BIT_STRING *signature,char *data, RSA *rsa);
  722. int ASN1_BIT_STRING_cmp(ASN1_BIT_STRING *a, ASN1_BIT_STRING *b);
  723. ASN1_BIT_STRING *ASN1_BIT_STRING_type_new(int type );
  724. int ASN1_UTCTIME_check(ASN1_UTCTIME *a);
  725. void ASN1_UTCTIME_print(BIO *fp,ASN1_UTCTIME *a);
  726. ASN1_UTCTIME *ASN1_UTCTIME_dup(ASN1_UTCTIME *a);
  727. ASN1_BIT_STRING *d2i_asn1_print_type(ASN1_BIT_STRING **a,unsigned char **pp,
  728. long length,int type);
  729. int i2d_ASN1_SET(STACK *a, unsigned char **pp,
  730. int (*func)(), int ex_tag, int ex_class);
  731. STACK * d2i_ASN1_SET(STACK **a, unsigned char **pp, long length,
  732. char *(*func)(), int ex_tag, int ex_class);
  733. int i2a_ASN1_OBJECT(BIO *bp,ASN1_OBJECT *object);
  734. int i2a_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *a);
  735. int a2i_ASN1_INTEGER(BIO *bp,ASN1_INTEGER *bs,char *buf,int size);
  736. int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
  737. long ASN1_INTEGER_get(ASN1_INTEGER *a);
  738. ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
  739. BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
  740. /* given a string, return the correct type. Max is the maximum number
  741. * of bytes to parse. It stops parsing when 'max' bytes have been
  742. * processed or a '\0' is hit */
  743. int ASN1_PRINTABLE_type(unsigned char *s,int max);
  744. void ASN1_parse(BIO *fp,unsigned char *pp,long len);
  745. int i2d_ASN1_bytes(ASN1_BIT_STRING *a, unsigned char **pp, int tag, int class);
  746. ASN1_BIT_STRING *d2i_ASN1_bytes(ASN1_OCTET_STRING **a, unsigned char **pp,
  747. long length, int Ptag, int Pclass);
  748. /* PARSING */
  749. int asn1_Finish(ASN1_CTX *c);
  750. /* SPECIALS */
  751. int ASN1_get_object(unsigned char **pp, long *plength, int *ptag,
  752. int *pclass, long omax);
  753. int ASN1_check_infinite_end(unsigned char **p,long len);
  754. void ASN1_put_object(unsigned char **pp, int constructed, int length,
  755. int tag, int class);
  756. int ASN1_object_size(int constructed, int length, int tag);
  757. X509 * X509_get_cert(CERTIFICATE_CTX *ctx,X509_NAME * name,X509 *tmp_x509);
  758. int X509_add_cert(CERTIFICATE_CTX *ctx,X509 *);
  759. char * X509_cert_verify_error_string(int n);
  760. int X509_add_cert_file(CERTIFICATE_CTX *c,char *file, int type);
  761. char * X509_gmtime (char *s, long adj);
  762. int X509_add_cert_dir (CERTIFICATE_CTX *c,char *dir, int type);
  763. int X509_load_verify_locations (CERTIFICATE_CTX *ctx,
  764. char *file_env, char *dir_env);
  765. int X509_set_default_verify_paths(CERTIFICATE_CTX *cts);
  766. X509 * X509_new_D2i_X509(int len, unsigned char *p);
  767. char * X509_get_default_cert_area(void );
  768. char * X509_get_default_cert_dir(void );
  769. char * X509_get_default_cert_file(void );
  770. char * X509_get_default_cert_dir_env(void );
  771. char * X509_get_default_cert_file_env(void );
  772. char * X509_get_default_private_dir(void );
  773. X509_REQ *X509_X509_TO_req(X509 *x, RSA *rsa);
  774. int X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)());
  775. CERTIFICATE_CTX *CERTIFICATE_CTX_new();
  776. void CERTIFICATE_CTX_free(CERTIFICATE_CTX *c);
  777. void X509_NAME_print(BIO *fp, X509_NAME *name, int obase);
  778. int X509_print_fp(FILE *fp,X509 *x);
  779. int X509_print(BIO *fp,X509 *x);
  780. X509_INFO * X509_INFO_new(void);
  781. void X509_INFO_free(X509_INFO *a);
  782. char * X509_NAME_oneline(X509_NAME *a);
  783. #define X509_verify(x,rsa)
  784. #define X509_REQ_verify(x,rsa)
  785. #define X509_CRL_verify(x,rsa)
  786. #define X509_sign(x,rsa,md)
  787. #define X509_REQ_sign(x,rsa,md)
  788. #define X509_CRL_sign(x,rsa,md)
  789. #define X509_dup(x509)
  790. #define d2i_X509_fp(fp,x509)
  791. #define i2d_X509_fp(fp,x509)
  792. #define d2i_X509_bio(bp,x509)
  793. #define i2d_X509_bio(bp,x509)
  794. #define X509_CRL_dup(crl)
  795. #define d2i_X509_CRL_fp(fp,crl)
  796. #define i2d_X509_CRL_fp(fp,crl)
  797. #define d2i_X509_CRL_bio(bp,crl)
  798. #define i2d_X509_CRL_bio(bp,crl)
  799. #define X509_REQ_dup(req)
  800. #define d2i_X509_REQ_fp(fp,req)
  801. #define i2d_X509_REQ_fp(fp,req)
  802. #define d2i_X509_REQ_bio(bp,req)
  803. #define i2d_X509_REQ_bio(bp,req)
  804. #define RSAPrivateKey_dup(rsa)
  805. #define d2i_RSAPrivateKey_fp(fp,rsa)
  806. #define i2d_RSAPrivateKey_fp(fp,rsa)
  807. #define d2i_RSAPrivateKey_bio(bp,rsa)
  808. #define i2d_RSAPrivateKey_bio(bp,rsa)
  809. #define X509_NAME_dup(xn)
  810. #define X509_NAME_ENTRY_dup(ne)
  811. void X509_REQ_print_fp(FILE *fp,X509_REQ *req);
  812. void X509_REQ_print(BIO *fp,X509_REQ *req);
  813. RSA *X509_REQ_extract_key(X509_REQ *req);
  814. RSA *X509_extract_key(X509 *x509);
  815. int X509_issuer_and_serial_cmp(X509 *a, X509 *b);
  816. unsigned long X509_issuer_and_serial_hash(X509 *a);
  817. X509_NAME * X509_get_issuer_name(X509 *a);
  818. int X509_issuer_name_cmp(X509 *a, X509 *b);
  819. unsigned long X509_issuer_name_hash(X509 *a);
  820. X509_NAME * X509_get_subject_name(X509 *a);
  821. int X509_subject_name_cmp(X509 *a,X509 *b);
  822. unsigned long X509_subject_name_hash(X509 *x);
  823. int X509_NAME_cmp (X509_NAME *a, X509_NAME *b);
  824. unsigned long X509_NAME_hash(X509_NAME *x);
  825. ==== bio.doc ========================================================
  826. BIO Routines
  827. This documentation is rather sparse, you are probably best
  828. off looking at the code for specific details.
  829. The BIO library is a IO abstraction that was originally
  830. inspired by the need to have callbacks to perform IO to FILE
  831. pointers when using Windows 3.1 DLLs. There are two types
  832. of BIO; a source/sink type and a filter type.
  833. The source/sink methods are as follows:
  834. - BIO_s_mem() memory buffer - a read/write byte array that
  835. grows until memory runs out :-).
  836. - BIO_s_file() FILE pointer - A wrapper around the normal
  837. 'FILE *' commands, good for use with stdin/stdout.
  838. - BIO_s_fd() File descriptor - A wrapper around file
  839. descriptors, often used with pipes.
  840. - BIO_s_socket() Socket - Used around sockets. It is
  841. mostly in the Microsoft world that sockets are different
  842. from file descriptors and there are all those ugly winsock
  843. commands.
  844. - BIO_s_null() Null - read nothing and write nothing.; a
  845. useful endpoint for filter type BIO's specifically things
  846. like the message digest BIO.
  847. The filter types are
  848. - BIO_f_buffer() IO buffering - does output buffering into
  849. larger chunks and performs input buffering to allow gets()
  850. type functions.
  851. - BIO_f_md() Message digest - a transparent filter that can
  852. be asked to return a message digest for the data that has
  853. passed through it.
  854. - BIO_f_cipher() Encrypt or decrypt all data passing
  855. through the filter.
  856. - BIO_f_base64() Base64 decode on read and encode on write.
  857. - BIO_f_ssl() A filter that performs SSL encryption on the
  858. data sent through it.
  859. Base BIO functions.
  860. The BIO library has a set of base functions that are
  861. implemented for each particular type. Filter BIOs will
  862. normally call the equivalent function on the source/sink BIO
  863. that they are layered on top of after they have performed
  864. some modification to the data stream. Multiple filter BIOs
  865. can be 'push' into a stack of modifers, so to read from a
  866. file, unbase64 it, then decrypt it, a BIO_f_cipher,
  867. BIO_f_base64 and a BIO_s_file would probably be used. If a
  868. sha-1 and md5 message digest needed to be generated, a stack
  869. two BIO_f_md() BIOs and a BIO_s_null() BIO could be used.
  870. The base functions are
  871. - BIO *BIO_new(BIO_METHOD *type); Create a new BIO of type 'type'.
  872. - int BIO_free(BIO *a); Free a BIO structure. Depending on
  873. the configuration, this will free the underlying data
  874. object for a source/sink BIO.
  875. - int BIO_read(BIO *b, char *data, int len); Read upto 'len'
  876. bytes into 'data'.
  877. - int BIO_gets(BIO *bp,char *buf, int size); Depending on
  878. the BIO, this can either be a 'get special' or a get one
  879. line of data, as per fgets();
  880. - int BIO_write(BIO *b, char *data, int len); Write 'len'
  881. bytes from 'data' to the 'b' BIO.
  882. - int BIO_puts(BIO *bp,char *buf); Either a 'put special' or
  883. a write null terminated string as per fputs().
  884. - long BIO_ctrl(BIO *bp,int cmd,long larg,char *parg); A
  885. control function which is used to manipulate the BIO
  886. structure and modify it's state and or report on it. This
  887. function is just about never used directly, rather it
  888. should be used in conjunction with BIO_METHOD specific
  889. macros.
  890. - BIO *BIO_push(BIO *new_top, BIO *old); new_top is apped to the
  891. top of the 'old' BIO list. new_top should be a filter BIO.
  892. All writes will go through 'new_top' first and last on read.
  893. 'old' is returned.
  894. - BIO *BIO_pop(BIO *bio); the new topmost BIO is returned, NULL if
  895. there are no more.
  896. If a particular low level BIO method is not supported
  897. (normally BIO_gets()), -2 will be returned if that method is
  898. called. Otherwise the IO methods (read, write, gets, puts)
  899. will return the number of bytes read or written, and 0 or -1
  900. for error (or end of input). For the -1 case,
  901. BIO_should_retry(bio) can be called to determine if it was a
  902. genuine error or a temporary problem. -2 will also be
  903. returned if the BIO has not been initalised yet, in all
  904. cases, the correct error codes are set (accessible via the
  905. ERR library).
  906. The following functions are convenience functions:
  907. - int BIO_printf(BIO *bio, char * format, ..); printf but
  908. to a BIO handle.
  909. - long BIO_ctrl_int(BIO *bp,int cmd,long larg,int iarg); a
  910. convenience function to allow a different argument types
  911. to be passed to BIO_ctrl().
  912. - int BIO_dump(BIO *b,char *bytes,int len); output 'len'
  913. bytes from 'bytes' in a hex dump debug format.
  914. - long BIO_debug_callback(BIO *bio, int cmd, char *argp, int
  915. argi, long argl, long ret) - a default debug BIO callback,
  916. this is mentioned below. To use this one normally has to
  917. use the BIO_set_callback_arg() function to assign an
  918. output BIO for the callback to use.
  919. - BIO *BIO_find_type(BIO *bio,int type); when there is a 'stack'
  920. of BIOs, this function scan the list and returns the first
  921. that is of type 'type', as listed in buffer.h under BIO_TYPE_XXX.
  922. - void BIO_free_all(BIO *bio); Free the bio and all other BIOs
  923. in the list. It walks the bio->next_bio list.
  924. Extra commands are normally implemented as macros calling BIO_ctrl().
  925. - BIO_number_read(BIO *bio) - the number of bytes processed
  926. by BIO_read(bio,.).
  927. - BIO_number_written(BIO *bio) - the number of bytes written
  928. by BIO_write(bio,.).
  929. - BIO_reset(BIO *bio) - 'reset' the BIO.
  930. - BIO_eof(BIO *bio) - non zero if we are at the current end
  931. of input.
  932. - BIO_set_close(BIO *bio, int close_flag) - set the close flag.
  933. - BIO_get_close(BIO *bio) - return the close flag.
  934. BIO_pending(BIO *bio) - return the number of bytes waiting
  935. to be read (normally buffered internally).
  936. - BIO_flush(BIO *bio) - output any data waiting to be output.
  937. - BIO_should_retry(BIO *io) - after a BIO_read/BIO_write
  938. operation returns 0 or -1, a call to this function will
  939. return non zero if you should retry the call later (this
  940. is for non-blocking IO).
  941. - BIO_should_read(BIO *io) - we should retry when data can
  942. be read.
  943. - BIO_should_write(BIO *io) - we should retry when data can
  944. be written.
  945. - BIO_method_name(BIO *io) - return a string for the method name.
  946. - BIO_method_type(BIO *io) - return the unique ID of the BIO method.
  947. - BIO_set_callback(BIO *io, long (*callback)(BIO *io, int
  948. cmd, char *argp, int argi, long argl, long ret); - sets
  949. the debug callback.
  950. - BIO_get_callback(BIO *io) - return the assigned function
  951. as mentioned above.
  952. - BIO_set_callback_arg(BIO *io, char *arg) - assign some
  953. data against the BIO. This is normally used by the debug
  954. callback but could in reality be used for anything. To
  955. get an idea of how all this works, have a look at the code
  956. in the default debug callback mentioned above. The
  957. callback can modify the return values.
  958. Details of the BIO_METHOD structure.
  959. typedef struct bio_method_st
  960. {
  961. int type;
  962. char *name;
  963. int (*bwrite)();
  964. int (*bread)();
  965. int (*bputs)();
  966. int (*bgets)();
  967. long (*ctrl)();
  968. int (*create)();
  969. int (*destroy)();
  970. } BIO_METHOD;
  971. The 'type' is the numeric type of the BIO, these are listed in buffer.h;
  972. 'Name' is a textual representation of the BIO 'type'.
  973. The 7 function pointers point to the respective function
  974. methods, some of which can be NULL if not implemented.
  975. The BIO structure
  976. typedef struct bio_st
  977. {
  978. BIO_METHOD *method;
  979. long (*callback)(BIO * bio, int mode, char *argp, int
  980. argi, long argl, long ret);
  981. char *cb_arg; /* first argument for the callback */
  982. int init;
  983. int shutdown;
  984. int flags; /* extra storage */
  985. int num;
  986. char *ptr;
  987. struct bio_st *next_bio; /* used by filter BIOs */
  988. int references;
  989. unsigned long num_read;
  990. unsigned long num_write;
  991. } BIO;
  992. - 'Method' is the BIO method.
  993. - 'callback', when configured, is called before and after
  994. each BIO method is called for that particular BIO. This
  995. is intended primarily for debugging and of informational feedback.
  996. - 'init' is 0 when the BIO can be used for operation.
  997. Often, after a BIO is created, a number of operations may
  998. need to be performed before it is available for use. An
  999. example is for BIO_s_sock(). A socket needs to be
  1000. assigned to the BIO before it can be used.
  1001. - 'shutdown', this flag indicates if the underlying
  1002. communication primitive being used should be closed/freed
  1003. when the BIO is closed.
  1004. - 'flags' is used to hold extra state. It is primarily used
  1005. to hold information about why a non-blocking operation
  1006. failed and to record startup protocol information for the
  1007. SSL BIO.
  1008. - 'num' and 'ptr' are used to hold instance specific state
  1009. like file descriptors or local data structures.
  1010. - 'next_bio' is used by filter BIOs to hold the pointer of the
  1011. next BIO in the chain. written data is sent to this BIO and
  1012. data read is taken from it.
  1013. - 'references' is used to indicate the number of pointers to
  1014. this structure. This needs to be '1' before a call to
  1015. BIO_free() is made if the BIO_free() function is to
  1016. actually free() the structure, otherwise the reference
  1017. count is just decreased. The actual BIO subsystem does
  1018. not really use this functionality but it is useful when
  1019. used in more advanced applicaion.
  1020. - num_read and num_write are the total number of bytes
  1021. read/written via the 'read()' and 'write()' methods.
  1022. BIO_ctrl operations.
  1023. The following is the list of standard commands passed as the
  1024. second parameter to BIO_ctrl() and should be supported by
  1025. all BIO as best as possible. Some are optional, some are
  1026. manditory, in any case, where is makes sense, a filter BIO
  1027. should pass such requests to underlying BIO's.
  1028. - BIO_CTRL_RESET - Reset the BIO back to an initial state.
  1029. - BIO_CTRL_EOF - return 0 if we are not at the end of input,
  1030. non 0 if we are.
  1031. - BIO_CTRL_INFO - BIO specific special command, normal
  1032. information return.
  1033. - BIO_CTRL_SET - set IO specific parameter.
  1034. - BIO_CTRL_GET - get IO specific parameter.
  1035. - BIO_CTRL_GET_CLOSE - Get the close on BIO_free() flag, one
  1036. of BIO_CLOSE or BIO_NOCLOSE.
  1037. - BIO_CTRL_SET_CLOSE - Set the close on BIO_free() flag.
  1038. - BIO_CTRL_PENDING - Return the number of bytes available
  1039. for instant reading
  1040. - BIO_CTRL_FLUSH - Output pending data, return number of bytes output.
  1041. - BIO_CTRL_SHOULD_RETRY - After an IO error (-1 returned)
  1042. should we 'retry' when IO is possible on the underlying IO object.
  1043. - BIO_CTRL_RETRY_TYPE - What kind of IO are we waiting on.
  1044. The following command is a special BIO_s_file() specific option.
  1045. - BIO_CTRL_SET_FILENAME - specify a file to open for IO.
  1046. The BIO_CTRL_RETRY_TYPE needs a little more explanation.
  1047. When performing non-blocking IO, or say reading on a memory
  1048. BIO, when no data is present (or cannot be written),
  1049. BIO_read() and/or BIO_write() will return -1.
  1050. BIO_should_retry(bio) will return true if this is due to an
  1051. IO condition rather than an actual error. In the case of
  1052. BIO_s_mem(), a read when there is no data will return -1 and
  1053. a should retry when there is more 'read' data.
  1054. The retry type is deduced from 2 macros
  1055. BIO_should_read(bio) and BIO_should_write(bio).
  1056. Now while it may appear obvious that a BIO_read() failure
  1057. should indicate that a retry should be performed when more
  1058. read data is available, this is often not true when using
  1059. things like an SSL BIO. During the SSL protocol startup
  1060. multiple reads and writes are performed, triggered by any
  1061. SSL_read or SSL_write.
  1062. So to write code that will transparently handle either a
  1063. socket or SSL BIO,
  1064. i=BIO_read(bio,..)
  1065. if (I == -1)
  1066. {
  1067. if (BIO_should_retry(bio))
  1068. {
  1069. if (BIO_should_read(bio))
  1070. {
  1071. /* call us again when BIO can be read */
  1072. }
  1073. if (BIO_should_write(bio))
  1074. {
  1075. /* call us again when BIO can be written */
  1076. }
  1077. }
  1078. }
  1079. At this point in time only read and write conditions can be
  1080. used but in the future I can see the situation for other
  1081. conditions, specifically with SSL there could be a condition
  1082. of a X509 certificate lookup taking place and so the non-
  1083. blocking BIO_read would require a retry when the certificate
  1084. lookup subsystem has finished it's lookup. This is all
  1085. makes more sense and is easy to use in a event loop type
  1086. setup.
  1087. When using the SSL BIO, either SSL_read() or SSL_write()s
  1088. can be called during the protocol startup and things will
  1089. still work correctly.
  1090. The nice aspect of the use of the BIO_should_retry() macro
  1091. is that all the errno codes that indicate a non-fatal error
  1092. are encapsulated in one place. The Windows specific error
  1093. codes and WSAGetLastError() calls are also hidden from the
  1094. application.
  1095. Notes on each BIO method.
  1096. Normally buffer.h is just required but depending on the
  1097. BIO_METHOD, ssl.h or evp.h will also be required.
  1098. BIO_METHOD *BIO_s_mem(void);
  1099. - BIO_set_mem_buf(BIO *bio, BUF_MEM *bm, int close_flag) -
  1100. set the underlying BUF_MEM structure for the BIO to use.
  1101. - BIO_get_mem_ptr(BIO *bio, char **pp) - if pp is not NULL,
  1102. set it to point to the memory array and return the number
  1103. of bytes available.
  1104. A read/write BIO. Any data written is appended to the
  1105. memory array and any read is read from the front. This BIO
  1106. can be used for read/write at the same time. BIO_gets() is
  1107. supported in the fgets() sense.
  1108. BIO_CTRL_INFO can be used to retrieve pointers to the memory
  1109. buffer and it's length.
  1110. BIO_METHOD *BIO_s_file(void);
  1111. - BIO_set_fp(BIO *bio, FILE *fp, int close_flag) - set 'FILE *' to use.
  1112. - BIO_get_fp(BIO *bio, FILE **fp) - get the 'FILE *' in use.
  1113. - BIO_read_filename(BIO *bio, char *name) - read from file.
  1114. - BIO_write_filename(BIO *bio, char *name) - write to file.
  1115. - BIO_append_filename(BIO *bio, char *name) - append to file.
  1116. This BIO sits over the normal system fread()/fgets() type
  1117. functions. Gets() is supported. This BIO in theory could be
  1118. used for read and write but it is best to think of each BIO
  1119. of this type as either a read or a write BIO, not both.
  1120. BIO_METHOD *BIO_s_socket(void);
  1121. BIO_METHOD *BIO_s_fd(void);
  1122. - BIO_sock_should_retry(int i) - the underlying function
  1123. used to determine if a call should be retried; the
  1124. argument is the '0' or '-1' returned by the previous BIO
  1125. operation.
  1126. - BIO_fd_should_retry(int i) - same as the
  1127. - BIO_sock_should_retry() except that it is different internally.
  1128. - BIO_set_fd(BIO *bio, int fd, int close_flag) - set the
  1129. file descriptor to use
  1130. - BIO_get_fd(BIO *bio, int *fd) - get the file descriptor.
  1131. These two methods are very similar. Gets() is not
  1132. supported, if you want this functionality, put a
  1133. BIO_f_buffer() onto it. This BIO is bi-directional if the
  1134. underlying file descriptor is. This is normally the case
  1135. for sockets but not the case for stdio descriptors.
  1136. BIO_METHOD *BIO_s_null(void);
  1137. Read and write as much data as you like, it all disappears
  1138. into this BIO.
  1139. BIO_METHOD *BIO_f_buffer(void);
  1140. - BIO_get_buffer_num_lines(BIO *bio) - return the number of
  1141. complete lines in the buffer.
  1142. - BIO_set_buffer_size(BIO *bio, long size) - set the size of
  1143. the buffers.
  1144. This type performs input and output buffering. It performs
  1145. both at the same time. The size of the buffer can be set
  1146. via the set buffer size option. Data buffered for output is
  1147. only written when the buffer fills.
  1148. BIO_METHOD *BIO_f_ssl(void);
  1149. - BIO_set_ssl(BIO *bio, SSL *ssl, int close_flag) - the SSL
  1150. structure to use.
  1151. - BIO_get_ssl(BIO *bio, SSL **ssl) - get the SSL structure
  1152. in use.
  1153. The SSL bio is a little different from normal BIOs because
  1154. the underlying SSL structure is a little different. A SSL
  1155. structure performs IO via a read and write BIO. These can
  1156. be different and are normally set via the
  1157. SSL_set_rbio()/SSL_set_wbio() calls. The SSL_set_fd() calls
  1158. are just wrappers that create socket BIOs and then call
  1159. SSL_set_bio() where the read and write BIOs are the same.
  1160. The BIO_push() operation makes the SSLs IO BIOs the same, so
  1161. make sure the BIO pushed is capable of two directional
  1162. traffic. If it is not, you will have to install the BIOs
  1163. via the more conventional SSL_set_bio() call. BIO_pop() will retrieve
  1164. the 'SSL read' BIO.
  1165. BIO_METHOD *BIO_f_md(void);
  1166. - BIO_set_md(BIO *bio, EVP_MD *md) - set the message digest
  1167. to use.
  1168. - BIO_get_md(BIO *bio, EVP_MD **mdp) - return the digest
  1169. method in use in mdp, return 0 if not set yet.
  1170. - BIO_reset() reinitializes the digest (EVP_DigestInit())
  1171. and passes the reset to the underlying BIOs.
  1172. All data read or written via BIO_read() or BIO_write() to
  1173. this BIO will be added to the calculated digest. This
  1174. implies that this BIO is only one directional. If read and
  1175. write operations are performed, two separate BIO_f_md() BIOs
  1176. are reuqired to generate digests on both the input and the
  1177. output. BIO_gets(BIO *bio, char *md, int size) will place the
  1178. generated digest into 'md' and return the number of bytes.
  1179. The EVP_MAX_MD_SIZE should probably be used to size the 'md'
  1180. array. Reading the digest will also reset it.
  1181. BIO_METHOD *BIO_f_cipher(void);
  1182. - BIO_reset() reinitializes the cipher.
  1183. - BIO_flush() should be called when the last bytes have been
  1184. output to flush the final block of block ciphers.
  1185. - BIO_get_cipher_status(BIO *b), when called after the last
  1186. read from a cipher BIO, returns non-zero if the data
  1187. decrypted correctly, otherwise, 0.
  1188. - BIO_set_cipher(BIO *b, EVP_CIPHER *c, unsigned char *key,
  1189. unsigned char *iv, int encrypt) This function is used to
  1190. setup a cipher BIO. The length of key and iv are
  1191. specified by the choice of EVP_CIPHER. Encrypt is 1 to
  1192. encrypt and 0 to decrypt.
  1193. BIO_METHOD *BIO_f_base64(void);
  1194. - BIO_flush() should be called when the last bytes have been output.
  1195. This BIO base64 encodes when writing and base64 decodes when
  1196. reading. It will scan the input until a suitable begin line
  1197. is found. After reading data, BIO_reset() will reset the
  1198. BIO to start scanning again. Do not mix reading and writing
  1199. on the same base64 BIO. It is meant as a single stream BIO.
  1200. Directions type
  1201. both BIO_s_mem()
  1202. one/both BIO_s_file()
  1203. both BIO_s_fd()
  1204. both BIO_s_socket()
  1205. both BIO_s_null()
  1206. both BIO_f_buffer()
  1207. one BIO_f_md()
  1208. one BIO_f_cipher()
  1209. one BIO_f_base64()
  1210. both BIO_f_ssl()
  1211. It is easy to mix one and two directional BIOs, all one has
  1212. to do is to keep two separate BIO pointers for reading and
  1213. writing and be careful about usage of underlying BIOs. The
  1214. SSL bio by it's very nature has to be two directional but
  1215. the BIO_push() command will push the one BIO into the SSL
  1216. BIO for both reading and writing.
  1217. The best example program to look at is apps/enc.c and/or perhaps apps/dgst.c.
  1218. ==== blowfish.doc ========================================================
  1219. The Blowfish library.
  1220. Blowfish is a block cipher that operates on 64bit (8 byte) quantities. It
  1221. uses variable size key, but 128bit (16 byte) key would normally be considered
  1222. good. It can be used in all the modes that DES can be used. This
  1223. library implements the ecb, cbc, cfb64, ofb64 modes.
  1224. Blowfish is quite a bit faster that DES, and much faster than IDEA or
  1225. RC2. It is one of the faster block ciphers.
  1226. For all calls that have an 'input' and 'output' variables, they can be the
  1227. same.
  1228. This library requires the inclusion of 'blowfish.h'.
  1229. All of the encryption functions take what is called an BF_KEY as an
  1230. argument. An BF_KEY is an expanded form of the Blowfish key.
  1231. For all modes of the Blowfish algorithm, the BF_KEY used for
  1232. decryption is the same one that was used for encryption.
  1233. The define BF_ENCRYPT is passed to specify encryption for the functions
  1234. that require an encryption/decryption flag. BF_DECRYPT is passed to
  1235. specify decryption.
  1236. Please note that any of the encryption modes specified in my DES library
  1237. could be used with Blowfish. I have only implemented ecb, cbc, cfb64 and
  1238. ofb64 for the following reasons.
  1239. - ecb is the basic Blowfish encryption.
  1240. - cbc is the normal 'chaining' form for block ciphers.
  1241. - cfb64 can be used to encrypt single characters, therefore input and output
  1242. do not need to be a multiple of 8.
  1243. - ofb64 is similar to cfb64 but is more like a stream cipher, not as
  1244. secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
  1245. - If you want triple Blowfish, thats 384 bits of key and you must be totally
  1246. obsessed with security. Still, if you want it, it is simple enough to
  1247. copy the function from the DES library and change the des_encrypt to
  1248. BF_encrypt; an exercise left for the paranoid reader :-).
  1249. The functions are as follows:
  1250. void BF_set_key(
  1251. BF_KEY *ks;
  1252. int len;
  1253. unsigned char *key;
  1254. BF_set_key converts an 'len' byte key into a BF_KEY.
  1255. A 'ks' is an expanded form of the 'key' which is used to
  1256. perform actual encryption. It can be regenerated from the Blowfish key
  1257. so it only needs to be kept when encryption or decryption is about
  1258. to occur. Don't save or pass around BF_KEY's since they
  1259. are CPU architecture dependent, 'key's are not. Blowfish is an
  1260. interesting cipher in that it can be used with a variable length
  1261. key. 'len' is the length of 'key' to be used as the key.
  1262. A 'len' of 16 is recomended by me, but blowfish can use upto
  1263. 72 bytes. As a warning, blowfish has a very very slow set_key
  1264. function, it actually runs BF_encrypt 521 times.
  1265. void BF_encrypt(unsigned long *data, BF_KEY *key);
  1266. void BF_decrypt(unsigned long *data, BF_KEY *key);
  1267. These are the Blowfish encryption function that gets called by just
  1268. about every other Blowfish routine in the library. You should not
  1269. use this function except to implement 'modes' of Blowfish.
  1270. I say this because the
  1271. functions that call this routine do the conversion from 'char *' to
  1272. long, and this needs to be done to make sure 'non-aligned' memory
  1273. access do not occur.
  1274. Data is a pointer to 2 unsigned long's and key is the
  1275. BF_KEY to use.
  1276. void BF_ecb_encrypt(
  1277. unsigned char *in,
  1278. unsigned char *out,
  1279. BF_KEY *key,
  1280. int encrypt);
  1281. This is the basic Electronic Code Book form of Blowfish (in DES this
  1282. mode is called Electronic Code Book so I'm going to use the term
  1283. for blowfish as well.
  1284. Input is encrypted into output using the key represented by
  1285. key. Depending on the encrypt, encryption or
  1286. decryption occurs. Input is 8 bytes long and output is 8 bytes.
  1287. void BF_cbc_encrypt(
  1288. unsigned char *in,
  1289. unsigned char *out,
  1290. long length,
  1291. BF_KEY *ks,
  1292. unsigned char *ivec,
  1293. int encrypt);
  1294. This routine implements Blowfish in Cipher Block Chaining mode.
  1295. Input, which should be a multiple of 8 bytes is encrypted
  1296. (or decrypted) to output which will also be a multiple of 8 bytes.
  1297. The number of bytes is in length (and from what I've said above,
  1298. should be a multiple of 8). If length is not a multiple of 8, bad
  1299. things will probably happen. ivec is the initialisation vector.
  1300. This function updates iv after each call so that it can be passed to
  1301. the next call to BF_cbc_encrypt().
  1302. void BF_cfb64_encrypt(
  1303. unsigned char *in,
  1304. unsigned char *out,
  1305. long length,
  1306. BF_KEY *schedule,
  1307. unsigned char *ivec,
  1308. int *num,
  1309. int encrypt);
  1310. This is one of the more useful functions in this Blowfish library, it
  1311. implements CFB mode of Blowfish with 64bit feedback.
  1312. This allows you to encrypt an arbitrary number of bytes,
  1313. you do not require 8 byte padding. Each call to this
  1314. routine will encrypt the input bytes to output and then update ivec
  1315. and num. Num contains 'how far' we are though ivec.
  1316. 'Encrypt' is used to indicate encryption or decryption.
  1317. CFB64 mode operates by using the cipher to generate a stream
  1318. of bytes which is used to encrypt the plain text.
  1319. The cipher text is then encrypted to generate the next 64 bits to
  1320. be xored (incrementally) with the next 64 bits of plain
  1321. text. As can be seen from this, to encrypt or decrypt,
  1322. the same 'cipher stream' needs to be generated but the way the next
  1323. block of data is gathered for encryption is different for
  1324. encryption and decryption.
  1325. void BF_ofb64_encrypt(
  1326. unsigned char *in,
  1327. unsigned char *out,
  1328. long length,
  1329. BF_KEY *schedule,
  1330. unsigned char *ivec,
  1331. int *num);
  1332. This functions implements OFB mode of Blowfish with 64bit feedback.
  1333. This allows you to encrypt an arbitrary number of bytes,
  1334. you do not require 8 byte padding. Each call to this
  1335. routine will encrypt the input bytes to output and then update ivec
  1336. and num. Num contains 'how far' we are though ivec.
  1337. This is in effect a stream cipher, there is no encryption or
  1338. decryption mode.
  1339. For reading passwords, I suggest using des_read_pw_string() from my DES library.
  1340. To generate a password from a text string, I suggest using MD5 (or MD2) to
  1341. produce a 16 byte message digest that can then be passed directly to
  1342. BF_set_key().
  1343. =====
  1344. For more information about the specific Blowfish modes in this library
  1345. (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
  1346. documentation on my DES library. What is said about DES is directly
  1347. applicable for Blowfish.
  1348. ==== bn.doc ========================================================
  1349. The Big Number library.
  1350. #include "bn.h" when using this library.
  1351. This big number library was written for use in implementing the RSA and DH
  1352. public key encryption algorithms. As such, features such as negative
  1353. numbers have not been extensively tested but they should work as expected.
  1354. This library uses dynamic memory allocation for storing its data structures
  1355. and so there are no limit on the size of the numbers manipulated by these
  1356. routines but there is always the requirement to check return codes from
  1357. functions just in case a memory allocation error has occurred.
  1358. The basic object in this library is a BIGNUM. It is used to hold a single
  1359. large integer. This type should be considered opaque and fields should not
  1360. be modified or accessed directly.
  1361. typedef struct bignum_st
  1362. {
  1363. int top; /* Index of last used d. */
  1364. BN_ULONG *d; /* Pointer to an array of 'BITS2' bit chunks. */
  1365. int max; /* Size of the d array. */
  1366. int neg;
  1367. } BIGNUM;
  1368. The big number is stored in a malloced array of BN_ULONG's. A BN_ULONG can
  1369. be either 16, 32 or 64 bits in size, depending on the 'number of bits'
  1370. specified in bn.h.
  1371. The 'd' field is this array. 'max' is the size of the 'd' array that has
  1372. been allocated. 'top' is the 'last' entry being used, so for a value of 4,
  1373. bn.d[0]=4 and bn.top=1. 'neg' is 1 if the number is negative.
  1374. When a BIGNUM is '0', the 'd' field can be NULL and top == 0.
  1375. Various routines in this library require the use of 'temporary' BIGNUM
  1376. variables during their execution. Due to the use of dynamic memory
  1377. allocation to create BIGNUMs being rather expensive when used in
  1378. conjunction with repeated subroutine calls, the BN_CTX structure is
  1379. used. This structure contains BN_CTX BIGNUMs. BN_CTX
  1380. is the maximum number of temporary BIGNUMs any publicly exported
  1381. function will use.
  1382. #define BN_CTX 12
  1383. typedef struct bignum_ctx
  1384. {
  1385. int tos; /* top of stack */
  1386. BIGNUM *bn[BN_CTX]; /* The variables */
  1387. } BN_CTX;
  1388. The functions that follow have been grouped according to function. Most
  1389. arithmetic functions return a result in the first argument, sometimes this
  1390. first argument can also be an input parameter, sometimes it cannot. These
  1391. restrictions are documented.
  1392. extern BIGNUM *BN_value_one;
  1393. There is one variable defined by this library, a BIGNUM which contains the
  1394. number 1. This variable is useful for use in comparisons and assignment.
  1395. Get Size functions.
  1396. int BN_num_bits(BIGNUM *a);
  1397. This function returns the size of 'a' in bits.
  1398. int BN_num_bytes(BIGNUM *a);
  1399. This function (macro) returns the size of 'a' in bytes.
  1400. For conversion of BIGNUMs to byte streams, this is the number of
  1401. bytes the output string will occupy. If the output byte
  1402. format specifies that the 'top' bit indicates if the number is
  1403. signed, so an extra '0' byte is required if the top bit on a
  1404. positive number is being written, it is upto the application to
  1405. make this adjustment. Like I said at the start, I don't
  1406. really support negative numbers :-).
  1407. Creation/Destruction routines.
  1408. BIGNUM *BN_new();
  1409. Return a new BIGNUM object. The number initially has a value of 0. If
  1410. there is an error, NULL is returned.
  1411. void BN_free(BIGNUM *a);
  1412. Free()s a BIGNUM.
  1413. void BN_clear(BIGNUM *a);
  1414. Sets 'a' to a value of 0 and also zeros all unused allocated
  1415. memory. This function is used to clear a variable of 'sensitive'
  1416. data that was held in it.
  1417. void BN_clear_free(BIGNUM *a);
  1418. This function zeros the memory used by 'a' and then free()'s it.
  1419. This function should be used to BN_free() BIGNUMS that have held
  1420. sensitive numeric values like RSA private key values. Both this
  1421. function and BN_clear tend to only be used by RSA and DH routines.
  1422. BN_CTX *BN_CTX_new(void);
  1423. Returns a new BN_CTX. NULL on error.
  1424. void BN_CTX_free(BN_CTX *c);
  1425. Free a BN_CTX structure. The BIGNUMs in 'c' are BN_clear_free()ed.
  1426. BIGNUM *bn_expand(BIGNUM *b, int bits);
  1427. This is an internal function that should not normally be used. It
  1428. ensures that 'b' has enough room for a 'bits' bit number. It is
  1429. mostly used by the various BIGNUM routines. If there is an error,
  1430. NULL is returned. if not, 'b' is returned.
  1431. BIGNUM *BN_copy(BIGNUM *to, BIGNUM *from);
  1432. The 'from' is copied into 'to'. NULL is returned if there is an
  1433. error, otherwise 'to' is returned.
  1434. BIGNUM *BN_dup(BIGNUM *a);
  1435. A new BIGNUM is created and returned containing the value of 'a'.
  1436. NULL is returned on error.
  1437. Comparison and Test Functions.
  1438. int BN_is_zero(BIGNUM *a)
  1439. Return 1 if 'a' is zero, else 0.
  1440. int BN_is_one(a)
  1441. Return 1 is 'a' is one, else 0.
  1442. int BN_is_word(a,w)
  1443. Return 1 if 'a' == w, else 0. 'w' is a BN_ULONG.
  1444. int BN_cmp(BIGNUM *a, BIGNUM *b);
  1445. Return -1 if 'a' is less than 'b', 0 if 'a' and 'b' are the same
  1446. and 1 is 'a' is greater than 'b'. This is a signed comparison.
  1447. int BN_ucmp(BIGNUM *a, BIGNUM *b);
  1448. This function is the same as BN_cmp except that the comparison
  1449. ignores the sign of the numbers.
  1450. Arithmetic Functions
  1451. For all of these functions, 0 is returned if there is an error and 1 is
  1452. returned for success. The return value should always be checked. eg.
  1453. if (!BN_add(r,a,b)) goto err;
  1454. Unless explicitly mentioned, the 'return' value can be one of the
  1455. 'parameters' to the function.
  1456. int BN_add(BIGNUM *r, BIGNUM *a, BIGNUM *b);
  1457. Add 'a' and 'b' and return the result in 'r'. This is r=a+b.
  1458. int BN_sub(BIGNUM *r, BIGNUM *a, BIGNUM *b);
  1459. Subtract 'a' from 'b' and put the result in 'r'. This is r=a-b.
  1460. int BN_lshift(BIGNUM *r, BIGNUM *a, int n);
  1461. Shift 'a' left by 'n' bits. This is r=a*(2^n).
  1462. int BN_lshift1(BIGNUM *r, BIGNUM *a);
  1463. Shift 'a' left by 1 bit. This form is more efficient than
  1464. BN_lshift(r,a,1). This is r=a*2.
  1465. int BN_rshift(BIGNUM *r, BIGNUM *a, int n);
  1466. Shift 'a' right by 'n' bits. This is r=int(a/(2^n)).
  1467. int BN_rshift1(BIGNUM *r, BIGNUM *a);
  1468. Shift 'a' right by 1 bit. This form is more efficient than
  1469. BN_rshift(r,a,1). This is r=int(a/2).
  1470. int BN_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b);
  1471. Multiply a by b and return the result in 'r'. 'r' must not be
  1472. either 'a' or 'b'. It has to be a different BIGNUM.
  1473. This is r=a*b.
  1474. int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx);
  1475. Multiply a by a and return the result in 'r'. 'r' must not be
  1476. 'a'. This function is alot faster than BN_mul(r,a,a). This is r=a*a.
  1477. int BN_div(BIGNUM *dv, BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
  1478. Divide 'm' by 'd' and return the result in 'dv' and the remainder
  1479. in 'rem'. Either of 'dv' or 'rem' can be NULL in which case that
  1480. value is not returned. 'ctx' needs to be passed as a source of
  1481. temporary BIGNUM variables.
  1482. This is dv=int(m/d), rem=m%d.
  1483. int BN_mod(BIGNUM *rem, BIGNUM *m, BIGNUM *d, BN_CTX *ctx);
  1484. Find the remainder of 'm' divided by 'd' and return it in 'rem'.
  1485. 'ctx' holds the temporary BIGNUMs required by this function.
  1486. This function is more efficient than BN_div(NULL,rem,m,d,ctx);
  1487. This is rem=m%d.
  1488. int BN_mod_mul(BIGNUM *r, BIGNUM *a, BIGNUM *b, BIGNUM *m,BN_CTX *ctx);
  1489. Multiply 'a' by 'b' and return the remainder when divided by 'm'.
  1490. 'ctx' holds the temporary BIGNUMs required by this function.
  1491. This is r=(a*b)%m.
  1492. int BN_mod_exp(BIGNUM *r, BIGNUM *a, BIGNUM *p, BIGNUM *m,BN_CTX *ctx);
  1493. Raise 'a' to the 'p' power and return the remainder when divided by
  1494. 'm'. 'ctx' holds the temporary BIGNUMs required by this function.
  1495. This is r=(a^p)%m.
  1496. int BN_reciprocal(BIGNUM *r, BIGNUM *m, BN_CTX *ctx);
  1497. Return the reciprocal of 'm'. 'ctx' holds the temporary variables
  1498. required. This function returns -1 on error, otherwise it returns
  1499. the number of bits 'r' is shifted left to make 'r' into an integer.
  1500. This number of bits shifted is required in BN_mod_mul_reciprocal().
  1501. This is r=(1/m)<<(BN_num_bits(m)+1).
  1502. int BN_mod_mul_reciprocal(BIGNUM *r, BIGNUM *x, BIGNUM *y, BIGNUM *m,
  1503. BIGNUM *i, int nb, BN_CTX *ctx);
  1504. This function is used to perform an efficient BN_mod_mul()
  1505. operation. If one is going to repeatedly perform BN_mod_mul() with
  1506. the same modulus is worth calculating the reciprocal of the modulus
  1507. and then using this function. This operation uses the fact that
  1508. a/b == a*r where r is the reciprocal of b. On modern computers
  1509. multiplication is very fast and big number division is very slow.
  1510. 'x' is multiplied by 'y' and then divided by 'm' and the remainder
  1511. is returned. 'i' is the reciprocal of 'm' and 'nb' is the number
  1512. of bits as returned from BN_reciprocal(). Normal usage is as follows.
  1513. bn=BN_reciprocal(i,m);
  1514. for (...)
  1515. { BN_mod_mul_reciprocal(r,x,y,m,i,bn,ctx); }
  1516. This is r=(x*y)%m. Internally it is approximately
  1517. r=(x*y)-m*(x*y/m) or r=(x*y)-m*((x*y*i) >> bn)
  1518. This function is used in BN_mod_exp() and BN_is_prime().
  1519. Assignment Operations
  1520. int BN_one(BIGNUM *a)
  1521. Set 'a' to hold the value one.
  1522. This is a=1.
  1523. int BN_zero(BIGNUM *a)
  1524. Set 'a' to hold the value zero.
  1525. This is a=0.
  1526. int BN_set_word(BIGNUM *a, unsigned long w);
  1527. Set 'a' to hold the value of 'w'. 'w' is an unsigned long.
  1528. This is a=w.
  1529. unsigned long BN_get_word(BIGNUM *a);
  1530. Returns 'a' in an unsigned long. Not remarkably, often 'a' will
  1531. be bigger than a word, in which case 0xffffffffL is returned.
  1532. Word Operations
  1533. These functions are much more efficient that the normal bignum arithmetic
  1534. operations.
  1535. BN_ULONG BN_mod_word(BIGNUM *a, unsigned long w);
  1536. Return the remainder of 'a' divided by 'w'.
  1537. This is return(a%w).
  1538. int BN_add_word(BIGNUM *a, unsigned long w);
  1539. Add 'w' to 'a'. This function does not take the sign of 'a' into
  1540. account. This is a+=w;
  1541. Bit operations.
  1542. int BN_is_bit_set(BIGNUM *a, int n);
  1543. This function return 1 if bit 'n' is set in 'a' else 0.
  1544. int BN_set_bit(BIGNUM *a, int n);
  1545. This function sets bit 'n' to 1 in 'a'.
  1546. This is a&= ~(1<<n);
  1547. int BN_clear_bit(BIGNUM *a, int n);
  1548. This function sets bit 'n' to zero in 'a'. Return 0 if less
  1549. than 'n' bits in 'a' else 1. This is a&= ~(1<<n);
  1550. int BN_mask_bits(BIGNUM *a, int n);
  1551. Truncate 'a' to n bits long. This is a&= ~((~0)<<n)
  1552. Format conversion routines.
  1553. BIGNUM *BN_bin2bn(unsigned char *s, int len,BIGNUM *ret);
  1554. This function converts 'len' bytes in 's' into a BIGNUM which
  1555. is put in 'ret'. If ret is NULL, a new BIGNUM is created.
  1556. Either this new BIGNUM or ret is returned. The number is
  1557. assumed to be in bigendian form in 's'. By this I mean that
  1558. to 'ret' is created as follows for 'len' == 5.
  1559. ret = s[0]*2^32 + s[1]*2^24 + s[2]*2^16 + s[3]*2^8 + s[4];
  1560. This function cannot be used to convert negative numbers. It
  1561. is always assumed the number is positive. The application
  1562. needs to diddle the 'neg' field of th BIGNUM its self.
  1563. The better solution would be to save the numbers in ASN.1 format
  1564. since this is a defined standard for storing big numbers.
  1565. Look at the functions
  1566. ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai);
  1567. BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai,BIGNUM *bn);
  1568. int i2d_ASN1_INTEGER(ASN1_INTEGER *a,unsigned char **pp);
  1569. ASN1_INTEGER *d2i_ASN1_INTEGER(ASN1_INTEGER **a,unsigned char **pp,
  1570. long length;
  1571. int BN_bn2bin(BIGNUM *a, unsigned char *to);
  1572. This function converts 'a' to a byte string which is put into
  1573. 'to'. The representation is big-endian in that the most
  1574. significant byte of 'a' is put into to[0]. This function
  1575. returns the number of bytes used to hold 'a'. BN_num_bytes(a)
  1576. would return the same value and can be used to determine how
  1577. large 'to' needs to be. If the number is negative, this
  1578. information is lost. Since this library was written to
  1579. manipulate large positive integers, the inability to save and
  1580. restore them is not considered to be a problem by me :-).
  1581. As for BN_bin2bn(), look at the ASN.1 integer encoding funtions
  1582. for SSLeay. They use BN_bin2bn() and BN_bn2bin() internally.
  1583. char *BN_bn2ascii(BIGNUM *a);
  1584. This function returns a malloc()ed string that contains the
  1585. ascii hexadecimal encoding of 'a'. The number is in bigendian
  1586. format with a '-' in front if the number is negative.
  1587. int BN_ascii2bn(BIGNUM **bn, char *a);
  1588. The inverse of BN_bn2ascii. The function returns the number of
  1589. characters from 'a' were processed in generating a the bignum.
  1590. error is inticated by 0 being returned. The number is a
  1591. hex digit string, optionally with a leading '-'. If *bn
  1592. is null, a BIGNUM is created and returned via that variable.
  1593. int BN_print_fp(FILE *fp, BIGNUM *a);
  1594. 'a' is printed to file pointer 'fp'. It is in the same format
  1595. that is output from BN_bn2ascii(). 0 is returned on error,
  1596. 1 if things are ok.
  1597. int BN_print(BIO *bp, BIGNUM *a);
  1598. Same as BN_print except that the output is done to the SSLeay libraries
  1599. BIO routines. BN_print_fp() actually calls this function.
  1600. Miscellaneous Routines.
  1601. int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
  1602. This function returns in 'rnd' a random BIGNUM that is bits
  1603. long. If bottom is 1, the number returned is odd. If top is set,
  1604. the top 2 bits of the number are set. This is useful because if
  1605. this is set, 2 'n; bit numbers multiplied together will return a 2n
  1606. bit number. If top was not set, they could produce a 2n-1 bit
  1607. number.
  1608. BIGNUM *BN_mod_inverse(BIGNUM *a, BIGNUM *n,BN_CTX *ctx);
  1609. This function create a new BIGNUM and returns it. This number
  1610. is the inverse mod 'n' of 'a'. By this it is meant that the
  1611. returned value 'r' satisfies (a*r)%n == 1. This function is
  1612. used in the generation of RSA keys. 'ctx', as per usual,
  1613. is used to hold temporary variables that are required by the
  1614. function. NULL is returned on error.
  1615. int BN_gcd(BIGNUM *r,BIGNUM *a,BIGNUM *b,BN_CTX *ctx);
  1616. 'r' has the greatest common divisor of 'a' and 'b'. 'ctx' is
  1617. used for temporary variables and 0 is returned on error.
  1618. int BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(),BN_CTX *ctx,
  1619. char *cb_arg);
  1620. This function is used to check if a BIGNUM ('p') is prime.
  1621. It performs this test by using the Miller-Rabin randomised
  1622. primality test. This is a probalistic test that requires a
  1623. number of rounds to ensure the number is prime to a high
  1624. degree of probability. Since this can take quite some time, a
  1625. callback function can be passed and it will be called each
  1626. time 'p' passes a round of the prime testing. 'callback' will
  1627. be called as follows, callback(1,n,cb_arg) where n is the number of
  1628. the round, just passed. As per usual 'ctx' contains temporary
  1629. variables used. If ctx is NULL, it does not matter, a local version
  1630. will be malloced. This parameter is present to save some mallocing
  1631. inside the function but probably could be removed.
  1632. 0 is returned on error.
  1633. 'ncheck' is the number of Miller-Rabin tests to run. It is
  1634. suggested to use the value 'BN_prime_checks' by default.
  1635. BIGNUM *BN_generate_prime(
  1636. int bits,
  1637. int strong,
  1638. BIGNUM *a,
  1639. BIGNUM *rems,
  1640. void (*callback)());
  1641. char *cb_arg
  1642. This function is used to generate prime numbers. It returns a
  1643. new BIGNUM that has a high probability of being a prime.
  1644. 'bits' is the number of bits that
  1645. are to be in the prime. If 'strong' is true, the returned prime
  1646. will also be a strong prime ((p-1)/2 is also prime).
  1647. While searching for the prime ('p'), we
  1648. can add the requirement that the prime fill the following
  1649. condition p%a == rem. This can be used to help search for
  1650. primes with specific features, which is required when looking
  1651. for primes suitable for use with certain 'g' values in the
  1652. Diffie-Hellman key exchange algorithm. If 'a' is NULL,
  1653. this condition is not checked. If rem is NULL, rem is assumed
  1654. to be 1. Since this search for a prime
  1655. can take quite some time, if callback is not NULL, it is called
  1656. in the following situations.
  1657. We have a suspected prime (from a quick sieve),
  1658. callback(0,sus_prime++,cb_arg). Each item to be passed to BN_is_prime().
  1659. callback(1,round++,cb_arg). Each successful 'round' in BN_is_prime().
  1660. callback(2,round,cb_arg). For each successful BN_is_prime() test.
  1661. Hints
  1662. -----
  1663. DSA wants 64*32 to use word mont mul, but RSA wants to use full.
  1664. ==== callback.doc ========================================================
  1665. Callback functions used in SSLeay.
  1666. --------------------------
  1667. The BIO library.
  1668. Each BIO structure can have a callback defined against it. This callback is
  1669. called 2 times for each BIO 'function'. It is passed 6 parameters.
  1670. BIO_debug_callback() is an example callback which is defined in
  1671. crypto/buffer/bio_cb.c and is used in apps/dgst.c This is intended mostly
  1672. for debuging or to notify the application of IO.
  1673. long BIO_debug_callback(BIO *bio,int cmd,char *argp,int argi,long argl,
  1674. long ret);
  1675. bio is the BIO being called, cmd is the type of BIO function being called.
  1676. Look at the BIO_CB_* defines in buffer.h. Argp and argi are the arguments
  1677. passed to BIO_read(), BIO_write, BIO_gets(), BIO_puts(). In the case of
  1678. BIO_ctrl(), argl is also defined. The first time the callback is called,
  1679. before the underlying function has been executed, 0 is passed as 'ret', and
  1680. if the return code from the callback is not > 0, the call is aborted
  1681. and the returned <= 0 value is returned.
  1682. The second time the callback is called, the 'cmd' value also has
  1683. BIO_CB_RETURN logically 'or'ed with it. The 'ret' value is the value returned
  1684. from the actuall function call and whatever the callback returns is returned
  1685. from the BIO function.
  1686. BIO_set_callback(b,cb) can be used to set the callback function
  1687. (b is a BIO), and BIO_set_callback_arg(b,arg) can be used to
  1688. set the cb_arg argument in the BIO strucutre. This field is only intended
  1689. to be used by application, primarily in the callback function since it is
  1690. accessable since the BIO is passed.
  1691. --------------------------
  1692. The PEM library.
  1693. The pem library only really uses one type of callback,
  1694. static int def_callback(char *buf, int num, int verify);
  1695. which is used to return a password string if required.
  1696. 'buf' is the buffer to put the string in. 'num' is the size of 'buf'
  1697. and 'verify' is used to indicate that the password should be checked.
  1698. This last flag is mostly used when reading a password for encryption.
  1699. For all of these functions, a NULL callback will call the above mentioned
  1700. default callback. This default function does not work under Windows 3.1.
  1701. For other machines, it will use an application defined prompt string
  1702. (EVP_set_pw_prompt(), which defines a library wide prompt string)
  1703. if defined, otherwise it will use it's own PEM password prompt.
  1704. It will then call EVP_read_pw_string() to get a password from the console.
  1705. If your application wishes to use nice fancy windows to retrieve passwords,
  1706. replace this function. The callback should return the number of bytes read
  1707. into 'buf'. If the number of bytes <= 0, it is considered an error.
  1708. Functions that take this callback are listed below. For the 'read' type
  1709. functions, the callback will only be required if the PEM data is encrypted.
  1710. For the Write functions, normally a password can be passed in 'kstr', of
  1711. 'klen' bytes which will be used if the 'enc' cipher is not NULL. If
  1712. 'kstr' is NULL, the callback will be used to retrieve a password.
  1713. int PEM_do_header (EVP_CIPHER_INFO *cipher, unsigned char *data,long *len,
  1714. int (*callback)());
  1715. char *PEM_ASN1_read_bio(char *(*d2i)(),char *name,BIO *bp,char **x,int (*cb)());
  1716. char *PEM_ASN1_read(char *(*d2i)(),char *name,FILE *fp,char **x,int (*cb)());
  1717. int PEM_ASN1_write_bio(int (*i2d)(),char *name,BIO *bp,char *x,
  1718. EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
  1719. int PEM_ASN1_write(int (*i2d)(),char *name,FILE *fp,char *x,
  1720. EVP_CIPHER *enc,unsigned char *kstr,int klen,int (*callback)());
  1721. STACK *PEM_X509_INFO_read(FILE *fp, STACK *sk, int (*cb)());
  1722. STACK *PEM_X509_INFO_read_bio(BIO *fp, STACK *sk, int (*cb)());
  1723. #define PEM_write_RSAPrivateKey(fp,x,enc,kstr,klen,cb)
  1724. #define PEM_write_DSAPrivateKey(fp,x,enc,kstr,klen,cb)
  1725. #define PEM_write_bio_RSAPrivateKey(bp,x,enc,kstr,klen,cb)
  1726. #define PEM_write_bio_DSAPrivateKey(bp,x,enc,kstr,klen,cb)
  1727. #define PEM_read_SSL_SESSION(fp,x,cb)
  1728. #define PEM_read_X509(fp,x,cb)
  1729. #define PEM_read_X509_REQ(fp,x,cb)
  1730. #define PEM_read_X509_CRL(fp,x,cb)
  1731. #define PEM_read_RSAPrivateKey(fp,x,cb)
  1732. #define PEM_read_DSAPrivateKey(fp,x,cb)
  1733. #define PEM_read_PrivateKey(fp,x,cb)
  1734. #define PEM_read_PKCS7(fp,x,cb)
  1735. #define PEM_read_DHparams(fp,x,cb)
  1736. #define PEM_read_bio_SSL_SESSION(bp,x,cb)
  1737. #define PEM_read_bio_X509(bp,x,cb)
  1738. #define PEM_read_bio_X509_REQ(bp,x,cb)
  1739. #define PEM_read_bio_X509_CRL(bp,x,cb)
  1740. #define PEM_read_bio_RSAPrivateKey(bp,x,cb)
  1741. #define PEM_read_bio_DSAPrivateKey(bp,x,cb)
  1742. #define PEM_read_bio_PrivateKey(bp,x,cb)
  1743. #define PEM_read_bio_PKCS7(bp,x,cb)
  1744. #define PEM_read_bio_DHparams(bp,x,cb)
  1745. int i2d_Netscape_RSA(RSA *a, unsigned char **pp, int (*cb)());
  1746. RSA *d2i_Netscape_RSA(RSA **a, unsigned char **pp, long length, int (*cb)());
  1747. Now you will notice that macros like
  1748. #define PEM_write_X509(fp,x) \
  1749. PEM_ASN1_write((int (*)())i2d_X509,PEM_STRING_X509,fp, \
  1750. (char *)x, NULL,NULL,0,NULL)
  1751. Don't do encryption normally. If you want to PEM encrypt your X509 structure,
  1752. either just call PEM_ASN1_write directly or just define your own
  1753. macro variant. As you can see, this macro just sets all encryption related
  1754. parameters to NULL.
  1755. --------------------------
  1756. The SSL library.
  1757. #define SSL_set_info_callback(ssl,cb)
  1758. #define SSL_CTX_set_info_callback(ctx,cb)
  1759. void callback(SSL *ssl,int location,int ret)
  1760. This callback is called each time around the SSL_connect()/SSL_accept()
  1761. state machine. So it will be called each time the SSL protocol progresses.
  1762. It is mostly present for use when debugging. When SSL_connect() or
  1763. SSL_accept() return, the location flag is SSL_CB_ACCEPT_EXIT or
  1764. SSL_CB_CONNECT_EXIT and 'ret' is the value about to be returned.
  1765. Have a look at the SSL_CB_* defines in ssl.h. If an info callback is defined
  1766. against the SSL_CTX, it is called unless there is one set against the SSL.
  1767. Have a look at
  1768. void client_info_callback() in apps/s_client() for an example.
  1769. Certificate verification.
  1770. void SSL_set_verify(SSL *s, int mode, int (*callback) ());
  1771. void SSL_CTX_set_verify(SSL_CTX *ctx,int mode,int (*callback)());
  1772. This callback is used to help verify client and server X509 certificates.
  1773. It is actually passed to X509_cert_verify(), along with the SSL structure
  1774. so you have to read about X509_cert_verify() :-). The SSL_CTX version is used
  1775. if the SSL version is not defined. X509_cert_verify() is the function used
  1776. by the SSL part of the library to verify certificates. This function is
  1777. nearly always defined by the application.
  1778. void SSL_CTX_set_cert_verify_cb(SSL_CTX *ctx, int (*cb)(),char *arg);
  1779. int callback(char *arg,SSL *s,X509 *xs,STACK *cert_chain);
  1780. This call is used to replace the SSLeay certificate verification code.
  1781. The 'arg' is kept in the SSL_CTX and is passed to the callback.
  1782. If the callback returns 0, the certificate is rejected, otherwise it
  1783. is accepted. The callback is replacing the X509_cert_verify() call.
  1784. This feature is not often used, but if you wished to implement
  1785. some totally different certificate authentication system, this 'hook' is
  1786. vital.
  1787. SSLeay keeps a cache of session-ids against each SSL_CTX. These callbacks can
  1788. be used to notify the application when a SSL_SESSION is added to the cache
  1789. or to retrieve a SSL_SESSION that is not in the cache from the application.
  1790. #define SSL_CTX_sess_set_get_cb(ctx,cb)
  1791. SSL_SESSION *callback(SSL *s,char *session_id,int session_id_len,int *copy);
  1792. If defined, this callback is called to return the SESSION_ID for the
  1793. session-id in 'session_id', of 'session_id_len' bytes. 'copy' is set to 1
  1794. if the server is to 'take a copy' of the SSL_SESSION structure. It is 0
  1795. if the SSL_SESSION is being 'passed in' so the SSLeay library is now
  1796. responsible for 'free()ing' the structure. Basically it is used to indicate
  1797. if the reference count on the SSL_SESSION structure needs to be incremented.
  1798. #define SSL_CTX_sess_set_new_cb(ctx,cb)
  1799. int callback(SSL *s, SSL_SESSION *sess);
  1800. When a new connection is established, if the SSL_SESSION is going to be added
  1801. to the cache, this callback is called. Return 1 if a 'copy' is required,
  1802. otherwise, return 0. This return value just causes the reference count
  1803. to be incremented (on return of a 1), this means the application does
  1804. not need to worry about incrementing the refernece count (and the
  1805. locking that implies in a multi-threaded application).
  1806. void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx,int (*cb)());
  1807. This sets the SSL password reading function.
  1808. It is mostly used for windowing applications
  1809. and used by PEM_read_bio_X509() and PEM_read_bio_RSAPrivateKey()
  1810. calls inside the SSL library. The only reason this is present is because the
  1811. calls to PEM_* functions is hidden in the SSLeay library so you have to
  1812. pass in the callback some how.
  1813. #define SSL_CTX_set_client_cert_cb(ctx,cb)
  1814. int callback(SSL *s,X509 **x509, EVP_PKEY **pkey);
  1815. Called when a client certificate is requested but there is not one set
  1816. against the SSL_CTX or the SSL. If the callback returns 1, x509 and
  1817. pkey need to point to valid data. The library will free these when
  1818. required so if the application wants to keep these around, increment
  1819. their reference counts. If 0 is returned, no client cert is
  1820. available. If -1 is returned, it is assumed that the callback needs
  1821. to be called again at a later point in time. SSL_connect will return
  1822. -1 and SSL_want_x509_lookup(ssl) returns true. Remember that
  1823. application data can be attached to an SSL structure via the
  1824. SSL_set_app_data(SSL *ssl,char *data) call.
  1825. --------------------------
  1826. The X509 library.
  1827. int X509_cert_verify(CERTIFICATE_CTX *ctx,X509 *xs, int (*cb)(),
  1828. int *error,char *arg,STACK *cert_chain);
  1829. int verify_callback(int ok,X509 *xs,X509 *xi,int depth,int error,char *arg,
  1830. STACK *cert_chain);
  1831. X509_cert_verify() is used to authenticate X509 certificates. The 'ctx' holds
  1832. the details of the various caches and files used to locate certificates.
  1833. 'xs' is the certificate to verify and 'cb' is the application callback (more
  1834. detail later). 'error' will be set to the error code and 'arg' is passed
  1835. to the 'cb' callback. Look at the VERIFY_* defines in crypto/x509/x509.h
  1836. When ever X509_cert_verify() makes a 'negative' decision about a
  1837. certitificate, the callback is called. If everything checks out, the
  1838. callback is called with 'VERIFY_OK' or 'VERIFY_ROOT_OK' (for a self
  1839. signed cert that is not the passed certificate).
  1840. The callback is passed the X509_cert_verify opinion of the certificate
  1841. in 'ok', the certificate in 'xs', the issuer certificate in 'xi',
  1842. the 'depth' of the certificate in the verification 'chain', the
  1843. VERIFY_* code in 'error' and the argument passed to X509_cert_verify()
  1844. in 'arg'. cert_chain is a list of extra certs to use if they are not
  1845. in the cache.
  1846. The callback can be used to look at the error reason, and then return 0
  1847. for an 'error' or '1' for ok. This will override the X509_cert_verify()
  1848. opinion of the certificates validity. Processing will continue depending on
  1849. the return value. If one just wishes to use the callback for informational
  1850. reason, just return the 'ok' parameter.
  1851. --------------------------
  1852. The BN and DH library.
  1853. BIGNUM *BN_generate_prime(int bits,int strong,BIGNUM *add,
  1854. BIGNUM *rem,void (*callback)(int,int));
  1855. int BN_is_prime(BIGNUM *p,int nchecks,void (*callback)(int,int),
  1856. Read doc/bn.doc for the description of these 2.
  1857. DH *DH_generate_parameters(int prime_len,int generator,
  1858. void (*callback)(int,int));
  1859. Read doc/bn.doc for the description of the callback, since it is just passed
  1860. to BN_generate_prime(), except that it is also called as
  1861. callback(3,0) by this function.
  1862. --------------------------
  1863. The CRYPTO library.
  1864. void CRYPTO_set_locking_callback(void (*func)(int mode,int type,char *file,
  1865. int line));
  1866. void CRYPTO_set_add_lock_callback(int (*func)(int *num,int mount,
  1867. int type,char *file, int line));
  1868. void CRYPTO_set_id_callback(unsigned long (*func)(void));
  1869. Read threads.doc for info on these ones.
  1870. ==== cipher.doc ========================================================
  1871. The Cipher subroutines.
  1872. These routines require "evp.h" to be included.
  1873. These functions are a higher level interface to the various cipher
  1874. routines found in this library. As such, they allow the same code to be
  1875. used to encrypt and decrypt via different ciphers with only a change
  1876. in an initial parameter. These routines also provide buffering for block
  1877. ciphers.
  1878. These routines all take a pointer to the following structure to specify
  1879. which cipher to use. If you wish to use a new cipher with these routines,
  1880. you would probably be best off looking an how an existing cipher is
  1881. implemented and copying it. At this point in time, I'm not going to go
  1882. into many details. This structure should be considered opaque
  1883. typedef struct pem_cipher_st
  1884. {
  1885. int type;
  1886. int block_size;
  1887. int key_len;
  1888. int iv_len;
  1889. void (*enc_init)(); /* init for encryption */
  1890. void (*dec_init)(); /* init for decryption */
  1891. void (*do_cipher)(); /* encrypt data */
  1892. } EVP_CIPHER;
  1893. The type field is the object NID of the cipher type
  1894. (read the section on Objects for an explanation of what a NID is).
  1895. The cipher block_size is how many bytes need to be passed
  1896. to the cipher at a time. Key_len is the
  1897. length of the key the cipher requires and iv_len is the length of the
  1898. initialisation vector required. enc_init is the function
  1899. called to initialise the ciphers context for encryption and dec_init is the
  1900. function to initialise for decryption (they need to be different, especially
  1901. for the IDEA cipher).
  1902. One reason for specifying the Cipher via a pointer to a structure
  1903. is that if you only use des-cbc, only the des-cbc routines will
  1904. be included when you link the program. If you passed an integer
  1905. that specified which cipher to use, the routine that mapped that
  1906. integer to a set of cipher functions would cause all the ciphers
  1907. to be link into the code. This setup also allows new ciphers
  1908. to be added by the application (with some restrictions).
  1909. The thirteen ciphers currently defined in this library are
  1910. EVP_CIPHER *EVP_des_ecb(); /* DES in ecb mode, iv=0, block=8, key= 8 */
  1911. EVP_CIPHER *EVP_des_ede(); /* DES in ecb ede mode, iv=0, block=8, key=16 */
  1912. EVP_CIPHER *EVP_des_ede3(); /* DES in ecb ede mode, iv=0, block=8, key=24 */
  1913. EVP_CIPHER *EVP_des_cfb(); /* DES in cfb mode, iv=8, block=1, key= 8 */
  1914. EVP_CIPHER *EVP_des_ede_cfb(); /* DES in ede cfb mode, iv=8, block=1, key=16 */
  1915. EVP_CIPHER *EVP_des_ede3_cfb();/* DES in ede cfb mode, iv=8, block=1, key=24 */
  1916. EVP_CIPHER *EVP_des_ofb(); /* DES in ofb mode, iv=8, block=1, key= 8 */
  1917. EVP_CIPHER *EVP_des_ede_ofb(); /* DES in ede ofb mode, iv=8, block=1, key=16 */
  1918. EVP_CIPHER *EVP_des_ede3_ofb();/* DES in ede ofb mode, iv=8, block=1, key=24 */
  1919. EVP_CIPHER *EVP_des_cbc(); /* DES in cbc mode, iv=8, block=8, key= 8 */
  1920. EVP_CIPHER *EVP_des_ede_cbc(); /* DES in cbc ede mode, iv=8, block=8, key=16 */
  1921. EVP_CIPHER *EVP_des_ede3_cbc();/* DES in cbc ede mode, iv=8, block=8, key=24 */
  1922. EVP_CIPHER *EVP_desx_cbc(); /* DES in desx cbc mode,iv=8, block=8, key=24 */
  1923. EVP_CIPHER *EVP_rc4(); /* RC4, iv=0, block=1, key=16 */
  1924. EVP_CIPHER *EVP_idea_ecb(); /* IDEA in ecb mode, iv=0, block=8, key=16 */
  1925. EVP_CIPHER *EVP_idea_cfb(); /* IDEA in cfb mode, iv=8, block=1, key=16 */
  1926. EVP_CIPHER *EVP_idea_ofb(); /* IDEA in ofb mode, iv=8, block=1, key=16 */
  1927. EVP_CIPHER *EVP_idea_cbc(); /* IDEA in cbc mode, iv=8, block=8, key=16 */
  1928. EVP_CIPHER *EVP_rc2_ecb(); /* RC2 in ecb mode, iv=0, block=8, key=16 */
  1929. EVP_CIPHER *EVP_rc2_cfb(); /* RC2 in cfb mode, iv=8, block=1, key=16 */
  1930. EVP_CIPHER *EVP_rc2_ofb(); /* RC2 in ofb mode, iv=8, block=1, key=16 */
  1931. EVP_CIPHER *EVP_rc2_cbc(); /* RC2 in cbc mode, iv=8, block=8, key=16 */
  1932. EVP_CIPHER *EVP_bf_ecb(); /* Blowfish in ecb mode,iv=0, block=8, key=16 */
  1933. EVP_CIPHER *EVP_bf_cfb(); /* Blowfish in cfb mode,iv=8, block=1, key=16 */
  1934. EVP_CIPHER *EVP_bf_ofb(); /* Blowfish in ofb mode,iv=8, block=1, key=16 */
  1935. EVP_CIPHER *EVP_bf_cbc(); /* Blowfish in cbc mode,iv=8, block=8, key=16 */
  1936. The meaning of the compound names is as follows.
  1937. des The base cipher is DES.
  1938. idea The base cipher is IDEA
  1939. rc4 The base cipher is RC4-128
  1940. rc2 The base cipher is RC2-128
  1941. ecb Electronic Code Book form of the cipher.
  1942. cbc Cipher Block Chaining form of the cipher.
  1943. cfb 64 bit Cipher Feedback form of the cipher.
  1944. ofb 64 bit Output Feedback form of the cipher.
  1945. ede The cipher is used in Encrypt, Decrypt, Encrypt mode. The first
  1946. and last keys are the same.
  1947. ede3 The cipher is used in Encrypt, Decrypt, Encrypt mode.
  1948. All the Cipher routines take a EVP_CIPHER_CTX pointer as an argument.
  1949. The state of the cipher is kept in this structure.
  1950. typedef struct EVP_CIPHER_Ctx_st
  1951. {
  1952. EVP_CIPHER *cipher;
  1953. int encrypt; /* encrypt or decrypt */
  1954. int buf_len; /* number we have left */
  1955. unsigned char buf[8];
  1956. union {
  1957. .... /* cipher specific stuff */
  1958. } c;
  1959. } EVP_CIPHER_CTX;
  1960. Cipher is a pointer the the EVP_CIPHER for the current context. The encrypt
  1961. flag indicates encryption or decryption. buf_len is the number of bytes
  1962. currently being held in buf.
  1963. The 'c' union holds the cipher specify context.
  1964. The following functions are to be used.
  1965. int EVP_read_pw_string(
  1966. char *buf,
  1967. int len,
  1968. char *prompt,
  1969. int verify,
  1970. This function is the same as des_read_pw_string() (des.doc).
  1971. void EVP_set_pw_prompt(char *prompt);
  1972. This function sets the 'default' prompt to use to use in
  1973. EVP_read_pw_string when the prompt parameter is NULL. If the
  1974. prompt parameter is NULL, this 'default prompt' feature is turned
  1975. off. Be warned, this is a global variable so weird things
  1976. will happen if it is used under Win16 and care must be taken
  1977. with a multi-threaded version of the library.
  1978. char *EVP_get_pw_prompt();
  1979. This returns a pointer to the default prompt string. NULL
  1980. if it is not set.
  1981. int EVP_BytesToKey(
  1982. EVP_CIPHER *type,
  1983. EVP_MD *md,
  1984. unsigned char *salt,
  1985. unsigned char *data,
  1986. int datal,
  1987. int count,
  1988. unsigned char *key,
  1989. unsigned char *iv);
  1990. This function is used to generate a key and an initialisation vector
  1991. for a specified cipher from a key string and a salt. Type
  1992. specifies the cipher the 'key' is being generated for. Md is the
  1993. message digest algorithm to use to generate the key and iv. The salt
  1994. is an optional 8 byte object that is used to help seed the key
  1995. generator.
  1996. If the salt value is NULL, it is just not used. Datal is the
  1997. number of bytes to use from 'data' in the key generation.
  1998. This function returns the key size for the specified cipher, if
  1999. data is NULL, this value is returns and no other
  2000. computation is performed. Count is
  2001. the number of times to loop around the key generator. I would
  2002. suggest leaving it's value as 1. Key and iv are the structures to
  2003. place the returning iv and key in. If they are NULL, no value is
  2004. generated for that particular value.
  2005. The algorithm used is as follows
  2006. /* M[] is an array of message digests
  2007. * MD() is the message digest function */
  2008. M[0]=MD(data . salt);
  2009. for (i=1; i<count; i++) M[0]=MD(M[0]);
  2010. i=1
  2011. while (data still needed for key and iv)
  2012. {
  2013. M[i]=MD(M[i-1] . data . salt);
  2014. for (i=1; i<count; i++) M[i]=MD(M[i]);
  2015. i++;
  2016. }
  2017. If the salt is NULL, it is not used.
  2018. The digests are concatenated together.
  2019. M = M[0] . M[1] . M[2] .......
  2020. For key= 8, iv=8 => key=M[0.. 8], iv=M[ 9 .. 16].
  2021. For key=16, iv=0 => key=M[0..16].
  2022. For key=16, iv=8 => key=M[0..16], iv=M[17 .. 24].
  2023. For key=24, iv=8 => key=M[0..24], iv=M[25 .. 32].
  2024. This routine will produce DES-CBC keys and iv that are compatible
  2025. with the PKCS-5 standard when md2 or md5 are used. If md5 is
  2026. used, the salt is NULL and count is 1, this routine will produce
  2027. the password to key mapping normally used with RC4.
  2028. I have attempted to logically extend the PKCS-5 standard to
  2029. generate keys and iv for ciphers that require more than 16 bytes,
  2030. if anyone knows what the correct standard is, please inform me.
  2031. When using sha or sha1, things are a bit different under this scheme,
  2032. since sha produces a 20 byte digest. So for ciphers requiring
  2033. 24 bits of data, 20 will come from the first MD and 4 will
  2034. come from the second.
  2035. I have considered having a separate function so this 'routine'
  2036. can be used without the requirement of passing a EVP_CIPHER *,
  2037. but I have decided to not bother. If you wish to use the
  2038. function without official EVP_CIPHER structures, just declare
  2039. a local one and set the key_len and iv_len fields to the
  2040. length you desire.
  2041. The following routines perform encryption and decryption 'by parts'. By
  2042. this I mean that there are groups of 3 routines. An Init function that is
  2043. used to specify a cipher and initialise data structures. An Update routine
  2044. that does encryption/decryption, one 'chunk' at a time. And finally a
  2045. 'Final' function that finishes the encryption/decryption process.
  2046. All these functions take a EVP_CIPHER pointer to specify which cipher to
  2047. encrypt/decrypt with. They also take a EVP_CIPHER_CTX object as an
  2048. argument. This structure is used to hold the state information associated
  2049. with the operation in progress.
  2050. void EVP_EncryptInit(
  2051. EVP_CIPHER_CTX *ctx,
  2052. EVP_CIPHER *type,
  2053. unsigned char *key,
  2054. unsigned char *iv);
  2055. This function initialise a EVP_CIPHER_CTX for encryption using the
  2056. cipher passed in the 'type' field. The cipher is initialised to use
  2057. 'key' as the key and 'iv' for the initialisation vector (if one is
  2058. required). If the type, key or iv is NULL, the value currently in the
  2059. EVP_CIPHER_CTX is reused. So to perform several decrypt
  2060. using the same cipher, key and iv, initialise with the cipher,
  2061. key and iv the first time and then for subsequent calls,
  2062. reuse 'ctx' but pass NULL for type, key and iv. You must make sure
  2063. to pass a key that is large enough for a particular cipher. I
  2064. would suggest using the EVP_BytesToKey() function.
  2065. void EVP_EncryptUpdate(
  2066. EVP_CIPHER_CTX *ctx,
  2067. unsigned char *out,
  2068. int *outl,
  2069. unsigned char *in,
  2070. int inl);
  2071. This function takes 'inl' bytes from 'in' and outputs bytes
  2072. encrypted by the cipher 'ctx' was initialised with into 'out'. The
  2073. number of bytes written to 'out' is put into outl. If a particular
  2074. cipher encrypts in blocks, less or more bytes than input may be
  2075. output. Currently the largest block size used by supported ciphers
  2076. is 8 bytes, so 'out' should have room for 'inl+7' bytes. Normally
  2077. EVP_EncryptInit() is called once, followed by lots and lots of
  2078. calls to EVP_EncryptUpdate, followed by a single EVP_EncryptFinal
  2079. call.
  2080. void EVP_EncryptFinal(
  2081. EVP_CIPHER_CTX *ctx,
  2082. unsigned char *out,
  2083. int *outl);
  2084. Because quite a large number of ciphers are block ciphers, there is
  2085. often an incomplete block to write out at the end of the
  2086. encryption. EVP_EncryptFinal() performs processing on this last
  2087. block. The last block in encoded in such a way that it is possible
  2088. to determine how many bytes in the last block are valid. For 8 byte
  2089. block size ciphers, if only 5 bytes in the last block are valid, the
  2090. last three bytes will be filled with the value 3. If only 2 were
  2091. valid, the other 6 would be filled with sixes. If all 8 bytes are
  2092. valid, a extra 8 bytes are appended to the cipher stream containing
  2093. nothing but 8 eights. These last bytes are output into 'out' and
  2094. the number of bytes written is put into 'outl' These last bytes
  2095. are output into 'out' and the number of bytes written is put into
  2096. 'outl'. This form of block cipher finalisation is compatible with
  2097. PKCS-5. Please remember that even if you are using ciphers like
  2098. RC4 that has no blocking and so the function will not write
  2099. anything into 'out', it would still be a good idea to pass a
  2100. variable for 'out' that can hold 8 bytes just in case the cipher is
  2101. changed some time in the future. It should also be remembered
  2102. that the EVP_CIPHER_CTX contains the password and so when one has
  2103. finished encryption with a particular EVP_CIPHER_CTX, it is good
  2104. practice to zero the structure
  2105. (ie. memset(ctx,0,sizeof(EVP_CIPHER_CTX)).
  2106. void EVP_DecryptInit(
  2107. EVP_CIPHER_CTX *ctx,
  2108. EVP_CIPHER *type,
  2109. unsigned char *key,
  2110. unsigned char *iv);
  2111. This function is basically the same as EVP_EncryptInit() accept that
  2112. is prepares the EVP_CIPHER_CTX for decryption.
  2113. void EVP_DecryptUpdate(
  2114. EVP_CIPHER_CTX *ctx,
  2115. unsigned char *out,
  2116. int *outl,
  2117. unsigned char *in,
  2118. int inl);
  2119. This function is basically the same as EVP_EncryptUpdate()
  2120. except that it performs decryption. There is one
  2121. fundamental difference though. 'out' can not be the same as
  2122. 'in' for any ciphers with a block size greater than 1 if more
  2123. than one call to EVP_DecryptUpdate() will be made. This
  2124. is because this routine can hold a 'partial' block between
  2125. calls. When a partial block is decrypted (due to more bytes
  2126. being passed via this function, they will be written to 'out'
  2127. overwriting the input bytes in 'in' that have not been read
  2128. yet. From this it should also be noted that 'out' should
  2129. be at least one 'block size' larger than 'inl'. This problem
  2130. only occurs on the second and subsequent call to
  2131. EVP_DecryptUpdate() when using a block cipher.
  2132. int EVP_DecryptFinal(
  2133. EVP_CIPHER_CTX *ctx,
  2134. unsigned char *out,
  2135. int *outl);
  2136. This function is different to EVP_EncryptFinal in that it 'removes'
  2137. any padding bytes appended when the data was encrypted. Due to the
  2138. way in which 1 to 8 bytes may have been appended when encryption
  2139. using a block cipher, 'out' can end up with 0 to 7 bytes being put
  2140. into it. When decoding the padding bytes, it is possible to detect
  2141. an incorrect decryption. If the decryption appears to be wrong, 0
  2142. is returned. If everything seems ok, 1 is returned. For ciphers
  2143. with a block size of 1 (RC4), this function would normally not
  2144. return any bytes and would always return 1. Just because this
  2145. function returns 1 does not mean the decryption was correct. It
  2146. would normally be wrong due to either the wrong key/iv or
  2147. corruption of the cipher data fed to EVP_DecryptUpdate().
  2148. As for EVP_EncryptFinal, it is a good idea to zero the
  2149. EVP_CIPHER_CTX after use since the structure contains the key used
  2150. to decrypt the data.
  2151. The following Cipher routines are convenience routines that call either
  2152. EVP_EncryptXxx or EVP_DecryptXxx depending on weather the EVP_CIPHER_CTX
  2153. was setup to encrypt or decrypt.
  2154. void EVP_CipherInit(
  2155. EVP_CIPHER_CTX *ctx,
  2156. EVP_CIPHER *type,
  2157. unsigned char *key,
  2158. unsigned char *iv,
  2159. int enc);
  2160. This function take arguments that are the same as EVP_EncryptInit()
  2161. and EVP_DecryptInit() except for the extra 'enc' flag. If 1, the
  2162. EVP_CIPHER_CTX is setup for encryption, if 0, decryption.
  2163. void EVP_CipherUpdate(
  2164. EVP_CIPHER_CTX *ctx,
  2165. unsigned char *out,
  2166. int *outl,
  2167. unsigned char *in,
  2168. int inl);
  2169. Again this function calls either EVP_EncryptUpdate() or
  2170. EVP_DecryptUpdate() depending on state in the 'ctx' structure.
  2171. As noted for EVP_DecryptUpdate(), when this routine is used
  2172. for decryption with block ciphers, 'out' should not be the
  2173. same as 'in'.
  2174. int EVP_CipherFinal(
  2175. EVP_CIPHER_CTX *ctx,
  2176. unsigned char *outm,
  2177. int *outl);
  2178. This routine call EVP_EncryptFinal() or EVP_DecryptFinal()
  2179. depending on the state information in 'ctx'. 1 is always returned
  2180. if the mode is encryption, otherwise the return value is the return
  2181. value of EVP_DecryptFinal().
  2182. ==== cipher.m ========================================================
  2183. Date: Tue, 15 Oct 1996 08:16:14 +1000 (EST)
  2184. From: Eric Young <eay@mincom.com>
  2185. X-Sender: eay@orb
  2186. To: Roland Haring <rharing@tandem.cl>
  2187. Cc: ssl-users@mincom.com
  2188. Subject: Re: Symmetric encryption with ssleay
  2189. In-Reply-To: <m0vBpyq-00001aC@tandemnet.tandem.cl>
  2190. Message-Id: <Pine.SOL.3.91.961015075623.11394A-100000@orb>
  2191. Mime-Version: 1.0
  2192. Content-Type: TEXT/PLAIN; charset=US-ASCII
  2193. Sender: ssl-lists-owner@mincom.com
  2194. Precedence: bulk
  2195. Status: RO
  2196. X-Status:
  2197. On Fri, 11 Oct 1996, Roland Haring wrote:
  2198. > THE_POINT:
  2199. > Would somebody be so kind to give me the minimum basic
  2200. > calls I need to do to libcrypto.a to get some text encrypted
  2201. > and decrypted again? ...hopefully with code included to do
  2202. > base64 encryption and decryption ... e.g. that sign-it.c code
  2203. > posted some while ago was a big help :-) (please, do not point
  2204. > me to apps/enc.c where I suspect my Heissenbug to be hidden :-)
  2205. Ok, the base64 encoding stuff in 'enc.c' does the wrong thing sometimes
  2206. when the data is less than a line long (this is for decoding). I'll dig
  2207. up the exact fix today and post it. I am taking longer on 0.6.5 than I
  2208. intended so I'll just post this patch.
  2209. The documentation to read is in
  2210. doc/cipher.doc,
  2211. doc/encode.doc (very sparse :-).
  2212. and perhaps
  2213. doc/digest.doc,
  2214. The basic calls to encrypt with say triple DES are
  2215. Given
  2216. char key[EVP_MAX_KEY_LENGTH];
  2217. char iv[EVP_MAX_IV_LENGTH];
  2218. EVP_CIPHER_CTX ctx;
  2219. unsigned char out[512+8];
  2220. int outl;
  2221. /* optional generation of key/iv data from text password using md5
  2222. * via an upward compatable verson of PKCS#5. */
  2223. EVP_BytesToKey(EVP_des_ede3_cbc,EVP_md5,NULL,passwd,strlen(passwd),
  2224. key,iv);
  2225. /* Initalise the EVP_CIPHER_CTX */
  2226. EVP_EncryptInit(ctx,EVP_des_ede3_cbc,key,iv);
  2227. while (....)
  2228. {
  2229. /* This is processing 512 bytes at a time, the bytes are being
  2230. * copied into 'out', outl bytes are output. 'out' should not be the
  2231. * same as 'in' for reasons mentioned in the documentation. */
  2232. EVP_EncryptUpdate(ctx,out,&outl,in,512);
  2233. }
  2234. /* Output the last 'block'. If the cipher is a block cipher, the last
  2235. * block is encoded in such a way so that a wrong decryption will normally be
  2236. * detected - again, one of the PKCS standards. */
  2237. EVP_EncryptFinal(ctx,out,&outl);
  2238. To decrypt, use the EVP_DecryptXXXXX functions except that EVP_DecryptFinal()
  2239. will return 0 if the decryption fails (only detectable on block ciphers).
  2240. You can also use
  2241. EVP_CipherInit()
  2242. EVP_CipherUpdate()
  2243. EVP_CipherFinal()
  2244. which does either encryption or decryption depending on an extra
  2245. parameter to EVP_CipherInit().
  2246. To do the base64 encoding,
  2247. EVP_EncodeInit()
  2248. EVP_EncodeUpdate()
  2249. EVP_EncodeFinal()
  2250. EVP_DecodeInit()
  2251. EVP_DecodeUpdate()
  2252. EVP_DecodeFinal()
  2253. where the encoding is quite simple, but the decoding can be a bit more
  2254. fun (due to dud input).
  2255. EVP_DecodeUpdate() returns -1 for an error on an input line, 0 if the
  2256. 'last line' was just processed, and 1 if more lines should be submitted.
  2257. EVP_DecodeFinal() returns -1 for an error or 1 if things are ok.
  2258. So the loop becomes
  2259. EVP_DecodeInit(....)
  2260. for (;;)
  2261. {
  2262. i=EVP_DecodeUpdate(....);
  2263. if (i < 0) goto err;
  2264. /* process the data */
  2265. if (i == 0) break;
  2266. }
  2267. EVP_DecodeFinal(....);
  2268. /* process the data */
  2269. The problem in 'enc.c' is that I was stuff the processing up after the
  2270. EVP_DecodeFinal(...) when the for(..) loop was not being run (one line of
  2271. base64 data) and this was because 'enc.c' tries to scan over a file until
  2272. it hits the first valid base64 encoded line.
  2273. hope this helps a bit.
  2274. eric
  2275. --
  2276. Eric Young | BOOL is tri-state according to Bill Gates.
  2277. AARNet: eay@mincom.oz.au | RTFM Win32 GetMessage().
  2278. ==== conf.doc ========================================================
  2279. The CONF library.
  2280. The CONF library is a simple set of routines that can be used to configure
  2281. programs. It is a superset of the genenv() function with some extra
  2282. structure.
  2283. The library consists of 5 functions.
  2284. LHASH *CONF_load(LHASH *config,char *file);
  2285. This function is called to load in a configuration file. Multiple
  2286. configuration files can be loaded, with each subsequent 'load' overwriting
  2287. any already defined 'variables'. If there is an error, NULL is returned.
  2288. If config is NULL, a new LHASH structure is created and returned, otherwise
  2289. the new data in the 'file' is loaded into the 'config' structure.
  2290. void CONF_free(LHASH *config);
  2291. This function free()s the data in config.
  2292. char *CONF_get_string(LHASH *config,char *section,char *name);
  2293. This function returns the string found in 'config' that corresponds to the
  2294. 'section' and 'name' specified. Classes and the naming system used will be
  2295. discussed later in this document. If the variable is not defined, an NULL
  2296. is returned.
  2297. long CONF_get_long(LHASH *config,char *section, char *name);
  2298. This function is the same as CONF_get_string() except that it converts the
  2299. string to an long and returns it. If variable is not a number or the
  2300. variable does not exist, 0 is returned. This is a little problematic but I
  2301. don't know of a simple way around it.
  2302. STACK *CONF_get_section(LHASH *config, char *section);
  2303. This function returns a 'stack' of CONF_VALUE items that are all the
  2304. items defined in a particular section. DO NOT free() any of the
  2305. variable returned. They will disappear when CONF_free() is called.
  2306. The 'lookup' model.
  2307. The configuration file is divided into 'sections'. Each section is started by
  2308. a line of the form '[ section ]'. All subsequent variable definitions are
  2309. of this section. A variable definition is a simple alpha-numeric name
  2310. followed by an '=' and then the data. A section or variable name can be
  2311. described by a regular expression of the following form '[A-Za-z0-9_]+'.
  2312. The value of the variable is the text after the '=' until the end of the
  2313. line, stripped of leading and trailing white space.
  2314. At this point I should mention that a '#' is a comment character, \ is the
  2315. escape character, and all three types of quote can be used to stop any
  2316. special interpretation of the data.
  2317. Now when the data is being loaded, variable expansion can occur. This is
  2318. done by expanding any $NAME sequences into the value represented by the
  2319. variable NAME. If the variable is not in the current section, the different
  2320. section can be specified by using the $SECTION::NAME form. The ${NAME} form
  2321. also works and is very useful for expanding variables inside strings.
  2322. When a variable is looked up, there are 2 special section. 'default', which
  2323. is the initial section, and 'ENV' which is the processes environment
  2324. variables (accessed via getenv()). When a variable is looked up, it is
  2325. first 'matched' with it's section (if one was specified), if this fails, the
  2326. 'default' section is matched.
  2327. If the 'lhash' variable passed was NULL, the environment is searched.
  2328. Now why do we bother with sections? So we can have multiple programs using
  2329. the same configuration file, or multiple instances of the same program
  2330. using different variables. It also provides a nice mechanism to override
  2331. the processes environment variables (eg ENV::HOME=/tmp). If there is a
  2332. program specific variable missing, we can have default values.
  2333. Multiple configuration files can be loaded, with each new value clearing
  2334. any predefined values. A system config file can provide 'default' values,
  2335. and application/usr specific files can provide overriding values.
  2336. Examples
  2337. # This is a simple example
  2338. SSLEAY_HOME = /usr/local/ssl
  2339. ENV::PATH = $SSLEAY_HOME/bin:$PATH # override my path
  2340. [X509]
  2341. cert_dir = $SSLEAY_HOME/certs # /usr/local/ssl/certs
  2342. [SSL]
  2343. CIPHER = DES-EDE-MD5:RC4-MD5
  2344. USER_CERT = $HOME/${USER}di'r 5' # /home/eay/eaydir 5
  2345. USER_CERT = $HOME/\${USER}di\'r # /home/eay/${USER}di'r
  2346. USER_CERT = "$HOME/${US"ER}di\'r # $HOME/${USER}di'r
  2347. TEST = 1234\
  2348. 5678\
  2349. 9ab # TEST=123456789ab
  2350. TTT = 1234\n\n # TTT=1234<nl><nl>
  2351. ==== des.doc ========================================================
  2352. The DES library.
  2353. Please note that this library was originally written to operate with
  2354. eBones, a version of Kerberos that had had encryption removed when it left
  2355. the USA and then put back in. As such there are some routines that I will
  2356. advise not using but they are still in the library for historical reasons.
  2357. For all calls that have an 'input' and 'output' variables, they can be the
  2358. same.
  2359. This library requires the inclusion of 'des.h'.
  2360. All of the encryption functions take what is called a des_key_schedule as an
  2361. argument. A des_key_schedule is an expanded form of the des key.
  2362. A des_key is 8 bytes of odd parity, the type used to hold the key is a
  2363. des_cblock. A des_cblock is an array of 8 bytes, often in this library
  2364. description I will refer to input bytes when the function specifies
  2365. des_cblock's as input or output, this just means that the variable should
  2366. be a multiple of 8 bytes.
  2367. The define DES_ENCRYPT is passed to specify encryption, DES_DECRYPT to
  2368. specify decryption. The functions and global variable are as follows:
  2369. int des_check_key;
  2370. DES keys are supposed to be odd parity. If this variable is set to
  2371. a non-zero value, des_set_key() will check that the key has odd
  2372. parity and is not one of the known weak DES keys. By default this
  2373. variable is turned off;
  2374. void des_set_odd_parity(
  2375. des_cblock *key );
  2376. This function takes a DES key (8 bytes) and sets the parity to odd.
  2377. int des_is_weak_key(
  2378. des_cblock *key );
  2379. This function returns a non-zero value if the DES key passed is a
  2380. weak, DES key. If it is a weak key, don't use it, try a different
  2381. one. If you are using 'random' keys, the chances of hitting a weak
  2382. key are 1/2^52 so it is probably not worth checking for them.
  2383. int des_set_key(
  2384. des_cblock *key,
  2385. des_key_schedule schedule);
  2386. Des_set_key converts an 8 byte DES key into a des_key_schedule.
  2387. A des_key_schedule is an expanded form of the key which is used to
  2388. perform actual encryption. It can be regenerated from the DES key
  2389. so it only needs to be kept when encryption or decryption is about
  2390. to occur. Don't save or pass around des_key_schedule's since they
  2391. are CPU architecture dependent, DES keys are not. If des_check_key
  2392. is non zero, zero is returned if the key has the wrong parity or
  2393. the key is a weak key, else 1 is returned.
  2394. int des_key_sched(
  2395. des_cblock *key,
  2396. des_key_schedule schedule);
  2397. An alternative name for des_set_key().
  2398. int des_rw_mode; /* defaults to DES_PCBC_MODE */
  2399. This flag holds either DES_CBC_MODE or DES_PCBC_MODE (default).
  2400. This specifies the function to use in the enc_read() and enc_write()
  2401. functions.
  2402. void des_encrypt(
  2403. unsigned long *data,
  2404. des_key_schedule ks,
  2405. int enc);
  2406. This is the DES encryption function that gets called by just about
  2407. every other DES routine in the library. You should not use this
  2408. function except to implement 'modes' of DES. I say this because the
  2409. functions that call this routine do the conversion from 'char *' to
  2410. long, and this needs to be done to make sure 'non-aligned' memory
  2411. access do not occur. The characters are loaded 'little endian',
  2412. have a look at my source code for more details on how I use this
  2413. function.
  2414. Data is a pointer to 2 unsigned long's and ks is the
  2415. des_key_schedule to use. enc, is non zero specifies encryption,
  2416. zero if decryption.
  2417. void des_encrypt2(
  2418. unsigned long *data,
  2419. des_key_schedule ks,
  2420. int enc);
  2421. This functions is the same as des_encrypt() except that the DES
  2422. initial permutation (IP) and final permutation (FP) have been left
  2423. out. As for des_encrypt(), you should not use this function.
  2424. It is used by the routines in my library that implement triple DES.
  2425. IP() des_encrypt2() des_encrypt2() des_encrypt2() FP() is the same
  2426. as des_encrypt() des_encrypt() des_encrypt() except faster :-).
  2427. void des_ecb_encrypt(
  2428. des_cblock *input,
  2429. des_cblock *output,
  2430. des_key_schedule ks,
  2431. int enc);
  2432. This is the basic Electronic Code Book form of DES, the most basic
  2433. form. Input is encrypted into output using the key represented by
  2434. ks. If enc is non zero (DES_ENCRYPT), encryption occurs, otherwise
  2435. decryption occurs. Input is 8 bytes long and output is 8 bytes.
  2436. (the des_cblock structure is 8 chars).
  2437. void des_ecb3_encrypt(
  2438. des_cblock *input,
  2439. des_cblock *output,
  2440. des_key_schedule ks1,
  2441. des_key_schedule ks2,
  2442. des_key_schedule ks3,
  2443. int enc);
  2444. This is the 3 key EDE mode of ECB DES. What this means is that
  2445. the 8 bytes of input is encrypted with ks1, decrypted with ks2 and
  2446. then encrypted again with ks3, before being put into output;
  2447. C=E(ks3,D(ks2,E(ks1,M))). There is a macro, des_ecb2_encrypt()
  2448. that only takes 2 des_key_schedules that implements,
  2449. C=E(ks1,D(ks2,E(ks1,M))) in that the final encrypt is done with ks1.
  2450. void des_cbc_encrypt(
  2451. des_cblock *input,
  2452. des_cblock *output,
  2453. long length,
  2454. des_key_schedule ks,
  2455. des_cblock *ivec,
  2456. int enc);
  2457. This routine implements DES in Cipher Block Chaining mode.
  2458. Input, which should be a multiple of 8 bytes is encrypted
  2459. (or decrypted) to output which will also be a multiple of 8 bytes.
  2460. The number of bytes is in length (and from what I've said above,
  2461. should be a multiple of 8). If length is not a multiple of 8, I'm
  2462. not being held responsible :-). ivec is the initialisation vector.
  2463. This function does not modify this variable. To correctly implement
  2464. cbc mode, you need to do one of 2 things; copy the last 8 bytes of
  2465. cipher text for use as the next ivec in your application,
  2466. or use des_ncbc_encrypt().
  2467. Only this routine has this problem with updating the ivec, all
  2468. other routines that are implementing cbc mode update ivec.
  2469. void des_ncbc_encrypt(
  2470. des_cblock *input,
  2471. des_cblock *output,
  2472. long length,
  2473. des_key_schedule sk,
  2474. des_cblock *ivec,
  2475. int enc);
  2476. For historical reasons, des_cbc_encrypt() did not update the
  2477. ivec with the value requires so that subsequent calls to
  2478. des_cbc_encrypt() would 'chain'. This was needed so that the same
  2479. 'length' values would not need to be used when decrypting.
  2480. des_ncbc_encrypt() does the right thing. It is the same as
  2481. des_cbc_encrypt accept that ivec is updates with the correct value
  2482. to pass in subsequent calls to des_ncbc_encrypt(). I advise using
  2483. des_ncbc_encrypt() instead of des_cbc_encrypt();
  2484. void des_xcbc_encrypt(
  2485. des_cblock *input,
  2486. des_cblock *output,
  2487. long length,
  2488. des_key_schedule sk,
  2489. des_cblock *ivec,
  2490. des_cblock *inw,
  2491. des_cblock *outw,
  2492. int enc);
  2493. This is RSA's DESX mode of DES. It uses inw and outw to
  2494. 'whiten' the encryption. inw and outw are secret (unlike the iv)
  2495. and are as such, part of the key. So the key is sort of 24 bytes.
  2496. This is much better than cbc des.
  2497. void des_3cbc_encrypt(
  2498. des_cblock *input,
  2499. des_cblock *output,
  2500. long length,
  2501. des_key_schedule sk1,
  2502. des_key_schedule sk2,
  2503. des_cblock *ivec1,
  2504. des_cblock *ivec2,
  2505. int enc);
  2506. This function is flawed, do not use it. I have left it in the
  2507. library because it is used in my des(1) program and will function
  2508. correctly when used by des(1). If I removed the function, people
  2509. could end up unable to decrypt files.
  2510. This routine implements outer triple cbc encryption using 2 ks and
  2511. 2 ivec's. Use des_ede2_cbc_encrypt() instead.
  2512. void des_ede3_cbc_encrypt(
  2513. des_cblock *input,
  2514. des_cblock *output,
  2515. long length,
  2516. des_key_schedule ks1,
  2517. des_key_schedule ks2,
  2518. des_key_schedule ks3,
  2519. des_cblock *ivec,
  2520. int enc);
  2521. This function implements outer triple CBC DES encryption with 3
  2522. keys. What this means is that each 'DES' operation
  2523. inside the cbc mode is really an C=E(ks3,D(ks2,E(ks1,M))).
  2524. Again, this is cbc mode so an ivec is requires.
  2525. This mode is used by SSL.
  2526. There is also a des_ede2_cbc_encrypt() that only uses 2
  2527. des_key_schedule's, the first being reused for the final
  2528. encryption. C=E(ks1,D(ks2,E(ks1,M))). This form of triple DES
  2529. is used by the RSAref library.
  2530. void des_pcbc_encrypt(
  2531. des_cblock *input,
  2532. des_cblock *output,
  2533. long length,
  2534. des_key_schedule ks,
  2535. des_cblock *ivec,
  2536. int enc);
  2537. This is Propagating Cipher Block Chaining mode of DES. It is used
  2538. by Kerberos v4. It's parameters are the same as des_ncbc_encrypt().
  2539. void des_cfb_encrypt(
  2540. unsigned char *in,
  2541. unsigned char *out,
  2542. int numbits,
  2543. long length,
  2544. des_key_schedule ks,
  2545. des_cblock *ivec,
  2546. int enc);
  2547. Cipher Feedback Back mode of DES. This implementation 'feeds back'
  2548. in numbit blocks. The input (and output) is in multiples of numbits
  2549. bits. numbits should to be a multiple of 8 bits. Length is the
  2550. number of bytes input. If numbits is not a multiple of 8 bits,
  2551. the extra bits in the bytes will be considered padding. So if
  2552. numbits is 12, for each 2 input bytes, the 4 high bits of the
  2553. second byte will be ignored. So to encode 72 bits when using
  2554. a numbits of 12 take 12 bytes. To encode 72 bits when using
  2555. numbits of 9 will take 16 bytes. To encode 80 bits when using
  2556. numbits of 16 will take 10 bytes. etc, etc. This padding will
  2557. apply to both input and output.
  2558. void des_cfb64_encrypt(
  2559. unsigned char *in,
  2560. unsigned char *out,
  2561. long length,
  2562. des_key_schedule ks,
  2563. des_cblock *ivec,
  2564. int *num,
  2565. int enc);
  2566. This is one of the more useful functions in this DES library, it
  2567. implements CFB mode of DES with 64bit feedback. Why is this
  2568. useful you ask? Because this routine will allow you to encrypt an
  2569. arbitrary number of bytes, no 8 byte padding. Each call to this
  2570. routine will encrypt the input bytes to output and then update ivec
  2571. and num. num contains 'how far' we are though ivec. If this does
  2572. not make much sense, read more about cfb mode of DES :-).
  2573. void des_ede3_cfb64_encrypt(
  2574. unsigned char *in,
  2575. unsigned char *out,
  2576. long length,
  2577. des_key_schedule ks1,
  2578. des_key_schedule ks2,
  2579. des_key_schedule ks3,
  2580. des_cblock *ivec,
  2581. int *num,
  2582. int enc);
  2583. Same as des_cfb64_encrypt() accept that the DES operation is
  2584. triple DES. As usual, there is a macro for
  2585. des_ede2_cfb64_encrypt() which reuses ks1.
  2586. void des_ofb_encrypt(
  2587. unsigned char *in,
  2588. unsigned char *out,
  2589. int numbits,
  2590. long length,
  2591. des_key_schedule ks,
  2592. des_cblock *ivec);
  2593. This is a implementation of Output Feed Back mode of DES. It is
  2594. the same as des_cfb_encrypt() in that numbits is the size of the
  2595. units dealt with during input and output (in bits).
  2596. void des_ofb64_encrypt(
  2597. unsigned char *in,
  2598. unsigned char *out,
  2599. long length,
  2600. des_key_schedule ks,
  2601. des_cblock *ivec,
  2602. int *num);
  2603. The same as des_cfb64_encrypt() except that it is Output Feed Back
  2604. mode.
  2605. void des_ede3_ofb64_encrypt(
  2606. unsigned char *in,
  2607. unsigned char *out,
  2608. long length,
  2609. des_key_schedule ks1,
  2610. des_key_schedule ks2,
  2611. des_key_schedule ks3,
  2612. des_cblock *ivec,
  2613. int *num);
  2614. Same as des_ofb64_encrypt() accept that the DES operation is
  2615. triple DES. As usual, there is a macro for
  2616. des_ede2_ofb64_encrypt() which reuses ks1.
  2617. int des_read_pw_string(
  2618. char *buf,
  2619. int length,
  2620. char *prompt,
  2621. int verify);
  2622. This routine is used to get a password from the terminal with echo
  2623. turned off. Buf is where the string will end up and length is the
  2624. size of buf. Prompt is a string presented to the 'user' and if
  2625. verify is set, the key is asked for twice and unless the 2 copies
  2626. match, an error is returned. A return code of -1 indicates a
  2627. system error, 1 failure due to use interaction, and 0 is success.
  2628. unsigned long des_cbc_cksum(
  2629. des_cblock *input,
  2630. des_cblock *output,
  2631. long length,
  2632. des_key_schedule ks,
  2633. des_cblock *ivec);
  2634. This function produces an 8 byte checksum from input that it puts in
  2635. output and returns the last 4 bytes as a long. The checksum is
  2636. generated via cbc mode of DES in which only the last 8 byes are
  2637. kept. I would recommend not using this function but instead using
  2638. the EVP_Digest routines, or at least using MD5 or SHA. This
  2639. function is used by Kerberos v4 so that is why it stays in the
  2640. library.
  2641. char *des_fcrypt(
  2642. const char *buf,
  2643. const char *salt
  2644. char *ret);
  2645. This is my fast version of the unix crypt(3) function. This version
  2646. takes only a small amount of space relative to other fast
  2647. crypt() implementations. This is different to the normal crypt
  2648. in that the third parameter is the buffer that the return value
  2649. is written into. It needs to be at least 14 bytes long. This
  2650. function is thread safe, unlike the normal crypt.
  2651. char *crypt(
  2652. const char *buf,
  2653. const char *salt);
  2654. This function calls des_fcrypt() with a static array passed as the
  2655. third parameter. This emulates the normal non-thread safe semantics
  2656. of crypt(3).
  2657. void des_string_to_key(
  2658. char *str,
  2659. des_cblock *key);
  2660. This function takes str and converts it into a DES key. I would
  2661. recommend using MD5 instead and use the first 8 bytes of output.
  2662. When I wrote the first version of these routines back in 1990, MD5
  2663. did not exist but I feel these routines are still sound. This
  2664. routines is compatible with the one in MIT's libdes.
  2665. void des_string_to_2keys(
  2666. char *str,
  2667. des_cblock *key1,
  2668. des_cblock *key2);
  2669. This function takes str and converts it into 2 DES keys.
  2670. I would recommend using MD5 and using the 16 bytes as the 2 keys.
  2671. I have nothing against these 2 'string_to_key' routines, it's just
  2672. that if you say that your encryption key is generated by using the
  2673. 16 bytes of an MD5 hash, every-one knows how you generated your
  2674. keys.
  2675. int des_read_password(
  2676. des_cblock *key,
  2677. char *prompt,
  2678. int verify);
  2679. This routine combines des_read_pw_string() with des_string_to_key().
  2680. int des_read_2passwords(
  2681. des_cblock *key1,
  2682. des_cblock *key2,
  2683. char *prompt,
  2684. int verify);
  2685. This routine combines des_read_pw_string() with des_string_to_2key().
  2686. void des_random_seed(
  2687. des_cblock key);
  2688. This routine sets a starting point for des_random_key().
  2689. void des_random_key(
  2690. des_cblock ret);
  2691. This function return a random key. Make sure to 'seed' the random
  2692. number generator (with des_random_seed()) before using this function.
  2693. I personally now use a MD5 based random number system.
  2694. int des_enc_read(
  2695. int fd,
  2696. char *buf,
  2697. int len,
  2698. des_key_schedule ks,
  2699. des_cblock *iv);
  2700. This function will write to a file descriptor the encrypted data
  2701. from buf. This data will be preceded by a 4 byte 'byte count' and
  2702. will be padded out to 8 bytes. The encryption is either CBC of
  2703. PCBC depending on the value of des_rw_mode. If it is DES_PCBC_MODE,
  2704. pcbc is used, if DES_CBC_MODE, cbc is used. The default is to use
  2705. DES_PCBC_MODE.
  2706. int des_enc_write(
  2707. int fd,
  2708. char *buf,
  2709. int len,
  2710. des_key_schedule ks,
  2711. des_cblock *iv);
  2712. This routines read stuff written by des_enc_read() and decrypts it.
  2713. I have used these routines quite a lot but I don't believe they are
  2714. suitable for non-blocking io. If you are after a full
  2715. authentication/encryption over networks, have a look at SSL instead.
  2716. unsigned long des_quad_cksum(
  2717. des_cblock *input,
  2718. des_cblock *output,
  2719. long length,
  2720. int out_count,
  2721. des_cblock *seed);
  2722. This is a function from Kerberos v4 that is not anything to do with
  2723. DES but was needed. It is a cksum that is quicker to generate than
  2724. des_cbc_cksum(); I personally would use MD5 routines now.
  2725. =====
  2726. Modes of DES
  2727. Quite a bit of the following information has been taken from
  2728. AS 2805.5.2
  2729. Australian Standard
  2730. Electronic funds transfer - Requirements for interfaces,
  2731. Part 5.2: Modes of operation for an n-bit block cipher algorithm
  2732. Appendix A
  2733. There are several different modes in which DES can be used, they are
  2734. as follows.
  2735. Electronic Codebook Mode (ECB) (des_ecb_encrypt())
  2736. - 64 bits are enciphered at a time.
  2737. - The order of the blocks can be rearranged without detection.
  2738. - The same plaintext block always produces the same ciphertext block
  2739. (for the same key) making it vulnerable to a 'dictionary attack'.
  2740. - An error will only affect one ciphertext block.
  2741. Cipher Block Chaining Mode (CBC) (des_cbc_encrypt())
  2742. - a multiple of 64 bits are enciphered at a time.
  2743. - The CBC mode produces the same ciphertext whenever the same
  2744. plaintext is encrypted using the same key and starting variable.
  2745. - The chaining operation makes the ciphertext blocks dependent on the
  2746. current and all preceding plaintext blocks and therefore blocks can not
  2747. be rearranged.
  2748. - The use of different starting variables prevents the same plaintext
  2749. enciphering to the same ciphertext.
  2750. - An error will affect the current and the following ciphertext blocks.
  2751. Cipher Feedback Mode (CFB) (des_cfb_encrypt())
  2752. - a number of bits (j) <= 64 are enciphered at a time.
  2753. - The CFB mode produces the same ciphertext whenever the same
  2754. plaintext is encrypted using the same key and starting variable.
  2755. - The chaining operation makes the ciphertext variables dependent on the
  2756. current and all preceding variables and therefore j-bit variables are
  2757. chained together and can not be rearranged.
  2758. - The use of different starting variables prevents the same plaintext
  2759. enciphering to the same ciphertext.
  2760. - The strength of the CFB mode depends on the size of k (maximal if
  2761. j == k). In my implementation this is always the case.
  2762. - Selection of a small value for j will require more cycles through
  2763. the encipherment algorithm per unit of plaintext and thus cause
  2764. greater processing overheads.
  2765. - Only multiples of j bits can be enciphered.
  2766. - An error will affect the current and the following ciphertext variables.
  2767. Output Feedback Mode (OFB) (des_ofb_encrypt())
  2768. - a number of bits (j) <= 64 are enciphered at a time.
  2769. - The OFB mode produces the same ciphertext whenever the same
  2770. plaintext enciphered using the same key and starting variable. More
  2771. over, in the OFB mode the same key stream is produced when the same
  2772. key and start variable are used. Consequently, for security reasons
  2773. a specific start variable should be used only once for a given key.
  2774. - The absence of chaining makes the OFB more vulnerable to specific attacks.
  2775. - The use of different start variables values prevents the same
  2776. plaintext enciphering to the same ciphertext, by producing different
  2777. key streams.
  2778. - Selection of a small value for j will require more cycles through
  2779. the encipherment algorithm per unit of plaintext and thus cause
  2780. greater processing overheads.
  2781. - Only multiples of j bits can be enciphered.
  2782. - OFB mode of operation does not extend ciphertext errors in the
  2783. resultant plaintext output. Every bit error in the ciphertext causes
  2784. only one bit to be in error in the deciphered plaintext.
  2785. - OFB mode is not self-synchronising. If the two operation of
  2786. encipherment and decipherment get out of synchronism, the system needs
  2787. to be re-initialised.
  2788. - Each re-initialisation should use a value of the start variable
  2789. different from the start variable values used before with the same
  2790. key. The reason for this is that an identical bit stream would be
  2791. produced each time from the same parameters. This would be
  2792. susceptible to a ' known plaintext' attack.
  2793. Triple ECB Mode (des_ecb3_encrypt())
  2794. - Encrypt with key1, decrypt with key2 and encrypt with key3 again.
  2795. - As for ECB encryption but increases the key length to 168 bits.
  2796. There are theoretic attacks that can be used that make the effective
  2797. key length 112 bits, but this attack also requires 2^56 blocks of
  2798. memory, not very likely, even for the NSA.
  2799. - If both keys are the same it is equivalent to encrypting once with
  2800. just one key.
  2801. - If the first and last key are the same, the key length is 112 bits.
  2802. There are attacks that could reduce the key space to 55 bit's but it
  2803. requires 2^56 blocks of memory.
  2804. - If all 3 keys are the same, this is effectively the same as normal
  2805. ecb mode.
  2806. Triple CBC Mode (des_ede3_cbc_encrypt())
  2807. - Encrypt with key1, decrypt with key2 and then encrypt with key3.
  2808. - As for CBC encryption but increases the key length to 168 bits with
  2809. the same restrictions as for triple ecb mode.
  2810. ==== digest.doc ========================================================
  2811. The Message Digest subroutines.
  2812. These routines require "evp.h" to be included.
  2813. These functions are a higher level interface to the various message digest
  2814. routines found in this library. As such, they allow the same code to be
  2815. used to digest via different algorithms with only a change in an initial
  2816. parameter. They are basically just a front-end to the MD2, MD5, SHA
  2817. and SHA1
  2818. routines.
  2819. These routines all take a pointer to the following structure to specify
  2820. which message digest algorithm to use.
  2821. typedef struct evp_md_st
  2822. {
  2823. int type;
  2824. int pkey_type;
  2825. int md_size;
  2826. void (*init)();
  2827. void (*update)();
  2828. void (*final)();
  2829. int required_pkey_type; /*EVP_PKEY_xxx */
  2830. int (*sign)();
  2831. int (*verify)();
  2832. } EVP_MD;
  2833. If additional message digest algorithms are to be supported, a structure of
  2834. this type needs to be declared and populated and then the Digest routines
  2835. can be used with that algorithm. The type field is the object NID of the
  2836. digest type (read the section on Objects for an explanation). The pkey_type
  2837. is the Object type to use when the a message digest is generated by there
  2838. routines and then is to be signed with the pkey algorithm. Md_size is
  2839. the size of the message digest returned. Init, update
  2840. and final are the relevant functions to perform the message digest function
  2841. by parts. One reason for specifying the message digest to use via this
  2842. mechanism is that if you only use md5, only the md5 routines will
  2843. be included in you linked program. If you passed an integer
  2844. that specified which message digest to use, the routine that mapped that
  2845. integer to a set of message digest functions would cause all the message
  2846. digests functions to be link into the code. This setup also allows new
  2847. message digest functions to be added by the application.
  2848. The six message digests defined in this library are
  2849. EVP_MD *EVP_md2(void); /* RSA sign/verify */
  2850. EVP_MD *EVP_md5(void); /* RSA sign/verify */
  2851. EVP_MD *EVP_sha(void); /* RSA sign/verify */
  2852. EVP_MD *EVP_sha1(void); /* RSA sign/verify */
  2853. EVP_MD *EVP_dss(void); /* DSA sign/verify */
  2854. EVP_MD *EVP_dss1(void); /* DSA sign/verify */
  2855. All the message digest routines take a EVP_MD_CTX pointer as an argument.
  2856. The state of the message digest is kept in this structure.
  2857. typedef struct pem_md_ctx_st
  2858. {
  2859. EVP_MD *digest;
  2860. union {
  2861. unsigned char base[4]; /* this is used in my library as a
  2862. * 'pointer' to all union elements
  2863. * structures. */
  2864. MD2_CTX md2;
  2865. MD5_CTX md5;
  2866. SHA_CTX sha;
  2867. } md;
  2868. } EVP_MD_CTX;
  2869. The Digest functions are as follows.
  2870. void EVP_DigestInit(
  2871. EVP_MD_CTX *ctx,
  2872. EVP_MD *type);
  2873. This function is used to initialise the EVP_MD_CTX. The message
  2874. digest that will associated with 'ctx' is specified by 'type'.
  2875. void EVP_DigestUpdate(
  2876. EVP_MD_CTX *ctx,
  2877. unsigned char *data,
  2878. unsigned int cnt);
  2879. This function is used to pass more data to the message digest
  2880. function. 'cnt' bytes are digested from 'data'.
  2881. void EVP_DigestFinal(
  2882. EVP_MD_CTX *ctx,
  2883. unsigned char *md,
  2884. unsigned int *len);
  2885. This function finishes the digestion and puts the message digest
  2886. into 'md'. The length of the message digest is put into len;
  2887. EVP_MAX_MD_SIZE is the size of the largest message digest that
  2888. can be returned from this function. Len can be NULL if the
  2889. size of the digest is not required.
  2890. ==== encode.doc ========================================================
  2891. void EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
  2892. void EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,
  2893. int *outl,unsigned char *in,int inl);
  2894. void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl);
  2895. int EVP_EncodeBlock(unsigned char *t, unsigned char *f, int n);
  2896. void EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
  2897. int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx,unsigned char *out,int *outl,
  2898. unsigned char *in, int inl);
  2899. int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned
  2900. char *out, int *outl);
  2901. int EVP_DecodeBlock(unsigned char *t, unsigned
  2902. char *f, int n);
  2903. ==== envelope.doc ========================================================
  2904. The following routines are use to create 'digital' envelopes.
  2905. By this I mean that they perform various 'higher' level cryptographic
  2906. functions. Have a read of 'cipher.doc' and 'digest.doc' since those
  2907. routines are used by these functions.
  2908. cipher.doc contains documentation about the cipher part of the
  2909. envelope library and digest.doc contatins the description of the
  2910. message digests supported.
  2911. To 'sign' a document involves generating a message digest and then encrypting
  2912. the digest with an private key.
  2913. #define EVP_SignInit(a,b) EVP_DigestInit(a,b)
  2914. #define EVP_SignUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
  2915. Due to the fact this operation is basically just an extended message
  2916. digest, the first 2 functions are macro calls to Digest generating
  2917. functions.
  2918. int EVP_SignFinal(
  2919. EVP_MD_CTX *ctx,
  2920. unsigned char *md,
  2921. unsigned int *s,
  2922. EVP_PKEY *pkey);
  2923. This finalisation function finishes the generation of the message
  2924. digest and then encrypts the digest (with the correct message digest
  2925. object identifier) with the EVP_PKEY private key. 'ctx' is the message digest
  2926. context. 'md' will end up containing the encrypted message digest. This
  2927. array needs to be EVP_PKEY_size(pkey) bytes long. 's' will actually
  2928. contain the exact length. 'pkey' of course is the private key. It is
  2929. one of EVP_PKEY_RSA or EVP_PKEY_DSA type.
  2930. If there is an error, 0 is returned, otherwise 1.
  2931. Verify is used to check an signed message digest.
  2932. #define EVP_VerifyInit(a,b) EVP_DigestInit(a,b)
  2933. #define EVP_VerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
  2934. Since the first step is to generate a message digest, the first 2 functions
  2935. are macros.
  2936. int EVP_VerifyFinal(
  2937. EVP_MD_CTX *ctx,
  2938. unsigned char *md,
  2939. unsigned int s,
  2940. EVP_PKEY *pkey);
  2941. This function finishes the generation of the message digest and then
  2942. compares it with the supplied encrypted message digest. 'md' contains the
  2943. 's' bytes of encrypted message digest. 'pkey' is used to public key decrypt
  2944. the digest. It is then compared with the message digest just generated.
  2945. If they match, 1 is returned else 0.
  2946. int EVP_SealInit(EVP_CIPHER_CTX *ctx, EVP_CIPHER *type, unsigned char **ek,
  2947. int *ekl, unsigned char *iv, EVP_PKEY **pubk, int npubk);
  2948. Must have at least one public key, error is 0. I should also mention that
  2949. the buffers pointed to by 'ek' need to be EVP_PKEY_size(pubk[n]) is size.
  2950. #define EVP_SealUpdate(a,b,c,d,e) EVP_EncryptUpdate(a,b,c,d,e)
  2951. void EVP_SealFinal(EVP_CIPHER_CTX *ctx,unsigned char *out,int *outl);
  2952. int EVP_OpenInit(EVP_CIPHER_CTX *ctx,EVP_CIPHER *type,unsigned char *ek,
  2953. int ekl,unsigned char *iv,EVP_PKEY *priv);
  2954. 0 on failure
  2955. #define EVP_OpenUpdate(a,b,c,d,e) EVP_DecryptUpdate(a,b,c,d,e)
  2956. int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
  2957. Decrypt final return code
  2958. ==== error.doc ========================================================
  2959. The error routines.
  2960. The 'error' system I've implemented is intended to server 2 purpose, to
  2961. record the reason why a command failed and to record where in the libraries
  2962. the failure occurred. It is more or less setup to record a 'trace' of which
  2963. library components were being traversed when the error occurred.
  2964. When an error is recorded, it is done so a as single unsigned long which is
  2965. composed of three parts. The top byte is the 'library' number, the middle
  2966. 12 bytes is the function code, and the bottom 12 bits is the 'reason' code.
  2967. Each 'library', or should a say, 'section' of the SSLeay library has a
  2968. different unique 'library' error number. Each function in the library has
  2969. a number that is unique for that library. Each 'library' also has a number
  2970. for each 'error reason' that is only unique for that 'library'.
  2971. Due to the way these error routines record a 'error trace', there is an
  2972. array per thread that is used to store the error codes.
  2973. The various functions in this library are used to access
  2974. and manipulate this array.
  2975. void ERR_put_error(int lib, int func,int reason);
  2976. This routine records an error in library 'lib', function 'func'
  2977. and reason 'reason'. As errors get 'put' into the buffer, they wrap
  2978. around and overwrite old errors if too many are written. It is assumed
  2979. that the last errors are the most important.
  2980. unsigned long ERR_get_error(void );
  2981. This function returns the last error added to the error buffer.
  2982. In effect it is popping the value off the buffer so repeated calls will
  2983. continue to return values until there are no more errors to return in which
  2984. case 0 is returned.
  2985. unsigned long ERR_peek_error(void );
  2986. This function returns the value of the last error added to the
  2987. error buffer but does not 'pop' it from the buffer.
  2988. void ERR_clear_error(void );
  2989. This function clears the error buffer, discarding all unread
  2990. errors.
  2991. While the above described error system obviously produces lots of different
  2992. error number, a method for 'reporting' these errors in a human readable
  2993. form is required. To achieve this, each library has the option of
  2994. 'registering' error strings.
  2995. typedef struct ERR_string_data_st
  2996. {
  2997. unsigned long error;
  2998. char *string;
  2999. } ERR_STRING_DATA;
  3000. The 'ERR_STRING_DATA' contains an error code and the corresponding text
  3001. string. To add new function error strings for a library, the
  3002. ERR_STRING_DATA needs to be 'registered' with the library.
  3003. void ERR_load_strings(unsigned long lib,ERR_STRING_DATA *err);
  3004. This function 'registers' the array of ERR_STRING_DATA pointed to by
  3005. 'err' as error text strings for the error library 'lib'.
  3006. void ERR_free_strings(void);
  3007. This function free()s all the loaded error strings.
  3008. char *ERR_error_string(unsigned long error,char *buf);
  3009. This function returns a text string that is a human readable
  3010. version of the error represented by 'error'. Buff should be at least 120
  3011. bytes long and if it is NULL, the return value is a pointer to a static
  3012. variable that will contain the error string, otherwise 'buf' is returned.
  3013. If there is not a text string registered for a particular error, a text
  3014. string containing the error number is returned instead.
  3015. void ERR_print_errors(BIO *bp);
  3016. void ERR_print_errors_fp(FILE *fp);
  3017. This function is a convenience routine that prints the error string
  3018. for each error until all errors have been accounted for.
  3019. char *ERR_lib_error_string(unsigned long e);
  3020. char *ERR_func_error_string(unsigned long e);
  3021. char *ERR_reason_error_string(unsigned long e);
  3022. The above three functions return the 3 different components strings for the
  3023. error 'e'. ERR_error_string() uses these functions.
  3024. void ERR_load_ERR_strings(void );
  3025. This function 'registers' the error strings for the 'ERR' module.
  3026. void ERR_load_crypto_strings(void );
  3027. This function 'register' the error strings for just about every
  3028. library in the SSLeay package except for the SSL routines. There is no
  3029. need to ever register any error text strings and you will probably save in
  3030. program size. If on the other hand you do 'register' all errors, it is
  3031. quite easy to determine why a particular routine failed.
  3032. As a final footnote as to why the error system is designed as it is.
  3033. 1) I did not want a single 'global' error code.
  3034. 2) I wanted to know which subroutine a failure occurred in.
  3035. 3) For Windows NT etc, it should be simple to replace the 'key' routines
  3036. with code to pass error codes back to the application.
  3037. 4) I wanted the option of meaningful error text strings.
  3038. Late breaking news - the changes to support threads.
  3039. Each 'thread' has an 'ERR_STATE' state associated with it.
  3040. ERR_STATE *ERR_get_state(void ) will return the 'state' for the calling
  3041. thread/process.
  3042. ERR_remove_state(unsigned long pid); will 'free()' this state. If pid == 0
  3043. the current 'thread/process' will have it's error state removed.
  3044. If you do not remove the error state of a thread, this could be considered a
  3045. form of memory leak, so just after 'reaping' a thread that has died,
  3046. call ERR_remove_state(pid).
  3047. Have a read of thread.doc for more details for what is required for
  3048. multi-threading support. All the other error routines will
  3049. work correctly when using threads.
  3050. ==== idea.doc ========================================================
  3051. The IDEA library.
  3052. IDEA is a block cipher that operates on 64bit (8 byte) quantities. It
  3053. uses a 128bit (16 byte) key. It can be used in all the modes that DES can
  3054. be used. This library implements the ecb, cbc, cfb64 and ofb64 modes.
  3055. For all calls that have an 'input' and 'output' variables, they can be the
  3056. same.
  3057. This library requires the inclusion of 'idea.h'.
  3058. All of the encryption functions take what is called an IDEA_KEY_SCHEDULE as an
  3059. argument. An IDEA_KEY_SCHEDULE is an expanded form of the idea key.
  3060. For all modes of the IDEA algorithm, the IDEA_KEY_SCHEDULE used for
  3061. decryption is different to the one used for encryption.
  3062. The define IDEA_ENCRYPT is passed to specify encryption for the functions
  3063. that require an encryption/decryption flag. IDEA_DECRYPT is passed to
  3064. specify decryption. For some mode there is no encryption/decryption
  3065. flag since this is determined by the IDEA_KEY_SCHEDULE.
  3066. So to encrypt you would do the following
  3067. idea_set_encrypt_key(key,encrypt_ks);
  3068. idea_ecb_encrypt(...,encrypt_ks);
  3069. idea_cbc_encrypt(....,encrypt_ks,...,IDEA_ENCRYPT);
  3070. To Decrypt
  3071. idea_set_encrypt_key(key,encrypt_ks);
  3072. idea_set_decrypt_key(encrypt_ks,decrypt_ks);
  3073. idea_ecb_encrypt(...,decrypt_ks);
  3074. idea_cbc_encrypt(....,decrypt_ks,...,IDEA_DECRYPT);
  3075. Please note that any of the encryption modes specified in my DES library
  3076. could be used with IDEA. I have only implemented ecb, cbc, cfb64 and
  3077. ofb64 for the following reasons.
  3078. - ecb is the basic IDEA encryption.
  3079. - cbc is the normal 'chaining' form for block ciphers.
  3080. - cfb64 can be used to encrypt single characters, therefore input and output
  3081. do not need to be a multiple of 8.
  3082. - ofb64 is similar to cfb64 but is more like a stream cipher, not as
  3083. secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
  3084. - If you want triple IDEA, thats 384 bits of key and you must be totally
  3085. obsessed with security. Still, if you want it, it is simple enough to
  3086. copy the function from the DES library and change the des_encrypt to
  3087. idea_encrypt; an exercise left for the paranoid reader :-).
  3088. The functions are as follows:
  3089. void idea_set_encrypt_key(
  3090. unsigned char *key;
  3091. IDEA_KEY_SCHEDULE *ks);
  3092. idea_set_encrypt_key converts a 16 byte IDEA key into an
  3093. IDEA_KEY_SCHEDULE. The IDEA_KEY_SCHEDULE is an expanded form of
  3094. the key which can be used to perform IDEA encryption.
  3095. An IDEA_KEY_SCHEDULE is an expanded form of the key which is used to
  3096. perform actual encryption. It can be regenerated from the IDEA key
  3097. so it only needs to be kept when encryption is about
  3098. to occur. Don't save or pass around IDEA_KEY_SCHEDULE's since they
  3099. are CPU architecture dependent, IDEA keys are not.
  3100. void idea_set_decrypt_key(
  3101. IDEA_KEY_SCHEDULE *encrypt_ks,
  3102. IDEA_KEY_SCHEDULE *decrypt_ks);
  3103. This functions converts an encryption IDEA_KEY_SCHEDULE into a
  3104. decryption IDEA_KEY_SCHEDULE. For all decryption, this conversion
  3105. of the key must be done. In some modes of IDEA, an
  3106. encryption/decryption flag is also required, this is because these
  3107. functions involve block chaining and the way this is done changes
  3108. depending on which of encryption of decryption is being done.
  3109. Please note that there is no quick way to generate the decryption
  3110. key schedule other than generating the encryption key schedule and
  3111. then converting it.
  3112. void idea_encrypt(
  3113. unsigned long *data,
  3114. IDEA_KEY_SCHEDULE *ks);
  3115. This is the IDEA encryption function that gets called by just about
  3116. every other IDEA routine in the library. You should not use this
  3117. function except to implement 'modes' of IDEA. I say this because the
  3118. functions that call this routine do the conversion from 'char *' to
  3119. long, and this needs to be done to make sure 'non-aligned' memory
  3120. access do not occur.
  3121. Data is a pointer to 2 unsigned long's and ks is the
  3122. IDEA_KEY_SCHEDULE to use. Encryption or decryption depends on the
  3123. IDEA_KEY_SCHEDULE.
  3124. void idea_ecb_encrypt(
  3125. unsigned char *input,
  3126. unsigned char *output,
  3127. IDEA_KEY_SCHEDULE *ks);
  3128. This is the basic Electronic Code Book form of IDEA (in DES this
  3129. mode is called Electronic Code Book so I'm going to use the term
  3130. for idea as well :-).
  3131. Input is encrypted into output using the key represented by
  3132. ks. Depending on the IDEA_KEY_SCHEDULE, encryption or
  3133. decryption occurs. Input is 8 bytes long and output is 8 bytes.
  3134. void idea_cbc_encrypt(
  3135. unsigned char *input,
  3136. unsigned char *output,
  3137. long length,
  3138. IDEA_KEY_SCHEDULE *ks,
  3139. unsigned char *ivec,
  3140. int enc);
  3141. This routine implements IDEA in Cipher Block Chaining mode.
  3142. Input, which should be a multiple of 8 bytes is encrypted
  3143. (or decrypted) to output which will also be a multiple of 8 bytes.
  3144. The number of bytes is in length (and from what I've said above,
  3145. should be a multiple of 8). If length is not a multiple of 8, bad
  3146. things will probably happen. ivec is the initialisation vector.
  3147. This function updates iv after each call so that it can be passed to
  3148. the next call to idea_cbc_encrypt().
  3149. void idea_cfb64_encrypt(
  3150. unsigned char *in,
  3151. unsigned char *out,
  3152. long length,
  3153. des_key_schedule ks,
  3154. des_cblock *ivec,
  3155. int *num,
  3156. int enc);
  3157. This is one of the more useful functions in this IDEA library, it
  3158. implements CFB mode of IDEA with 64bit feedback.
  3159. This allows you to encrypt an arbitrary number of bytes,
  3160. you do not require 8 byte padding. Each call to this
  3161. routine will encrypt the input bytes to output and then update ivec
  3162. and num. Num contains 'how far' we are though ivec.
  3163. Enc is used to indicate encryption or decryption.
  3164. One very important thing to remember is that when decrypting, use
  3165. the encryption form of the key.
  3166. CFB64 mode operates by using the cipher to
  3167. generate a stream of bytes which is used to encrypt the plain text.
  3168. The cipher text is then encrypted to generate the next 64 bits to
  3169. be xored (incrementally) with the next 64 bits of plain
  3170. text. As can be seen from this, to encrypt or decrypt,
  3171. the same 'cipher stream' needs to be generated but the way the next
  3172. block of data is gathered for encryption is different for
  3173. encryption and decryption. What this means is that to encrypt
  3174. idea_set_encrypt_key(key,ks);
  3175. idea_cfb64_encrypt(...,ks,..,IDEA_ENCRYPT)
  3176. do decrypt
  3177. idea_set_encrypt_key(key,ks)
  3178. idea_cfb64_encrypt(...,ks,...,IDEA_DECRYPT)
  3179. Note: The same IDEA_KEY_SCHEDULE but different encryption flags.
  3180. For idea_cbc or idea_ecb, idea_set_decrypt_key() would need to be
  3181. used to generate the IDEA_KEY_SCHEDULE for decryption.
  3182. The reason I'm stressing this point is that I just wasted 3 hours
  3183. today trying to decrypt using this mode and the decryption form of
  3184. the key :-(.
  3185. void idea_ofb64_encrypt(
  3186. unsigned char *in,
  3187. unsigned char *out,
  3188. long length,
  3189. des_key_schedule ks,
  3190. des_cblock *ivec,
  3191. int *num);
  3192. This functions implements OFB mode of IDEA with 64bit feedback.
  3193. This allows you to encrypt an arbitrary number of bytes,
  3194. you do not require 8 byte padding. Each call to this
  3195. routine will encrypt the input bytes to output and then update ivec
  3196. and num. Num contains 'how far' we are though ivec.
  3197. This is in effect a stream cipher, there is no encryption or
  3198. decryption mode. The same key and iv should be used to
  3199. encrypt and decrypt.
  3200. For reading passwords, I suggest using des_read_pw_string() from my DES library.
  3201. To generate a password from a text string, I suggest using MD5 (or MD2) to
  3202. produce a 16 byte message digest that can then be passed directly to
  3203. idea_set_encrypt_key().
  3204. =====
  3205. For more information about the specific IDEA modes in this library
  3206. (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
  3207. documentation on my DES library. What is said about DES is directly
  3208. applicable for IDEA.
  3209. ==== legal.doc ========================================================
  3210. From eay@mincom.com Thu Jun 27 00:25:45 1996
  3211. Received: by orb.mincom.oz.au id AA15821
  3212. (5.65c/IDA-1.4.4 for eay); Wed, 26 Jun 1996 14:25:45 +1000
  3213. Date: Wed, 26 Jun 1996 14:25:45 +1000 (EST)
  3214. From: Eric Young <eay@mincom.oz.au>
  3215. X-Sender: eay@orb
  3216. To: Ken Toll <ktoll@ren.digitalage.com>
  3217. Cc: Eric Young <eay@mincom.oz.au>, ssl-talk@netscape.com
  3218. Subject: Re: Unidentified subject!
  3219. In-Reply-To: <9606261950.ZM28943@ren.digitalage.com>
  3220. Message-Id: <Pine.SOL.3.91.960626131156.28573K-100000@orb>
  3221. Mime-Version: 1.0
  3222. Content-Type: TEXT/PLAIN; charset=US-ASCII
  3223. Status: O
  3224. X-Status:
  3225. This is a little off topic but since SSLeay is a free implementation of
  3226. the SSLv2 protocol, I feel it is worth responding on the topic of if it
  3227. is actually legal for Americans to use free cryptographic software.
  3228. On Wed, 26 Jun 1996, Ken Toll wrote:
  3229. > Is the U.S the only country that SSLeay cannot be used commercially
  3230. > (because of RSAref) or is that going to be an issue with every country
  3231. > that a client/server application (non-web browser/server) is deployed
  3232. > and sold?
  3233. >From what I understand, the software patents that apply to algorithms
  3234. like RSA and DH only apply in the USA. The IDEA algorithm I believe is
  3235. patened in europe (USA?), but considing how little it is used by other SSL
  3236. implementations, it quite easily be left out of the SSLeay build
  3237. (this can be done with a compile flag).
  3238. Actually if the RSA patent did apply outside the USA, it could be rather
  3239. interesting since RSA is not alowed to let RSA toolkits outside of the USA
  3240. [1], and since these are the only forms that they will alow the algorithm
  3241. to be used in, it would mean that non-one outside of the USA could produce
  3242. public key software which would be a very strong statment for
  3243. international patent law to make :-). This logic is a little flawed but
  3244. it still points out some of the more interesting permutations of USA
  3245. patent law and ITAR restrictions.
  3246. Inside the USA there is also the unresolved issue of RC4/RC2 which were
  3247. made public on sci.crypt in Sep 1994 (RC4) and Feb 1996 (RC2). I have
  3248. copies of the origional postings if people are interested. RSA I believe
  3249. claim that they were 'trade-secrets' and that some-one broke an NDA in
  3250. revealing them. Other claim they reverse engineered the algorithms from
  3251. compiled binaries. If the algorithms were reverse engineered, I believe
  3252. RSA had no legal leg to stand on. If an NDA was broken, I don't know.
  3253. Regardless, RSA, I believe, is willing to go to court over the issue so
  3254. licencing is probably the best idea, or at least talk to them.
  3255. If there are people who actually know more about this, pease let me know, I
  3256. don't want to vilify or spread miss-information if I can help it.
  3257. If you are not producing a web browser, it is easy to build SSLeay with
  3258. RC2/RC4 removed. Since RC4 is the defacto standard cipher in
  3259. all web software (and it is damn fast) it is more or less required for
  3260. www use. For non www use of SSL, especially for an application where
  3261. interoperability with other vendors is not critical just leave it out.
  3262. Removing IDEA, RC2 and RC4 would only leave DES and Triple DES but
  3263. they should be ok. Considing that Triple DES can encrypt at rates of
  3264. 410k/sec on a pentium 100, and 940k/sec on a P6/200, this is quite
  3265. reasonable performance. Single DES clocks in at 1160k/s and 2467k/s
  3266. respectivly is actually quite fast for those not so paranoid (56 bit key).[1]
  3267. > Is it possible to get a certificate for commercial use outside of the U.S.?
  3268. yes.
  3269. Thawte Consulting issues certificates (they are the people who sell the
  3270. Sioux httpd server and are based in South Africa)
  3271. Verisign will issue certificates for Sioux (sold from South Africa), so this
  3272. proves that they will issue certificate for OS use if they are
  3273. happy with the quality of the software.
  3274. (The above mentioned companies just the ones that I know for sure are issuing
  3275. certificates outside the USA).
  3276. There is always the point that if you are using SSL for an intra net,
  3277. SSLeay provides programs that can be used so you can issue your own
  3278. certificates. They need polishing but at least it is a good starting point.
  3279. I am not doing anything outside Australian law by implementing these
  3280. algorithms (to the best of my knowedge). It is another example of how
  3281. the world legal system does not cope with the internet very well.
  3282. I may start making shared libraries available (I have now got DLL's for
  3283. Windows). This will mean that distributions into the usa could be
  3284. shipped with a version with a reduced cipher set and the versions outside
  3285. could use the DLL/shared library with all the ciphers (and without RSAref).
  3286. This could be completly hidden from the application, so this would not
  3287. even require a re-linking.
  3288. This is the reverse of what people were talking about doing to get around
  3289. USA export regulations :-)
  3290. eric
  3291. [1]: The RSAref2.0 tookit is available on at least 3 ftp sites in Europe
  3292. and one in South Africa.
  3293. [2]: Since I always get questions when I post benchmark numbers :-),
  3294. DES performace figures are in 1000's of bytes per second in cbc
  3295. mode using an 8192 byte buffer. The pentium 100 was running Windows NT
  3296. 3.51 DLLs and the 686/200 was running NextStep.
  3297. I quote pentium 100 benchmarks because it is basically the
  3298. 'entry level' computer that most people buy for personal use.
  3299. Windows 95 is the OS shipping on those boxes, so I'll give
  3300. NT numbers (the same Win32 runtime environment). The 686
  3301. numbers are present as an indication of where we will be in a
  3302. few years.
  3303. --
  3304. Eric Young | BOOL is tri-state according to Bill Gates.
  3305. AARNet: eay@mincom.oz.au | RTFM Win32 GetMessage().
  3306. ==== lhash.doc ========================================================
  3307. The LHASH library.
  3308. I wrote this library in 1991 and have since forgotten why I called it lhash.
  3309. It implements a hash table from an article I read at the
  3310. time from 'Communications of the ACM'. What makes this hash
  3311. table different is that as the table fills, the hash table is
  3312. increased (or decreased) in size via realloc().
  3313. When a 'resize' is done, instead of all hashes being redistributed over
  3314. twice as many 'buckets', one bucket is split. So when an 'expand' is done,
  3315. there is only a minimal cost to redistribute some values. Subsequent
  3316. inserts will cause more single 'bucket' redistributions but there will
  3317. never be a sudden large cost due to redistributing all the 'buckets'.
  3318. The state for a particular hash table is kept in the LHASH structure.
  3319. The LHASH structure also records statistics about most aspects of accessing
  3320. the hash table. This is mostly a legacy of my writing this library for
  3321. the reasons of implementing what looked like a nice algorithm rather than
  3322. for a particular software product.
  3323. Internal stuff you probably don't want to know about.
  3324. The decision to increase or decrease the hash table size is made depending
  3325. on the 'load' of the hash table. The load is the number of items in the
  3326. hash table divided by the size of the hash table. The default values are
  3327. as follows. If (hash->up_load < load) => expand.
  3328. if (hash->down_load > load) => contract. The 'up_load' has a default value of
  3329. 1 and 'down_load' has a default value of 2. These numbers can be modified
  3330. by the application by just playing with the 'up_load' and 'down_load'
  3331. variables. The 'load' is kept in a form which is multiplied by 256. So
  3332. hash->up_load=8*256; will cause a load of 8 to be set.
  3333. If you are interested in performance the field to watch is
  3334. num_comp_calls. The hash library keeps track of the 'hash' value for
  3335. each item so when a lookup is done, the 'hashes' are compared, if
  3336. there is a match, then a full compare is done, and
  3337. hash->num_comp_calls is incremented. If num_comp_calls is not equal
  3338. to num_delete plus num_retrieve it means that your hash function is
  3339. generating hashes that are the same for different values. It is
  3340. probably worth changing your hash function if this is the case because
  3341. even if your hash table has 10 items in a 'bucked', it can be searched
  3342. with 10 'unsigned long' compares and 10 linked list traverses. This
  3343. will be much less expensive that 10 calls to you compare function.
  3344. LHASH *lh_new(
  3345. unsigned long (*hash)(),
  3346. int (*cmp)());
  3347. This function is used to create a new LHASH structure. It is passed
  3348. function pointers that are used to store and retrieve values passed
  3349. into the hash table. The 'hash'
  3350. function is a hashing function that will return a hashed value of
  3351. it's passed structure. 'cmp' is passed 2 parameters, it returns 0
  3352. is they are equal, otherwise, non zero.
  3353. If there are any problems (usually malloc failures), NULL is
  3354. returned, otherwise a new LHASH structure is returned. The
  3355. hash value is normally truncated to a power of 2, so make sure
  3356. that your hash function returns well mixed low order bits.
  3357. void lh_free(
  3358. LHASH *lh);
  3359. This function free()s a LHASH structure. If there is malloced
  3360. data in the hash table, it will not be freed. Consider using the
  3361. lh_doall function to deallocate any remaining entries in the hash
  3362. table.
  3363. char *lh_insert(
  3364. LHASH *lh,
  3365. char *data);
  3366. This function inserts the data pointed to by data into the lh hash
  3367. table. If there is already and entry in the hash table entry, the
  3368. value being replaced is returned. A NULL is returned if the new
  3369. entry does not clash with an entry already in the table (the normal
  3370. case) or on a malloc() failure (perhaps I should change this....).
  3371. The 'char *data' is exactly what is passed to the hash and
  3372. comparison functions specified in lh_new().
  3373. char *lh_delete(
  3374. LHASH *lh,
  3375. char *data);
  3376. This routine deletes an entry from the hash table. The value being
  3377. deleted is returned. NULL is returned if there is no such value in
  3378. the hash table.
  3379. char *lh_retrieve(
  3380. LHASH *lh,
  3381. char *data);
  3382. If 'data' is in the hash table it is returned, else NULL is
  3383. returned. The way these routines would normally be uses is that a
  3384. dummy structure would have key fields populated and then
  3385. ret=lh_retrieve(hash,&dummy);. Ret would now be a pointer to a fully
  3386. populated structure.
  3387. void lh_doall(
  3388. LHASH *lh,
  3389. void (*func)(char *a));
  3390. This function will, for every entry in the hash table, call function
  3391. 'func' with the data item as parameters.
  3392. This function can be quite useful when used as follows.
  3393. void cleanup(STUFF *a)
  3394. { STUFF_free(a); }
  3395. lh_doall(hash,cleanup);
  3396. lh_free(hash);
  3397. This can be used to free all the entries, lh_free() then
  3398. cleans up the 'buckets' that point to nothing. Be careful
  3399. when doing this. If you delete entries from the hash table,
  3400. in the call back function, the table may decrease in size,
  3401. moving item that you are
  3402. currently on down lower in the hash table. This could cause
  3403. some entries to be skipped. The best solution to this problem
  3404. is to set lh->down_load=0 before you start. This will stop
  3405. the hash table ever being decreased in size.
  3406. void lh_doall_arg(
  3407. LHASH *lh;
  3408. void(*func)(char *a,char *arg));
  3409. char *arg;
  3410. This function is the same as lh_doall except that the function
  3411. called will be passed 'arg' as the second argument.
  3412. unsigned long lh_strhash(
  3413. char *c);
  3414. This function is a demo string hashing function. Since the LHASH
  3415. routines would normally be passed structures, this routine would
  3416. not normally be passed to lh_new(), rather it would be used in the
  3417. function passed to lh_new().
  3418. The next three routines print out various statistics about the state of the
  3419. passed hash table. These numbers are all kept in the lhash structure.
  3420. void lh_stats(
  3421. LHASH *lh,
  3422. FILE *out);
  3423. This function prints out statistics on the size of the hash table,
  3424. how many entries are in it, and the number and result of calls to
  3425. the routines in this library.
  3426. void lh_node_stats(
  3427. LHASH *lh,
  3428. FILE *out);
  3429. For each 'bucket' in the hash table, the number of entries is
  3430. printed.
  3431. void lh_node_usage_stats(
  3432. LHASH *lh,
  3433. FILE *out);
  3434. This function prints out a short summary of the state of the hash
  3435. table. It prints what I call the 'load' and the 'actual load'.
  3436. The load is the average number of data items per 'bucket' in the
  3437. hash table. The 'actual load' is the average number of items per
  3438. 'bucket', but only for buckets which contain entries. So the
  3439. 'actual load' is the average number of searches that will need to
  3440. find an item in the hash table, while the 'load' is the average number
  3441. that will be done to record a miss.
  3442. ==== md2.doc ========================================================
  3443. The MD2 library.
  3444. MD2 is a message digest algorithm that can be used to condense an arbitrary
  3445. length message down to a 16 byte hash. The functions all need to be passed
  3446. a MD2_CTX which is used to hold the MD2 context during multiple MD2_Update()
  3447. function calls. The normal method of use for this library is as follows
  3448. MD2_Init(...);
  3449. MD2_Update(...);
  3450. ...
  3451. MD2_Update(...);
  3452. MD2_Final(...);
  3453. This library requires the inclusion of 'md2.h'.
  3454. The main negative about MD2 is that it is slow, especially when compared
  3455. to MD5.
  3456. The functions are as follows:
  3457. void MD2_Init(
  3458. MD2_CTX *c);
  3459. This function needs to be called to initiate a MD2_CTX structure for
  3460. use.
  3461. void MD2_Update(
  3462. MD2_CTX *c;
  3463. unsigned char *data;
  3464. unsigned long len);
  3465. This updates the message digest context being generated with 'len'
  3466. bytes from the 'data' pointer. The number of bytes can be any
  3467. length.
  3468. void MD2_Final(
  3469. unsigned char *md;
  3470. MD2_CTX *c;
  3471. This function is called when a message digest of the data digested
  3472. with MD2_Update() is wanted. The message digest is put in the 'md'
  3473. array and is MD2_DIGEST_LENGTH (16) bytes long.
  3474. unsigned char *MD2(
  3475. unsigned long n;
  3476. unsigned char *d;
  3477. unsigned char *md;
  3478. This function performs a MD2_Init(), followed by a MD2_Update()
  3479. followed by a MD2_Final() (using a local MD2_CTX).
  3480. The resulting digest is put into 'md' if it is not NULL.
  3481. Regardless of the value of 'md', the message
  3482. digest is returned from the function. If 'md' was NULL, the message
  3483. digest returned is being stored in a static structure.
  3484. ==== md5.doc ========================================================
  3485. The MD5 library.
  3486. MD5 is a message digest algorithm that can be used to condense an arbitrary
  3487. length message down to a 16 byte hash. The functions all need to be passed
  3488. a MD5_CTX which is used to hold the MD5 context during multiple MD5_Update()
  3489. function calls. This library also contains random number routines that are
  3490. based on MD5
  3491. The normal method of use for this library is as follows
  3492. MD5_Init(...);
  3493. MD5_Update(...);
  3494. ...
  3495. MD5_Update(...);
  3496. MD5_Final(...);
  3497. This library requires the inclusion of 'md5.h'.
  3498. The functions are as follows:
  3499. void MD5_Init(
  3500. MD5_CTX *c);
  3501. This function needs to be called to initiate a MD5_CTX structure for
  3502. use.
  3503. void MD5_Update(
  3504. MD5_CTX *c;
  3505. unsigned char *data;
  3506. unsigned long len);
  3507. This updates the message digest context being generated with 'len'
  3508. bytes from the 'data' pointer. The number of bytes can be any
  3509. length.
  3510. void MD5_Final(
  3511. unsigned char *md;
  3512. MD5_CTX *c;
  3513. This function is called when a message digest of the data digested
  3514. with MD5_Update() is wanted. The message digest is put in the 'md'
  3515. array and is MD5_DIGEST_LENGTH (16) bytes long.
  3516. unsigned char *MD5(
  3517. unsigned char *d;
  3518. unsigned long n;
  3519. unsigned char *md;
  3520. This function performs a MD5_Init(), followed by a MD5_Update()
  3521. followed by a MD5_Final() (using a local MD5_CTX).
  3522. The resulting digest is put into 'md' if it is not NULL.
  3523. Regardless of the value of 'md', the message
  3524. digest is returned from the function. If 'md' was NULL, the message
  3525. digest returned is being stored in a static structure.
  3526. ==== memory.doc ========================================================
  3527. In the interests of debugging SSLeay, there is an option to compile
  3528. using some simple memory leak checking.
  3529. All malloc(), free() and realloc() calls in SSLeay now go via
  3530. Malloc(), Free() and Realloc() (except those in crypto/lhash).
  3531. If CRYPTO_MDEBUG is defined, these calls are #defined to
  3532. CRYPTO_malloc(), CRYPTO_free() and CRYPTO_realloc().
  3533. If it is not defined, they are #defined to malloc(), free() and realloc().
  3534. the CRYPTO_malloc() routines by default just call the underlying library
  3535. functons.
  3536. If CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON) is called, memory leak detection is
  3537. turned on. CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_OFF) turns it off.
  3538. When turned on, each Malloc() or Realloc() call is recored along with the file
  3539. and line number from where the call was made. (This is done using the
  3540. lhash library which always uses normal system malloc(3) routines).
  3541. void CRYPTO_mem_leaks(BIO *b);
  3542. void CRYPTO_mem_leaks_fp(FILE *fp);
  3543. These both print out the list of memory that has not been free()ed.
  3544. This will probably be rather hard to read, but if you look for the 'top level'
  3545. structure allocation, this will often give an idea as to what is not being
  3546. free()ed. I don't expect people to use this stuff normally.
  3547. ==== ca.1 ========================================================
  3548. From eay@orb.mincom.oz.au Thu Dec 28 23:56:45 1995
  3549. Received: by orb.mincom.oz.au id AA07374
  3550. (5.65c/IDA-1.4.4 for eay); Thu, 28 Dec 1995 13:56:45 +1000
  3551. Date: Thu, 28 Dec 1995 13:56:45 +1000 (EST)
  3552. From: Eric Young <eay@mincom.oz.au>
  3553. X-Sender: eay@orb
  3554. To: sameer <sameer@c2.org>
  3555. Cc: ssleay@mincom.oz.au
  3556. Subject: Re: 'ca'
  3557. In-Reply-To: <199512230440.UAA23410@infinity.c2.org>
  3558. Message-Id: <Pine.SOL.3.91.951228133525.7269A-100000@orb>
  3559. Mime-Version: 1.0
  3560. Content-Type: TEXT/PLAIN; charset=US-ASCII
  3561. Status: RO
  3562. X-Status:
  3563. On Fri, 22 Dec 1995, sameer wrote:
  3564. > I could use documentation on 'ca'. Thanks.
  3565. Very quickly.
  3566. The ca program uses the ssleay.conf file for most of its configuration
  3567. ./ca -help
  3568. -verbose - Talk alot while doing things
  3569. -config file - A config file. If you don't want to use the
  3570. default config file
  3571. -name arg - The particular CA definition to use
  3572. In the config file, the section to use for parameters. This lets
  3573. multiple setups to be contained in the one file. By default, the
  3574. default_ca variable is looked up in the [ ca ] section. So in the
  3575. shipped ssleay.conf, the CA definition used is CA_default. It could be
  3576. any other name.
  3577. -gencrl days - Generate a new CRL, days is when the next CRL is due
  3578. This will generate a new certificate revocion list.
  3579. -days arg - number of days to certify the certificate for
  3580. When certifiying certificates, this is the number of days to use.
  3581. -md arg - md to use, one of md2, md5, sha or sha1
  3582. -policy arg - The CA 'policy' to support
  3583. I'll describe this later, but there are 2 policies definied in the
  3584. shipped ssleay.conf
  3585. -keyfile arg - PEM RSA private key file
  3586. -key arg - key to decode the RSA private key if it is encrypted
  3587. since we need to keep the CA's RSA key encrypted
  3588. -cert - The CA certificate
  3589. -in file - The input PEM encoded certificate request(s)
  3590. -out file - Where to put the output file(s)
  3591. -outdir dir - Where to put output certificates
  3592. The -out options concatinates all the output certificied
  3593. certificates to one file, -outdir puts them in a directory,
  3594. named by serial number.
  3595. -infiles .... - The last argument, requests to process
  3596. The certificate requests to process, -in is the same.
  3597. Just about all the above have default values defined in ssleay.conf.
  3598. The key variables in ssleay.conf are (for the pariticular '-name' being
  3599. used, in the default, it is CA_default).
  3600. dir is where all the CA database stuff is kept.
  3601. certs is where all the previously issued certificates are kept.
  3602. The database is a simple text database containing the following tab separated
  3603. fields.
  3604. status: a value of 'R' - revoked, 'E' -expired or 'V' valid.
  3605. issued date: When the certificate was certified.
  3606. revoked date: When it was revoked, blank if not revoked.
  3607. serial number: The certificate serial number.
  3608. certificate: Where the certificate is located.
  3609. CN: The name of the certificate.
  3610. The demo file has quite a few made up values it it. The last 2 were
  3611. added by the ca program and are acurate.
  3612. The CA program does not update the 'certificate' file correctly right now.
  3613. The serial field should be unique as should the CN/status combination.
  3614. The ca program checks these at startup. What still needs to be
  3615. wrtten is a program to 'regenerate' the data base file from the issued
  3616. certificate list (and a CRL list).
  3617. Back to the CA_default variables.
  3618. Most of the variables are commented.
  3619. policy is the default policy.
  3620. Ok for policies, they define the order and which fields must be present
  3621. in the certificate request and what gets filled in.
  3622. So a value of
  3623. countryName = match
  3624. means that the country name must match the CA certificate.
  3625. organizationalUnitName = optional
  3626. The org.Unit,Name does not have to be present and
  3627. commonName = supplied
  3628. commonName must be supplied in the certificate request.
  3629. For the 'policy_match' polocy, the order of the attributes in the
  3630. generated certiticate would be
  3631. countryName
  3632. stateOrProvinceName
  3633. organizationName
  3634. organizationalUnitName
  3635. commonName
  3636. emailAddress
  3637. Have a play, it sort of makes sense. If you think about how the persona
  3638. requests operate, it is similar to the 'policy_match' policy and the
  3639. 'policy_anything' is similar to what versign is doing.
  3640. I hope this helps a bit. Some backend scripts are definitly needed to
  3641. update the database and to make certificate revocion easy. All
  3642. certificates issued should also be kept forever (or until they expire?)
  3643. hope this helps
  3644. eric (who has to run off an buy some cheap knee pads for the caving in 4
  3645. days time :-)
  3646. --
  3647. Eric Young | Signature removed since it was generating
  3648. AARNet: eay@mincom.oz.au | more followups than the message contents :-)
  3649. ==== ms3-ca.doc ========================================================
  3650. Date: Mon, 9 Jun 97 08:00:33 +0200
  3651. From: Holger.Reif@PrakInf.TU-Ilmenau.DE (Holger Reif)
  3652. Subject: ms3-ca.doc
  3653. Organization: TU Ilmenau, Fak. IA, FG Telematik
  3654. Content-Length: 14575
  3655. Status: RO
  3656. X-Status:
  3657. Loading client certs into MSIE 3.01
  3658. ===================================
  3659. This document contains all the information necessary to successfully set up
  3660. some scripts to issue client certs to Microsoft Internet Explorer. It
  3661. includes the required knowledge about the model MSIE uses for client
  3662. certification and includes complete sample scripts ready to play with. The
  3663. scripts were tested against a modified ca program of SSLeay 0.6.6 and should
  3664. work with the regular ca program that comes with version 0.8.0. I haven't
  3665. tested against MSIE 4.0
  3666. You can use the information contained in this document in either way you
  3667. want. However if you feel it saved you a lot of time I ask you to be as fair
  3668. as to mention my name: Holger Reif <reif@prakinf.tu-ilmenau.de>.
  3669. 1.) The model used by MSIE
  3670. --------------------------
  3671. The Internet Explorer doesn't come with a embedded engine for installing
  3672. client certs like Netscape's Navigator. It rather uses the CryptoAPI (CAPI)
  3673. defined by Microsoft. CAPI comes with WindowsNT 4.0 or is installed together
  3674. with Internet Explorer since 3.01. The advantage of this approach is a higher
  3675. flexibility because the certificates in the (per user) system open
  3676. certificate store may be used by other applications as well. The drawback
  3677. however is that you need to do a bit more work to get a client cert issued.
  3678. CAPI defines functions which will handle basic cryptographic work, eg.
  3679. generating keys, encrypting some data, signing text or building a certificate
  3680. request. The procedure is as follows: A CAPI function generates you a key
  3681. pair and saves it into the certificate store. After that one builds a
  3682. Distinguished Name. Together with that key pair another CAPI function forms a
  3683. PKCS#10 request which you somehow need to submit to a CA. Finally the issued
  3684. cert is given to a yet another CAPI function which saves it into the
  3685. certificate store.
  3686. The certificate store with the user's keys and certs is in the registry. You
  3687. will find it under HKEY_CURRENT_USER/Software/Microsoft/Cryptography/ (I
  3688. leave it to you as a little exercise to figure out what all the entries mean
  3689. ;-). Note that the keys are protected only with the user's usual Windows
  3690. login password.
  3691. 2.) The practical usage
  3692. -----------------------
  3693. Unfortunatly since CAPI is a system API you can't access its functions from
  3694. HTML code directly. For this purpose Microsoft provides a wrapper called
  3695. certenr3.dll. This DLL accesses the CAPI functions and provides an interface
  3696. usable from Visual Basic Script. One needs to install that library on the
  3697. computer which wants to have client cert. The easiest way is to load it as an
  3698. ActiveX control (certenr3.dll is properly authenticode signed by MS ;-). If
  3699. you have ever enrolled e cert request at a CA you will have installed it.
  3700. At time of writing certenr3.dll is contained in
  3701. http://www.microsoft.com/workshop/prog/security/csa/certenr3.exe. It comes
  3702. with an README file which explains the available functions. It is labeled
  3703. beta but every CA seems to use it anyway. The license.txt allows you the
  3704. usage for your own purposes (as far as I understood) and a somehow limited
  3705. distribution.
  3706. The two functions of main interest are GenerateKeyPair and AcceptCredentials.
  3707. For complete explanation of all possible parameters see the README file. Here
  3708. are only minimal required parameters and their values.
  3709. GenerateKeyPair(sessionID, FASLE, szName, 0, "ClientAuth", TRUE, FALSE, 1)
  3710. - sessionID is a (locally to that computer) unique string to correlate the
  3711. generated key pair with a cert installed later.
  3712. - szName is the DN of the form "C=DE; S=Thueringen; L=Ilmenau; CN=Holger
  3713. Reif; 1.2.840.113549.1.9.1=reif@prakinf.tu-ilmenau.de". Note that S is the
  3714. abreviation for StateOrProvince. The recognized abreviation include CN, O, C,
  3715. OU, G, I, L, S, T. If the abreviation is unknown (eg. for PKCS#9 email addr)
  3716. you need to use the full object identifier. The starting point for searching
  3717. them could be crypto/objects.h since all OIDs know to SSLeay are listed
  3718. there.
  3719. - note: the possible ninth parameter which should give a default name to the
  3720. certificate storage location doesn't seem to work. Changes to the constant
  3721. values in the call above doesn't seem to make sense. You can't generate
  3722. PKCS#10 extensions with that function.
  3723. The result of GenerateKeyPair is the base64 encoded PKCS#10 request. However
  3724. it has a little strange format that SSLeay doesn't accept. (BTW I feel the
  3725. decision of rejecting that format as standard conforming.) It looks like
  3726. follows:
  3727. 1st line with 76 chars
  3728. 2nd line with 76 chars
  3729. ...
  3730. (n-2)th line with 76 chars
  3731. (n-1)th line contains a multiple of 4 chars less then 76 (possible
  3732. empty)
  3733. (n)th line has zero or 4 chars (then with 1 or 2 equal signs - the
  3734. original text's lenght wasn'T a multiple of 3)
  3735. The line separator has two chars: 0x0d 0x0a
  3736. AcceptCredentials(sessionID, credentials, 0, FALSE)
  3737. - sessionID needs to be the same as while generating the key pair
  3738. - credentials is the base64 encoded PKCS#7 object containing the cert.
  3739. CRL's and CA certs are not required simply just the client cert. (It seems to
  3740. me that both are not even checked somehow.) The only format of the base64
  3741. encoded object I succesfully used was all characters in a very long string
  3742. without line feeds or carriage returns. (Hey, it doesn't matter, only a
  3743. computer reads it!)
  3744. The result should be S_OK. For error handling see the example that comes with
  3745. certenr3.dll.
  3746. A note about ASN.1 character encodings. certenr3.dll seems to know only about
  3747. 2 of them: UniversalString and PrintableString. First it is definitely wrong
  3748. for an email address which is IA5STRING (checked by ssleay's ca). Second
  3749. unfortunately MSIE (at least until version 3.02) can't handle UniversalString
  3750. correctly - they just blow up you cert store! Therefore ssleay's ca (starting
  3751. from version 0.8.0) tries to convert the encodings automatically to IA5STRING
  3752. or TeletexString. The beef is it will work only for the latin-1 (western)
  3753. charset. Microsoft still has to do abit of homework...
  3754. 3.) An example
  3755. --------------
  3756. At least you need two steps: generating the key & request and then installing
  3757. the certificate. A real world CA would have some more steps involved, eg.
  3758. accepting some license. Note that both scripts shown below are just
  3759. experimental state without any warrenty!
  3760. First how to generate a request. Note that we can't use a static page because
  3761. of the sessionID. I generate it from system time plus pid and hope it is
  3762. unique enough. Your are free to feed it through md5 to get more impressive
  3763. ID's ;-) Then the intended text is read in with sed which inserts the
  3764. sessionID.
  3765. -----BEGIN ms-enroll.cgi-----
  3766. #!/bin/sh
  3767. SESSION_ID=`date '+%y%m%d%H%M%S'`$$
  3768. echo Content-type: text/html
  3769. echo
  3770. sed s/template_for_sessId/$SESSION_ID/ <<EOF
  3771. <HTML><HEAD>
  3772. <TITLE>Certificate Enrollment Test Page</TITLE>
  3773. </HEAD><BODY>
  3774. <OBJECT
  3775. classid="clsid:33BEC9E0-F78F-11cf-B782-00C04FD7BF43"
  3776. codebase=certenr3.dll
  3777. id=certHelper
  3778. >
  3779. </OBJECT>
  3780. <CENTER>
  3781. <H2>enrollment for a personal cert</H2>
  3782. <BR><HR WIDTH=50%><BR><P>
  3783. <FORM NAME="MSIE_Enrollment" ACTION="ms-gencert.cgi" ENCTYPE=x-www-form-
  3784. encoded METHOD=POST>
  3785. <TABLE>
  3786. <TR><TD>Country</TD><TD><INPUT NAME="Country" VALUE=""></TD></TR>
  3787. <TR><TD>State</TD><TD><INPUT NAME="StateOrProvince" VALUE=""></TD></TR>
  3788. <TR><TD>Location</TD><TD><INPUT NAME="Location" VALUE=""></TD></TR>
  3789. <TR><TD>Organization</TD><TD><INPUT NAME="Organization"
  3790. VALUE=""></TD></TR>
  3791. <TR><TD>Organizational Unit</TD>
  3792. <TD><INPUT NAME="OrganizationalUnit" VALUE=""></TD></TR>
  3793. <TR><TD>Name</TD><TD><INPUT NAME="CommonName" VALUE=""></TD></TR>
  3794. <TR><TD>eMail Address</TD>
  3795. <TD><INPUT NAME="EmailAddress" VALUE=""></TD></TR>
  3796. <TR><TD></TD>
  3797. <TD><INPUT TYPE="BUTTON" NAME="submit" VALUE="Beantragen"></TD></TR>
  3798. </TABLE>
  3799. <INPUT TYPE="hidden" NAME="SessionId" VALUE="template_for_sessId">
  3800. <INPUT TYPE="hidden" NAME="Request" VALUE="">
  3801. </FORM>
  3802. <BR><HR WIDTH=50%><BR><P>
  3803. </CENTER>
  3804. <SCRIPT LANGUAGE=VBS>
  3805. Dim DN
  3806. Sub Submit_OnClick
  3807. Dim TheForm
  3808. Set TheForm = Document.MSIE_Enrollment
  3809. sessionId = TheForm.SessionId.value
  3810. reqHardware = FALSE
  3811. C = TheForm.Country.value
  3812. SP = TheForm.StateOrProvince.value
  3813. L = TheForm.Location.value
  3814. O = TheForm.Organization.value
  3815. OU = TheForm.OrganizationalUnit.value
  3816. CN = TheForm.CommonName.value
  3817. Email = TheForm.EmailAddress.value
  3818. szPurpose = "ClientAuth"
  3819. doAcceptanceUINow = FALSE
  3820. doOnline = TRUE
  3821. DN = ""
  3822. Call Add_RDN("C", C)
  3823. Call Add_RDN("S", SP)
  3824. Call Add_RDN("L", L)
  3825. Call Add_RDN("O", O)
  3826. Call Add_RDN("OU", OU)
  3827. Call Add_RDN("CN", CN)
  3828. Call Add_RDN("1.2.840.113549.1.9.1", Email)
  3829. ' rsadsi
  3830. ' pkcs
  3831. ' pkcs9
  3832. ' eMailAddress
  3833. On Error Resume Next
  3834. sz10 = certHelper.GenerateKeyPair(sessionId, _
  3835. FALSE, DN, 0, ClientAuth, FASLE, TRUE, 1)_
  3836. theError = Err.Number
  3837. On Error Goto 0
  3838. if (sz10 = Empty OR theError <> 0) Then
  3839. sz = "The error '" & Hex(theError) & "' occurred." & chr(13) & _
  3840. chr(10) & "Your credentials could not be generated."
  3841. result = MsgBox(sz, 0, "Credentials Enrollment")
  3842. Exit Sub
  3843. else
  3844. TheForm.Request.value = sz10
  3845. TheForm.Submit
  3846. end if
  3847. End Sub
  3848. Sub Add_RDN(sn, value)
  3849. if (value <> "") then
  3850. if (DN <> "") then
  3851. DN = DN & "; "
  3852. end if
  3853. DN = DN & sn & "=" & value
  3854. end if
  3855. End Sub
  3856. </SCRIPT>
  3857. </BODY>
  3858. </HTML>
  3859. EOF
  3860. -----END ms-enroll.cgi-----
  3861. Second, how to extract the request and feed the certificate back? We need to
  3862. "normalize" the base64 encoding of the PKCS#10 format which means
  3863. regenerating the lines and wrapping with BEGIN and END line. This is done by
  3864. gawk. The request is taken by ca the normal way. Then the cert needs to be
  3865. packed into a PKCS#7 structure (note: the use of a CRL is necessary for
  3866. crl2pkcs7 as of version 0.6.6. Starting with 0.8.0 it it might probably be
  3867. ommited). Finally we need to format the PKCS#7 object and generate the HTML
  3868. text. I use two templates to have a clearer script.
  3869. 1st note: postit2 is slightly modified from a program I found at ncsa's ftp
  3870. site. Grab it from http://www.easterngraphics.com/certs/IX9704/postit2.c. You
  3871. need utils.c from there too.
  3872. 2nd note: I'm note quite sure wether the gawk script really handles all
  3873. possible inputs for the request right! Today I don't use this construction
  3874. anymore myself.
  3875. 3d note: the cert must be of version 3! This could be done with the nsComment
  3876. line in ssleay.cnf...
  3877. ------BEGIN ms-gencert.cgi-----
  3878. #!/bin/sh
  3879. FILE="/tmp/"`date '+%y%m%d%H%M%S'-`$$
  3880. rm -f "$FILE".*
  3881. HOME=`pwd`; export HOME # as ssleay.cnf insists on having such an env var
  3882. cd /usr/local/ssl #where demoCA (as named in ssleay.conf) is located
  3883. postit2 -s " " -i 0x0d > "$FILE".inp # process the FORM vars
  3884. SESSION_ID=`gawk '$1 == "SessionId" { print $2; exit }' "$FILE".inp`
  3885. gawk \
  3886. 'BEGIN { \
  3887. OFS = ""; \
  3888. print "-----BEGIN CERTIFICATE REQUEST-----"; \
  3889. req_seen=0 \
  3890. } \
  3891. $1 == "Request" { \
  3892. req_seen=1; \
  3893. if (length($2) == 72) print($2); \
  3894. lastline=$2; \
  3895. next; \
  3896. } \
  3897. { \
  3898. if (req_seen == 1) { \
  3899. if (length($1) >= 72) print($1); \
  3900. else if (length(lastline) < 72) { \
  3901. req_seen=0; \
  3902. print (lastline,$1); \
  3903. } \
  3904. lastline=$1; \
  3905. } \
  3906. } \
  3907. END { \
  3908. print "-----END CERTIFICATE REQUEST-----"; \
  3909. }' > "$FILE".pem < "$FILE".inp
  3910. ssleay ca -batch -in "$FILE".pem -key passwd -out "$FILE".out
  3911. ssleay crl2pkcs7 -certfile "$FILE".out -out "$FILE".pkcs7 -in demoCA/crl.pem
  3912. sed s/template_for_sessId/$SESSION_ID/ <ms-enroll2a.html >"$FILE".cert
  3913. /usr/local/bin/gawk \
  3914. 'BEGIN { \
  3915. OFS = ""; \
  3916. dq = sprintf("%c",34); \
  3917. } \
  3918. $0 ~ "PKCS7" { next; } \
  3919. { \
  3920. print dq$0dq" & _"; \
  3921. }' <"$FILE".pkcs7 >> "$FILE".cert
  3922. cat ms-enroll2b.html >>"$FILE".cert
  3923. echo Content-type: text/html
  3924. echo Content-length: `wc -c "$FILE".cert`
  3925. echo
  3926. cat "$FILE".cert
  3927. rm -f "$FILE".*
  3928. -----END ms-gencert.cgi-----
  3929. ----BEGIN ms-enroll2a.html----
  3930. <HTML><HEAD><TITLE>Certificate Acceptance Test Page</TITLE></HEAD><BODY>
  3931. <OBJECT
  3932. classid="clsid:33BEC9E0-F78F-11cf-B782-00C04FD7BF43"
  3933. codebase=certenr3.dll
  3934. id=certHelper
  3935. >
  3936. </OBJECT>
  3937. <CENTER>
  3938. <H2>Your personal certificate</H2>
  3939. <BR><HR WIDTH=50%><BR><P>
  3940. Press the button!
  3941. <P><INPUT TYPE=BUTTON VALUE="Nimm mich!" NAME="InstallCert">
  3942. </CENTER>
  3943. <BR><HR WIDTH=50%><BR>
  3944. <SCRIPT LANGUAGE=VBS>
  3945. Sub InstallCert_OnClick
  3946. sessionId = "template_for_sessId"
  3947. credentials = "" & _
  3948. ----END ms-enroll2a.html----
  3949. ----BEGIN ms-enroll2b.html----
  3950. ""
  3951. On Error Resume Next
  3952. result = certHelper.AcceptCredentials(sessionId, credentials, 0,
  3953. FALSE)
  3954. if (IsEmpty(result)) Then
  3955. sz = "The error '" & Err.Number & "' occurred." & chr(13) &
  3956. chr(10) & "This Digital ID could not be registered."
  3957. msgOut = MsgBox(sz, 0, "Credentials Registration Error")
  3958. navigate "error.html"
  3959. else
  3960. sz = "Digital ID successfully registered."
  3961. msgOut = MsgBox(sz, 0, "Credentials Registration")
  3962. navigate "success.html"
  3963. end if
  3964. Exit Sub
  3965. End Sub
  3966. </SCRIPT>
  3967. </BODY>
  3968. </HTML>
  3969. ----END ms-enroll2b.html----
  3970. 4.) What do do with the cert?
  3971. -----------------------------
  3972. The cert is visible (without restarting MSIE) under the following menu:
  3973. View->Options->Security->Personal certs. You can examine it's contents at
  3974. least partially.
  3975. To use it for client authentication you need to use SSL3.0 (fortunately
  3976. SSLeay supports it with 0.8.0). Furthermore MSIE is told to only supports a
  3977. kind of automatic selection of certs (I personally wasn't able to test it
  3978. myself). But there is a requirement that the issuer of the server cert and
  3979. the issuer of the client cert needs to be the same (according to a developer
  3980. from MS). Which means: you need may more then one cert to talk to all
  3981. servers...
  3982. I'm sure we will get a bit more experience after ApacheSSL is available for
  3983. SSLeay 0.8.8.
  3984. I hope you enjoyed reading and that in future questions on this topic will
  3985. rarely appear on ssl-users@moncom.com ;-)
  3986. Ilmenau, 9th of June 1997
  3987. Holger Reif <reif@prakinf.tu-ilmenau.de>
  3988. --
  3989. read you later - Holger Reif
  3990. ---------------------------------------- Signaturprojekt Deutsche Einheit
  3991. TU Ilmenau - Informatik - Telematik (Verdamp lang her)
  3992. Holger.Reif@PrakInf.TU-Ilmenau.DE Alt wie ein Baum werden, um ueber
  3993. http://Remus.PrakInf.TU-Ilmenau.DE/Reif/ alle 7 Bruecken gehen zu koennen
  3994. ==== ns-ca.doc ========================================================
  3995. The following documentation was supplied by Jeff Barber, who provided the
  3996. patch to the CA program to add this functionality.
  3997. eric
  3998. --
  3999. Jeff Barber Email: jeffb@issl.atl.hp.com
  4000. Hewlett Packard Phone: (404) 648-9503
  4001. Internet and System Security Lab Fax: (404) 648-9516
  4002. oo
  4003. ---------------------cut /\ here for ns-ca.doc ------------------------------
  4004. This document briefly describes how to use SSLeay to implement a
  4005. certificate authority capable of dynamically serving up client
  4006. certificates for version 3.0 beta 5 (and presumably later) versions of
  4007. the Netscape Navigator. Before describing how this is done, it's
  4008. important to understand a little about how the browser implements its
  4009. client certificate support. This is documented in some detail in the
  4010. URLs based at <URL:http://home.netscape.com/eng/security/certs.html>.
  4011. Here's a brief overview:
  4012. - The Navigator supports a new HTML tag "KEYGEN" which will cause
  4013. the browser to generate an RSA key pair when you submit a form
  4014. containing the tag. The public key, along with an optional
  4015. challenge (supposedly provided for use in certificate revocation
  4016. but I don't use it) is signed, DER-encoded, base-64 encoded
  4017. and sent to the web server as the value of the variable
  4018. whose NAME is provided in the KEYGEN tag. The private key is
  4019. stored by the browser in a local key database.
  4020. This "Signed Public Key And Challenge" (SPKAC) arrives formatted
  4021. into 64 character lines (which are of course URL-encoded when
  4022. sent via HTTP -- i.e. spaces, newlines and most punctuatation are
  4023. encoded as "%HH" where HH is the hex equivalent of the ASCII code).
  4024. Note that the SPKAC does not contain the other usual attributes
  4025. of a certificate request, especially the subject name fields.
  4026. These must be otherwise encoded in the form for submission along
  4027. with the SPKAC.
  4028. - Either immediately (in response to this form submission), or at
  4029. some later date (a real CA will probably verify your identity in
  4030. some way before issuing the certificate), a web server can send a
  4031. certificate based on the public key and other attributes back to
  4032. the browser by encoding it in DER (the binary form) and sending it
  4033. to the browser as MIME type:
  4034. "Content-type: application/x-x509-user-cert"
  4035. The browser uses the public key encoded in the certificate to
  4036. associate the certificate with the appropriate private key in
  4037. its local key database. Now, the certificate is "installed".
  4038. - When a server wants to require authentication based on client
  4039. certificates, it uses the right signals via the SSL protocol to
  4040. trigger the Navigator to ask you which certificate you want to
  4041. send. Whether the certificate is accepted is dependent on CA
  4042. certificates and so forth installed in the server and is beyond
  4043. the scope of this document.
  4044. Now, here's how the SSLeay package can be used to provide client
  4045. certficates:
  4046. - You prepare a file for input to the SSLeay ca application.
  4047. The file contains a number of "name = value" pairs that identify
  4048. the subject. The names here are the same subject name component
  4049. identifiers used in the CA section of the lib/ssleay.conf file,
  4050. such as "emailAddress", "commonName" "organizationName" and so
  4051. forth. Both the long version and the short version (e.g. "Email",
  4052. "CN", "O") can be used.
  4053. One more name is supported: this one is "SPKAC". Its value
  4054. is simply the value of the base-64 encoded SPKAC sent by the
  4055. browser (with all the newlines and other space charaters
  4056. removed -- and newline escapes are NOT supported).
  4057. [ As of SSLeay 0.6.4, multiple lines are supported.
  4058. Put a \ at the end of each line and it will be joined with the
  4059. previous line with the '\n' removed - eay ]
  4060. Here's a sample input file:
  4061. C = US
  4062. SP = Georgia
  4063. O = Some Organization, Inc.
  4064. OU = Netscape Compatibility Group
  4065. CN = John X. Doe
  4066. Email = jxdoe@someorg.com
  4067. SPKAC = MIG0MGAwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAwmk6FMJ4uAVIYbcvIOx5+bDGTfvL8X5gE+R67ccMk6rCSGbVQz2cetyQtnI+VIs0NwdD6wjuSuVtVFbLoHonowIDAQABFgAwDQYJKoZIhvcNAQEEBQADQQBFZDUWFl6BJdomtN1Bi53mwijy1rRgJ4YirF15yBEDM3DjAQkKXHYOIX+qpz4KXKnl6EYxTnGSFL5wWt8X2iyx
  4068. - You execute the ca command (either from a CGI program run out of
  4069. the web server, or as a later manual task) giving it the above
  4070. file as input. For example, if the file were named /tmp/cert.req,
  4071. you'd run:
  4072. $SSLDIR/bin/ca -spkac /tmp/cert.req -out /tmp/cert
  4073. The output is in DER format (binary) if a -out argument is
  4074. provided, as above; otherwise, it's in the PEM format (base-64
  4075. encoded DER). Also, the "-batch" switch is implied by the
  4076. "-spkac" so you don't get asked whether to complete the signing
  4077. (probably it shouldn't work this way but I was only interested
  4078. in hacking together an online CA that could be used for issuing
  4079. test certificates).
  4080. The "-spkac" capability doesn't support multiple files (I think).
  4081. Any CHALLENGE provided in the SPKAC is simply ignored.
  4082. The interactions between the identification fields you provide
  4083. and those identified in your lib/ssleay.conf are the same as if
  4084. you did an ordinary "ca -in infile -out outfile" -- that is, if
  4085. something is marked as required in the ssleay.conf file and it
  4086. isn't found in the -spkac file, the certificate won't be issued.
  4087. - Now, you pick up the output from /tmp/cert and pass it back to
  4088. the Navigator prepending the Content-type string described earlier.
  4089. - In order to run the ca command out of a CGI program, you must
  4090. provide a password to decrypt the CA's private key. You can
  4091. do this by using "echo MyKeyPassword | $SSLDIR/bin/ca ..."
  4092. I think there's a way to not encrypt the key file in the first
  4093. place, but I didn't see how to do that, so I made a small change
  4094. to the library that allows the password to be accepted from a pipe.
  4095. Either way is UTTERLY INSECURE and a real CA would never do that.
  4096. [ You can use the 'ssleay rsa' command to remove the password
  4097. from the private key, or you can use the '-key' option to the
  4098. ca command to specify the decryption key on the command line
  4099. or use the -nodes option when generating the key.
  4100. ca will try to clear the command line version of the password
  4101. but for quite a few operating systems, this is not possible.
  4102. - eric ]
  4103. So, what do you have to do to make use of this stuff to create an online
  4104. demo CA capability with SSLeay?
  4105. 1 Create an HTML form for your users. The form should contain
  4106. fields for all of the required or optional fields in ssleay.conf.
  4107. The form must contain a KEYGEN tag somewhere with at least a NAME
  4108. attribute.
  4109. 2 Create a CGI program to process the form input submitted by the
  4110. browser. The CGI program must URL-decode the variables and create
  4111. the file described above, containing subject identification info
  4112. as well as the SPKAC block. It should then run the the ca program
  4113. with the -spkac option. If it works (check the exit status),
  4114. return the new certificate with the appropriate MIME type. If not,
  4115. return the output of the ca command with MIME type "text/plain".
  4116. 3 Set up your web server to accept connections signed by your demo
  4117. CA. This probably involves obtaining the PEM-encoded CA certificate
  4118. (ordinarily in $SSLDIR/CA/cacert.pem) and installing it into a
  4119. server database. See your server manual for instructions.
  4120. ==== obj.doc ========================================================
  4121. The Object library.
  4122. As part of my Crypto library, I found I required a method of identifying various
  4123. objects. These objects normally had 3 different values associated with
  4124. them, a short text name, a long (or lower case) text name, and an
  4125. ASN.1 Object Identifier (which is a sequence of numbers).
  4126. This library contains a static list of objects and functions to lookup
  4127. according to one type and to return the other types.
  4128. To use these routines, 'Object.h' needs to be included.
  4129. For each supported object, #define entries are defined as follows
  4130. #define SN_Algorithm "Algorithm"
  4131. #define LN_algorithm "algorithm"
  4132. #define NID_algorithm 38
  4133. #define OBJ_algorithm 1L,3L,14L,3L,2L
  4134. SN_ stands for short name.
  4135. LN_ stands for either long name or lowercase name.
  4136. NID_ stands for Numeric ID. I each object has a unique NID and this
  4137. should be used internally to identify objects.
  4138. OBJ_ stands for ASN.1 Object Identifier or ASN1_OBJECT as defined in the
  4139. ASN1 routines. These values are used in ASN1 encoding.
  4140. The following functions are to be used to return pointers into a static
  4141. definition of these types. What this means is "don't try to free() any
  4142. pointers returned from these functions.
  4143. ASN1_OBJECT *OBJ_nid2obj(
  4144. int n);
  4145. Return the ASN1_OBJECT that corresponds to a NID of n.
  4146. char *OBJ_nid2ln(
  4147. int n);
  4148. Return the long/lower case name of the object represented by the
  4149. NID of n.
  4150. char *OBJ_nid2sn(
  4151. int n);
  4152. Return the short name for the object represented by the NID of n.
  4153. ASN1_OBJECT *OBJ_dup(
  4154. ASN1_OBJECT *o);
  4155. Duplicate and return a new ASN1_OBJECT that is the same as the
  4156. passed parameter.
  4157. int OBJ_obj2nid(
  4158. ASN1_OBJECT *o);
  4159. Given ASN1_OBJECT o, return the NID that corresponds.
  4160. int OBJ_ln2nid(
  4161. char *s);
  4162. Given the long/lower case name 's', return the NID of the object.
  4163. int OBJ_sn2nid(
  4164. char *s);
  4165. Given the short name 's', return the NID of the object.
  4166. char *OBJ_bsearch(
  4167. char *key,
  4168. char *base,
  4169. int num,
  4170. int size,
  4171. int (*cmp)());
  4172. Since I have come across a few platforms that do not have the
  4173. bsearch() function, OBJ_bsearch is my version of that function.
  4174. Feel free to use this function, but you may as well just use the
  4175. normal system bsearch(3) if it is present. This version also
  4176. has tolerance of being passed NULL pointers.
  4177. ==== keys ===========================================================
  4178. EVP_PKEY_DSA
  4179. EVP_PKEY_DSA2
  4180. EVP_PKEY_DSA3
  4181. EVP_PKEY_DSA4
  4182. EVP_PKEY_RSA
  4183. EVP_PKEY_RSA2
  4184. valid DSA pkey types
  4185. NID_dsa
  4186. NID_dsaWithSHA
  4187. NID_dsaWithSHA1
  4188. NID_dsaWithSHA1_2
  4189. valid RSA pkey types
  4190. NID_rsaEncryption
  4191. NID_rsa
  4192. NID_dsaWithSHA NID_dsaWithSHA DSA SHA
  4193. NID_dsa NID_dsaWithSHA1 DSA SHA1
  4194. NID_md2 NID_md2WithRSAEncryption RSA-pkcs1 MD2
  4195. NID_md5 NID_md5WithRSAEncryption RSA-pkcs1 MD5
  4196. NID_mdc2 NID_mdc2WithRSA RSA-none MDC2
  4197. NID_ripemd160 NID_ripemd160WithRSA RSA-pkcs1 RIPEMD160
  4198. NID_sha NID_shaWithRSAEncryption RSA-pkcs1 SHA
  4199. NID_sha1 NID_sha1WithRSAEncryption RSA-pkcs1 SHA1
  4200. ==== rand.doc ========================================================
  4201. My Random number library.
  4202. These routines can be used to generate pseudo random numbers and can be
  4203. used to 'seed' the pseudo random number generator (RNG). The RNG make no
  4204. effort to reproduce the same random number stream with each execution.
  4205. Various other routines in the SSLeay library 'seed' the RNG when suitable
  4206. 'random' input data is available. Read the section at the end for details
  4207. on the design of the RNG.
  4208. void RAND_bytes(
  4209. unsigned char *buf,
  4210. int num);
  4211. This routine puts 'num' random bytes into 'buf'. One should make
  4212. sure RAND_seed() has been called before using this routine.
  4213. void RAND_seed(
  4214. unsigned char *buf,
  4215. int num);
  4216. This routine adds more 'seed' data the RNG state. 'num' bytes
  4217. are added to the RNG state, they are taken from 'buf'. This
  4218. routine can be called with sensitive data such as user entered
  4219. passwords. This sensitive data is in no way recoverable from
  4220. the RAND library routines or state. Try to pass as much data
  4221. from 'random' sources as possible into the RNG via this function.
  4222. Also strongly consider using the RAND_load_file() and
  4223. RAND_write_file() routines.
  4224. void RAND_cleanup();
  4225. When a program has finished with the RAND library, if it so
  4226. desires, it can 'zero' all RNG state.
  4227. The following 3 routines are convenience routines that can be used to
  4228. 'save' and 'restore' data from/to the RNG and it's state.
  4229. Since the more 'random' data that is feed as seed data the better, why not
  4230. keep it around between executions of the program? Of course the
  4231. application should pass more 'random' data in via RAND_seed() and
  4232. make sure no-one can read the 'random' data file.
  4233. char *RAND_file_name(
  4234. char *buf,
  4235. int size);
  4236. This routine returns a 'default' name for the location of a 'rand'
  4237. file. The 'rand' file should keep a sequence of random bytes used
  4238. to initialise the RNG. The filename is put in 'buf'. Buf is 'size'
  4239. bytes long. Buf is returned if things go well, if they do not,
  4240. NULL is returned. The 'rand' file name is generated in the
  4241. following way. First, if there is a 'RANDFILE' environment
  4242. variable, it is returned. Second, if there is a 'HOME' environment
  4243. variable, $HOME/.rand is returned. Third, NULL is returned. NULL
  4244. is also returned if a buf would overflow.
  4245. int RAND_load_file(
  4246. char *file,
  4247. long number);
  4248. This function 'adds' the 'file' into the RNG state. It does this by
  4249. doing a RAND_seed() on the value returned from a stat() system call
  4250. on the file and if 'number' is non-zero, upto 'number' bytes read
  4251. from the file. The number of bytes passed to RAND_seed() is returned.
  4252. int RAND_write_file(
  4253. char *file),
  4254. RAND_write_file() writes N random bytes to the file 'file', where
  4255. N is the size of the internal RND state (currently 1k).
  4256. This is a suitable method of saving RNG state for reloading via
  4257. RAND_load_file().
  4258. What follows is a description of this RNG and a description of the rational
  4259. behind it's design.
  4260. It should be noted that this RNG is intended to be used to generate
  4261. 'random' keys for various ciphers including generation of DH and RSA keys.
  4262. It should also be noted that I have just created a system that I am happy with.
  4263. It may be overkill but that does not worry me. I have not spent that much
  4264. time on this algorithm so if there are glaring errors, please let me know.
  4265. Speed has not been a consideration in the design of these routines.
  4266. First up I will state the things I believe I need for a good RNG.
  4267. 1) A good hashing algorithm to mix things up and to convert the RNG 'state'
  4268. to random numbers.
  4269. 2) An initial source of random 'state'.
  4270. 3) The state should be very large. If the RNG is being used to generate
  4271. 4096 bit RSA keys, 2 2048 bit random strings are required (at a minimum).
  4272. If your RNG state only has 128 bits, you are obviously limiting the
  4273. search space to 128 bits, not 2048. I'm probably getting a little
  4274. carried away on this last point but it does indicate that it may not be
  4275. a bad idea to keep quite a lot of RNG state. It should be easier to
  4276. break a cipher than guess the RNG seed data.
  4277. 4) Any RNG seed data should influence all subsequent random numbers
  4278. generated. This implies that any random seed data entered will have
  4279. an influence on all subsequent random numbers generated.
  4280. 5) When using data to seed the RNG state, the data used should not be
  4281. extractable from the RNG state. I believe this should be a
  4282. requirement because one possible source of 'secret' semi random
  4283. data would be a private key or a password. This data must
  4284. not be disclosed by either subsequent random numbers or a
  4285. 'core' dump left by a program crash.
  4286. 6) Given the same initial 'state', 2 systems should deviate in their RNG state
  4287. (and hence the random numbers generated) over time if at all possible.
  4288. 7) Given the random number output stream, it should not be possible to determine
  4289. the RNG state or the next random number.
  4290. The algorithm is as follows.
  4291. There is global state made up of a 1023 byte buffer (the 'state'), a
  4292. working message digest ('md') and a counter ('count').
  4293. Whenever seed data is added, it is inserted into the 'state' as
  4294. follows.
  4295. The input is chopped up into units of 16 bytes (or less for
  4296. the last block). Each of these blocks is run through the MD5
  4297. message digest. The data passed to the MD5 digest is the
  4298. current 'md', the same number of bytes from the 'state'
  4299. (the location determined by in incremented looping index) as
  4300. the current 'block' and the new key data 'block'. The result
  4301. of this is kept in 'md' and also xored into the 'state' at the
  4302. same locations that were used as input into the MD5.
  4303. I believe this system addresses points 1 (MD5), 3 (the 'state'),
  4304. 4 (via the 'md'), 5 (by the use of MD5 and xor).
  4305. When bytes are extracted from the RNG, the following process is used.
  4306. For each group of 8 bytes (or less), we do the following,
  4307. Input into MD5, the top 8 bytes from 'md', the byte that are
  4308. to be overwritten by the random bytes and bytes from the
  4309. 'state' (incrementing looping index). From this digest output
  4310. (which is kept in 'md'), the top (upto) 8 bytes are
  4311. returned to the caller and the bottom (upto) 8 bytes are xored
  4312. into the 'state'.
  4313. Finally, after we have finished 'generation' random bytes for the
  4314. called, 'count' (which is incremented) and 'md' are fed into MD5 and
  4315. the results are kept in 'md'.
  4316. I believe the above addressed points 1 (use of MD5), 6 (by
  4317. hashing into the 'state' the 'old' data from the caller that
  4318. is about to be overwritten) and 7 (by not using the 8 bytes
  4319. given to the caller to update the 'state', but they are used
  4320. to update 'md').
  4321. So of the points raised, only 2 is not addressed, but sources of
  4322. random data will always be a problem.
  4323. ==== rc2.doc ========================================================
  4324. The RC2 library.
  4325. RC2 is a block cipher that operates on 64bit (8 byte) quantities. It
  4326. uses variable size key, but 128bit (16 byte) key would normally be considered
  4327. good. It can be used in all the modes that DES can be used. This
  4328. library implements the ecb, cbc, cfb64, ofb64 modes.
  4329. I have implemented this library from an article posted to sci.crypt on
  4330. 11-Feb-1996. I personally don't know how far to trust the RC2 cipher.
  4331. While it is capable of having a key of any size, not much reseach has
  4332. publically been done on it at this point in time (Apr-1996)
  4333. since the cipher has only been public for a few months :-)
  4334. It is of a similar speed to DES and IDEA, so unless it is required for
  4335. meeting some standard (SSLv2, perhaps S/MIME), it would probably be advisable
  4336. to stick to IDEA, or for the paranoid, Tripple DES.
  4337. Mind you, having said all that, I should mention that I just read alot and
  4338. implement ciphers, I'm a 'babe in the woods' when it comes to evaluating
  4339. ciphers :-).
  4340. For all calls that have an 'input' and 'output' variables, they can be the
  4341. same.
  4342. This library requires the inclusion of 'rc2.h'.
  4343. All of the encryption functions take what is called an RC2_KEY as an
  4344. argument. An RC2_KEY is an expanded form of the RC2 key.
  4345. For all modes of the RC2 algorithm, the RC2_KEY used for
  4346. decryption is the same one that was used for encryption.
  4347. The define RC2_ENCRYPT is passed to specify encryption for the functions
  4348. that require an encryption/decryption flag. RC2_DECRYPT is passed to
  4349. specify decryption.
  4350. Please note that any of the encryption modes specified in my DES library
  4351. could be used with RC2. I have only implemented ecb, cbc, cfb64 and
  4352. ofb64 for the following reasons.
  4353. - ecb is the basic RC2 encryption.
  4354. - cbc is the normal 'chaining' form for block ciphers.
  4355. - cfb64 can be used to encrypt single characters, therefore input and output
  4356. do not need to be a multiple of 8.
  4357. - ofb64 is similar to cfb64 but is more like a stream cipher, not as
  4358. secure (not cipher feedback) but it does not have an encrypt/decrypt mode.
  4359. - If you want triple RC2, thats 384 bits of key and you must be totally
  4360. obsessed with security. Still, if you want it, it is simple enough to
  4361. copy the function from the DES library and change the des_encrypt to
  4362. RC2_encrypt; an exercise left for the paranoid reader :-).
  4363. The functions are as follows:
  4364. void RC2_set_key(
  4365. RC2_KEY *ks;
  4366. int len;
  4367. unsigned char *key;
  4368. int bits;
  4369. RC2_set_key converts an 'len' byte key into a RC2_KEY.
  4370. A 'ks' is an expanded form of the 'key' which is used to
  4371. perform actual encryption. It can be regenerated from the RC2 key
  4372. so it only needs to be kept when encryption or decryption is about
  4373. to occur. Don't save or pass around RC2_KEY's since they
  4374. are CPU architecture dependent, 'key's are not. RC2 is an
  4375. interesting cipher in that it can be used with a variable length
  4376. key. 'len' is the length of 'key' to be used as the key.
  4377. A 'len' of 16 is recomended. The 'bits' argument is an
  4378. interesting addition which I only found out about in Aug 96.
  4379. BSAFE uses this parameter to 'limit' the number of bits used
  4380. for the key. To use the 'key' unmodified, set bits to 1024.
  4381. This is what old versions of my RC2 library did (SSLeay 0.6.3).
  4382. RSAs BSAFE library sets this parameter to be 128 if 128 bit
  4383. keys are being used. So to be compatable with BSAFE, set it
  4384. to 128, if you don't want to reduce RC2's key length, leave it
  4385. at 1024.
  4386. void RC2_encrypt(
  4387. unsigned long *data,
  4388. RC2_KEY *key,
  4389. int encrypt);
  4390. This is the RC2 encryption function that gets called by just about
  4391. every other RC2 routine in the library. You should not use this
  4392. function except to implement 'modes' of RC2. I say this because the
  4393. functions that call this routine do the conversion from 'char *' to
  4394. long, and this needs to be done to make sure 'non-aligned' memory
  4395. access do not occur.
  4396. Data is a pointer to 2 unsigned long's and key is the
  4397. RC2_KEY to use. Encryption or decryption is indicated by 'encrypt'.
  4398. which can have the values RC2_ENCRYPT or RC2_DECRYPT.
  4399. void RC2_ecb_encrypt(
  4400. unsigned char *in,
  4401. unsigned char *out,
  4402. RC2_KEY *key,
  4403. int encrypt);
  4404. This is the basic Electronic Code Book form of RC2 (in DES this
  4405. mode is called Electronic Code Book so I'm going to use the term
  4406. for rc2 as well.
  4407. Input is encrypted into output using the key represented by
  4408. key. Depending on the encrypt, encryption or
  4409. decryption occurs. Input is 8 bytes long and output is 8 bytes.
  4410. void RC2_cbc_encrypt(
  4411. unsigned char *in,
  4412. unsigned char *out,
  4413. long length,
  4414. RC2_KEY *ks,
  4415. unsigned char *ivec,
  4416. int encrypt);
  4417. This routine implements RC2 in Cipher Block Chaining mode.
  4418. Input, which should be a multiple of 8 bytes is encrypted
  4419. (or decrypted) to output which will also be a multiple of 8 bytes.
  4420. The number of bytes is in length (and from what I've said above,
  4421. should be a multiple of 8). If length is not a multiple of 8, bad
  4422. things will probably happen. ivec is the initialisation vector.
  4423. This function updates iv after each call so that it can be passed to
  4424. the next call to RC2_cbc_encrypt().
  4425. void RC2_cfb64_encrypt(
  4426. unsigned char *in,
  4427. unsigned char *out,
  4428. long length,
  4429. RC2_KEY *schedule,
  4430. unsigned char *ivec,
  4431. int *num,
  4432. int encrypt);
  4433. This is one of the more useful functions in this RC2 library, it
  4434. implements CFB mode of RC2 with 64bit feedback.
  4435. This allows you to encrypt an arbitrary number of bytes,
  4436. you do not require 8 byte padding. Each call to this
  4437. routine will encrypt the input bytes to output and then update ivec
  4438. and num. Num contains 'how far' we are though ivec.
  4439. 'Encrypt' is used to indicate encryption or decryption.
  4440. CFB64 mode operates by using the cipher to generate a stream
  4441. of bytes which is used to encrypt the plain text.
  4442. The cipher text is then encrypted to generate the next 64 bits to
  4443. be xored (incrementally) with the next 64 bits of plain
  4444. text. As can be seen from this, to encrypt or decrypt,
  4445. the same 'cipher stream' needs to be generated but the way the next
  4446. block of data is gathered for encryption is different for
  4447. encryption and decryption.
  4448. void RC2_ofb64_encrypt(
  4449. unsigned char *in,
  4450. unsigned char *out,
  4451. long length,
  4452. RC2_KEY *schedule,
  4453. unsigned char *ivec,
  4454. int *num);
  4455. This functions implements OFB mode of RC2 with 64bit feedback.
  4456. This allows you to encrypt an arbitrary number of bytes,
  4457. you do not require 8 byte padding. Each call to this
  4458. routine will encrypt the input bytes to output and then update ivec
  4459. and num. Num contains 'how far' we are though ivec.
  4460. This is in effect a stream cipher, there is no encryption or
  4461. decryption mode.
  4462. For reading passwords, I suggest using des_read_pw_string() from my DES library.
  4463. To generate a password from a text string, I suggest using MD5 (or MD2) to
  4464. produce a 16 byte message digest that can then be passed directly to
  4465. RC2_set_key().
  4466. =====
  4467. For more information about the specific RC2 modes in this library
  4468. (ecb, cbc, cfb and ofb), read the section entitled 'Modes of DES' from the
  4469. documentation on my DES library. What is said about DES is directly
  4470. applicable for RC2.
  4471. ==== rc4.doc ========================================================
  4472. The RC4 library.
  4473. RC4 is a stream cipher that operates on a byte stream. It can be used with
  4474. any length key but I would recommend normally using 16 bytes.
  4475. This library requires the inclusion of 'rc4.h'.
  4476. The RC4 encryption function takes what is called an RC4_KEY as an argument.
  4477. The RC4_KEY is generated by the RC4_set_key function from the key bytes.
  4478. RC4, being a stream cipher, does not have an encryption or decryption mode.
  4479. It produces a stream of bytes that the input stream is xor'ed against and
  4480. so decryption is just a case of 'encrypting' again with the same key.
  4481. I have only put in one 'mode' for RC4 which is the normal one. This means
  4482. there is no initialisation vector and there is no feedback of the cipher
  4483. text into the cipher. This implies that you should not ever use the
  4484. same key twice if you can help it. If you do, you leave yourself open to
  4485. known plain text attacks; if you know the plain text and
  4486. corresponding cipher text in one message, all messages that used the same
  4487. key can have the cipher text decoded for the corresponding positions in the
  4488. cipher stream.
  4489. The main positive feature of RC4 is that it is a very fast cipher; about 4
  4490. times faster that DES. This makes it ideally suited to protocols where the
  4491. key is randomly chosen, like SSL.
  4492. The functions are as follows:
  4493. void RC4_set_key(
  4494. RC4_KEY *key;
  4495. int len;
  4496. unsigned char *data);
  4497. This function initialises the RC4_KEY structure with the key passed
  4498. in 'data', which is 'len' bytes long. The key data can be any
  4499. length but 16 bytes seems to be a good number.
  4500. void RC4(
  4501. RC4_KEY *key;
  4502. unsigned long len;
  4503. unsigned char *in;
  4504. unsigned char *out);
  4505. Do the actual RC4 encryption/decryption. Using the 'key', 'len'
  4506. bytes are transformed from 'in' to 'out'. As mentioned above,
  4507. decryption is the operation as encryption.
  4508. ==== ref.doc ========================================================
  4509. I have lots more references etc, and will update this list in the future,
  4510. 30 Aug 1996 - eay
  4511. SSL The SSL Protocol - from Netscapes.
  4512. RC4 Newsgroups: sci.crypt
  4513. From: sterndark@netcom.com (David Sterndark)
  4514. Subject: RC4 Algorithm revealed.
  4515. Message-ID: <sternCvKL4B.Hyy@netcom.com>
  4516. RC2 Newsgroups: sci.crypt
  4517. From: pgut01@cs.auckland.ac.nz (Peter Gutmann)
  4518. Subject: Specification for Ron Rivests Cipher No.2
  4519. Message-ID: <4fk39f$f70@net.auckland.ac.nz>
  4520. MD2 RFC1319 The MD2 Message-Digest Algorithm
  4521. MD5 RFC1321 The MD5 Message-Digest Algorithm
  4522. X509 Certificates
  4523. RFC1421 Privacy Enhancement for Internet Electronic Mail: Part I
  4524. RFC1422 Privacy Enhancement for Internet Electronic Mail: Part II
  4525. RFC1423 Privacy Enhancement for Internet Electronic Mail: Part III
  4526. RFC1424 Privacy Enhancement for Internet Electronic Mail: Part IV
  4527. RSA and various standard encoding
  4528. PKCS#1 RSA Encryption Standard
  4529. PKCS#5 Password-Based Encryption Standard
  4530. PKCS#7 Cryptographic Message Syntax Standard
  4531. A Layman's Guide to a Subset of ASN.1, BER, and DER
  4532. An Overview of the PKCS Standards
  4533. Some Examples of the PKCS Standards
  4534. IDEA Chapter 3 The Block Cipher IDEA
  4535. RSA, prime number generation and bignum algorithms
  4536. Introduction To Algorithms,
  4537. Thomas Cormen, Charles Leiserson, Ronald Rivest,
  4538. Section 29 Arithmetic Circuits
  4539. Section 33 Number-Theoretic Algorithms
  4540. Fast Private Key algorithm
  4541. Fast Decipherment Algorithm for RSA Public-Key Cryptosystem
  4542. J.-J. Quisquater and C. Couvreur, Electronics Letters,
  4543. 14th October 1982, Vol. 18 No. 21
  4544. Prime number generation and bignum algorithms.
  4545. PGP-2.3a
  4546. ==== rsa.doc ========================================================
  4547. The RSA encryption and utility routines.
  4548. The RSA routines are built on top of a big number library (the BN library).
  4549. There are support routines in the X509 library for loading and manipulating
  4550. the various objects in the RSA library. When errors are returned, read
  4551. about the ERR library for how to access the error codes.
  4552. All RSA encryption is done according to the PKCS-1 standard which is
  4553. compatible with PEM and RSAref. This means that any values being encrypted
  4554. must be less than the size of the modulus in bytes, minus 10, bytes long.
  4555. This library uses RAND_bytes()() for it's random data, make sure to feed
  4556. RAND_seed() with lots of interesting and varied data before using these
  4557. routines.
  4558. The RSA library has one specific data type, the RSA structure.
  4559. It is composed of 8 BIGNUM variables (see the BN library for details) and
  4560. can hold either a private RSA key or a public RSA key.
  4561. Some RSA libraries have different structures for public and private keys, I
  4562. don't. For my libraries, a public key is determined by the fact that the
  4563. RSA->d value is NULL. These routines will operate on any size RSA keys.
  4564. While I'm sure 4096 bit keys are very very secure, they take a lot longer
  4565. to process that 1024 bit keys :-).
  4566. The function in the RSA library are as follows.
  4567. RSA *RSA_new();
  4568. This function creates a new RSA object. The sub-fields of the RSA
  4569. type are also malloced so you should always use this routine to
  4570. create RSA variables.
  4571. void RSA_free(
  4572. RSA *rsa);
  4573. This function 'frees' an RSA structure. This routine should always
  4574. be used to free the RSA structure since it will also 'free' any
  4575. sub-fields of the RSA type that need freeing.
  4576. int RSA_size(
  4577. RSA *rsa);
  4578. This function returns the size of the RSA modulus in bytes. Why do
  4579. I need this you may ask, well the reason is that when you encrypt
  4580. with RSA, the output string will be the size of the RSA modulus.
  4581. So the output for the RSA_encrypt and the input for the RSA_decrypt
  4582. routines need to be RSA_size() bytes long, because this is how many
  4583. bytes are expected.
  4584. For the following 4 RSA encryption routines, it should be noted that
  4585. RSA_private_decrypt() should be used on the output from
  4586. RSA_public_encrypt() and RSA_public_decrypt() should be used on
  4587. the output from RSA_private_encrypt().
  4588. int RSA_public_encrypt(
  4589. int from_len;
  4590. unsigned char *from
  4591. unsigned char *to
  4592. RSA *rsa);
  4593. This function implements RSA public encryption, the rsa variable
  4594. should be a public key (but can be a private key). 'from_len'
  4595. bytes taken from 'from' and encrypted and put into 'to'. 'to' needs
  4596. to be at least RSA_size(rsa) bytes long. The number of bytes
  4597. written into 'to' is returned. -1 is returned on an error. The
  4598. operation performed is
  4599. to = from^rsa->e mod rsa->n.
  4600. int RSA_private_encrypt(
  4601. int from_len;
  4602. unsigned char *from
  4603. unsigned char *to
  4604. RSA *rsa);
  4605. This function implements RSA private encryption, the rsa variable
  4606. should be a private key. 'from_len' bytes taken from
  4607. 'from' and encrypted and put into 'to'. 'to' needs
  4608. to be at least RSA_size(rsa) bytes long. The number of bytes
  4609. written into 'to' is returned. -1 is returned on an error. The
  4610. operation performed is
  4611. to = from^rsa->d mod rsa->n.
  4612. int RSA_public_decrypt(
  4613. int from_len;
  4614. unsigned char *from
  4615. unsigned char *to
  4616. RSA *rsa);
  4617. This function implements RSA public decryption, the rsa variable
  4618. should be a public key (but can be a private key). 'from_len'
  4619. bytes are taken from 'from' and decrypted. The decrypted data is
  4620. put into 'to'. The number of bytes encrypted is returned. -1 is
  4621. returned to indicate an error. The operation performed is
  4622. to = from^rsa->e mod rsa->n.
  4623. int RSA_private_decrypt(
  4624. int from_len;
  4625. unsigned char *from
  4626. unsigned char *to
  4627. RSA *rsa);
  4628. This function implements RSA private decryption, the rsa variable
  4629. should be a private key. 'from_len' bytes are taken
  4630. from 'from' and decrypted. The decrypted data is
  4631. put into 'to'. The number of bytes encrypted is returned. -1 is
  4632. returned to indicate an error. The operation performed is
  4633. to = from^rsa->d mod rsa->n.
  4634. int RSA_mod_exp(
  4635. BIGNUM *n;
  4636. BIGNUM *p;
  4637. RSA *rsa);
  4638. Normally you will never use this routine.
  4639. This is really an internal function which is called by
  4640. RSA_private_encrypt() and RSA_private_decrypt(). It performs
  4641. n=n^p mod rsa->n except that it uses the 5 extra variables in the
  4642. RSA structure to make this more efficient.
  4643. RSA *RSA_generate_key(
  4644. int bits;
  4645. unsigned long e;
  4646. void (*callback)();
  4647. char *cb_arg;
  4648. This routine is used to generate RSA private keys. It takes
  4649. quite a period of time to run and should only be used to
  4650. generate initial private keys that should then be stored
  4651. for later use. The passed callback function
  4652. will be called periodically so that feedback can be given
  4653. as to how this function is progressing.
  4654. 'bits' is the length desired for the modulus, so it would be 1024
  4655. to generate a 1024 bit private key.
  4656. 'e' is the value to use for the public exponent 'e'. Traditionally
  4657. it is set to either 3 or 0x10001.
  4658. The callback function (if not NULL) is called in the following
  4659. situations.
  4660. when we have generated a suspected prime number to test,
  4661. callback(0,num1++,cb_arg). When it passes a prime number test,
  4662. callback(1,num2++,cb_arg). When it is rejected as one of
  4663. the 2 primes required due to gcd(prime,e value) != 0,
  4664. callback(2,num3++,cb_arg). When finally accepted as one
  4665. of the 2 primes, callback(3,num4++,cb_arg).
  4666. ==== rsaref.doc ========================================================
  4667. This package can be compiled to use the RSAref library.
  4668. This library is not allowed outside of the USA but inside the USA it is
  4669. claimed by RSA to be the only RSA public key library that can be used
  4670. besides BSAFE..
  4671. There are 2 files, rsaref/rsaref.c and rsaref/rsaref.h that contain the glue
  4672. code to use RSAref. These files were written by looking at the PGP
  4673. source code and seeing which routines it used to access RSAref.
  4674. I have also been sent by some-one a copy of the RSAref header file that
  4675. contains the library error codes.
  4676. [ Jun 1996 update - I have recently gotten hold of RSAref 2.0 from
  4677. South Africa and have been doing some performace tests. ]
  4678. They have now been tested against the recently announced RSAEURO
  4679. library.
  4680. There are 2 ways to use SSLeay and RSAref. First, to build so that
  4681. the programs must be linked with RSAref, add '-DRSAref' to CFLAG in the top
  4682. level makefile and -lrsaref (or where ever you are keeping RSAref) to
  4683. EX_LIBS.
  4684. To build a makefile via util/mk1mf.pl to do this, use the 'rsaref' option.
  4685. The second method is to build as per normal and link applications with
  4686. the RSAglue library. The correct library order would be
  4687. cc -o cmd cmd.o -lssl -lRSAglue -lcrypto -lrsaref -ldes
  4688. The RSAglue library is built in the rsa directory and is NOT
  4689. automatically installed.
  4690. Be warned that the RSAEURO library, that is claimed to be compatible
  4691. with RSAref contains a different value for the maximum number of bits
  4692. supported. This changes structure sizes and so if you are using
  4693. RSAEURO, change the value of RSAref_MAX_BITS in rsa/rsaref.h
  4694. ==== s_mult.doc ========================================================
  4695. s_mult is a test program I hacked up on a Sunday for testing non-blocking
  4696. IO. It has a select loop at it's centre that handles multiple readers
  4697. and writers.
  4698. Try the following command
  4699. ssleay s_mult -echo -nbio -ssl -v
  4700. echo - sends any sent text back to the sender
  4701. nbio - turns on non-blocking IO
  4702. ssl - accept SSL connections, default is normal text
  4703. v - print lots
  4704. type Q<cr> to quit
  4705. In another window, run the following
  4706. ssleay s_client -pause </etc/termcap
  4707. The pause option puts in a 1 second pause in each read(2)/write(2) call
  4708. so the other end will have read()s fail.
  4709. ==== session.doc ========================================================
  4710. I have just checked over and re-worked the session stuff.
  4711. The following brief example will ignore all setup information to do with
  4712. authentication.
  4713. Things operate as follows.
  4714. The SSL environment has a 'context', a SSL_CTX structure. This holds the
  4715. cached SSL_SESSIONS (which can be reused) and the certificate lookup
  4716. information. Each SSL structure needs to be associated with a SSL_CTX.
  4717. Normally only one SSL_CTX structure is needed per program.
  4718. SSL_CTX *SSL_CTX_new(void );
  4719. void SSL_CTX_free(SSL_CTX *);
  4720. These 2 functions create and destroy SSL_CTX structures
  4721. The SSL_CTX has a session_cache_mode which is by default,
  4722. in SSL_SESS_CACHE_SERVER mode. What this means is that the library
  4723. will automatically add new session-id's to the cache upon successful
  4724. SSL_accept() calls.
  4725. If SSL_SESS_CACHE_CLIENT is set, then client certificates are also added
  4726. to the cache.
  4727. SSL_set_session_cache_mode(ctx,mode) will set the 'mode' and
  4728. SSL_get_session_cache_mode(ctx) will get the cache 'mode'.
  4729. The modes can be
  4730. SSL_SESS_CACHE_OFF - no caching
  4731. SSL_SESS_CACHE_CLIENT - only SSL_connect()
  4732. SSL_SESS_CACHE_SERVER - only SSL_accept()
  4733. SSL_SESS_NO_CACHE_BOTH - Either SSL_accept() or SSL_connect().
  4734. If SSL_SESS_CACHE_NO_AUTO_CLEAR is set, old timed out sessions are
  4735. not automatically removed each 255, SSL_connect()s or SSL_accept()s.
  4736. By default, upon every 255 successful SSL_connect() or SSL_accept()s,
  4737. the cache is flush. Please note that this could be expensive on
  4738. a heavily loaded SSL server, in which case, turn this off and
  4739. clear the cache of old entries 'manually' (with one of the functions
  4740. listed below) every few hours. Perhaps I should up this number, it is hard
  4741. to say. Remember, the '255' new calls is just a mechanism to get called
  4742. every now and then, in theory at most 255 new session-id's will have been
  4743. added but if 100 are added every minute, you would still have
  4744. 500 in the cache before any would start being flushed (assuming a 3 minute
  4745. timeout)..
  4746. int SSL_CTX_sess_hits(SSL_CTX *ctx);
  4747. int SSL_CTX_sess_misses(SSL_CTX *ctx);
  4748. int SSL_CTX_sess_timeouts(SSL_CTX *ctx);
  4749. These 3 functions return statistics about the SSL_CTX. These 3 are the
  4750. number of session id reuses. hits is the number of reuses, misses are the
  4751. number of lookups that failed, and timeouts is the number of cached
  4752. entries ignored because they had timeouted.
  4753. ctx->new_session_cb is a function pointer to a function of type
  4754. int new_session_callback(SSL *ssl,SSL_SESSION *new);
  4755. This function, if set in the SSL_CTX structure is called whenever a new
  4756. SSL_SESSION is added to the cache. If the callback returns non-zero, it
  4757. means that the application will have to do a SSL_SESSION_free()
  4758. on the structure (this is
  4759. to do with the cache keeping the reference counts correct, without the
  4760. application needing to know about it.
  4761. The 'active' parameter is the current SSL session for which this connection
  4762. was created.
  4763. void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,int (*cb)());
  4764. to set the callback,
  4765. int (*cb)() SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)
  4766. to get the callback.
  4767. If the 'get session' callback is set, when a session id is looked up and
  4768. it is not in the session-id cache, this callback is called. The callback is
  4769. of the form
  4770. SSL_SESSION *get_session_callback(unsigned char *sess_id,int sess_id_len,
  4771. int *copy);
  4772. The get_session_callback is intended to return null if no session id is found.
  4773. The reference count on the SSL_SESSION in incremented by the SSL library,
  4774. if copy is 1. Otherwise, the reference count is not modified.
  4775. void SSL_CTX_sess_set_get_cb(ctx,cb) sets the callback and
  4776. int (*cb)()SSL_CTX_sess_get_get_cb(ctx) returns the callback.
  4777. These callbacks are basically intended to be used by processes to
  4778. send their session-id's to other processes. I currently have not implemented
  4779. non-blocking semantics for these callbacks, it is upto the application
  4780. to make the callbacks efficient if they require blocking (perhaps
  4781. by 'saving' them and then 'posting them' when control returns from
  4782. the SSL_accept().
  4783. LHASH *SSL_CTX_sessions(SSL_CTX *ctx)
  4784. This returns the session cache. The lhash strucutre can be accessed for
  4785. statistics about the cache.
  4786. void lh_stats(LHASH *lh, FILE *out);
  4787. void lh_node_stats(LHASH *lh, FILE *out);
  4788. void lh_node_usage_stats(LHASH *lh, FILE *out);
  4789. can be used to print details about it's activity and current state.
  4790. You can also delve directly into the lhash structure for 14 different
  4791. counters that are kept against the structure. When I wrote the lhash library,
  4792. I was interested in gathering statistics :-).
  4793. Have a read of doc/lhash.doc in the SSLeay distribution area for more details
  4794. on the lhash library.
  4795. Now as mentioned ealier, when a SSL is created, it needs a SSL_CTX.
  4796. SSL * SSL_new(SSL_CTX *);
  4797. This stores a session. A session is secret information shared between 2
  4798. SSL contexts. It will only be created if both ends of the connection have
  4799. authenticated their peer to their satisfaction. It basically contains
  4800. the information required to use a particular secret key cipher.
  4801. To retrieve the SSL_CTX being used by a SSL,
  4802. SSL_CTX *SSL_get_SSL_CTX(SSL *s);
  4803. Now when a SSL session is established between to programs, the 'session'
  4804. information that is cached in the SSL_CTX can me manipulated by the
  4805. following functions.
  4806. int SSL_set_session(SSL *s, SSL_SESSION *session);
  4807. This will set the SSL_SESSION to use for the next SSL_connect(). If you use
  4808. this function on an already 'open' established SSL connection, 'bad things
  4809. will happen'. This function is meaning-less when used on a ssl strucutre
  4810. that is just about to be used in a SSL_accept() call since the
  4811. SSL_accept() will either create a new session or retrieve one from the
  4812. cache.
  4813. SSL_SESSION *SSL_get_session(SSL *s);
  4814. This will return the SSL_SESSION for the current SSL, NULL if there is
  4815. no session associated with the SSL structure.
  4816. The SSL sessions are kept in the SSL_CTX in a hash table, to remove a
  4817. session
  4818. void SSL_CTX_remove_session(SSL_CTX *,SSL_SESSION *c);
  4819. and to add one
  4820. int SSL_CTX_add_session(SSL_CTX *s, SSL_SESSION *c);
  4821. SSL_CTX_add_session() returns 1 if the session was already in the cache (so it
  4822. was not added).
  4823. Whenever a new session is created via SSL_connect()/SSL_accept(),
  4824. they are automatically added to the cache, depending on the session_cache_mode
  4825. settings. SSL_set_session()
  4826. does not add it to the cache. Just call SSL_CTX_add_session() if you do want the
  4827. session added. For a 'client' this would not normally be the case.
  4828. SSL_CTX_add_session() is not normally ever used, except for doing 'evil' things
  4829. which the next 2 funtions help you do.
  4830. int i2d_SSL_SESSION(SSL_SESSION *in,unsigned char **pp);
  4831. SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a,unsigned char **pp,long length);
  4832. These 2 functions are in the standard ASN1 library form and can be used to
  4833. load and save to a byte format, the SSL_SESSION structure.
  4834. With these functions, you can save and read these structures to a files or
  4835. arbitary byte string.
  4836. The PEM_write_SSL_SESSION(fp,x) and PEM_read_SSL_SESSION(fp,x,cb) will
  4837. write to a file pointer in base64 encoding.
  4838. What you can do with this, is pass session information between separate
  4839. processes. Please note, that you will probably also need to modify the
  4840. timeout information on the SSL_SESSIONs.
  4841. long SSL_get_time(SSL_SESSION *s)
  4842. will return the 'time' that the session
  4843. was loaded. The timeout is relative to this time. This information is
  4844. saved when the SSL_SESSION is converted to binarary but it is stored
  4845. in as a unix long, which is rather OS dependant, but easy to convert back.
  4846. long SSL_set_time(SSL_SESSION *s,long t) will set the above mentioned time.
  4847. The time value is just the value returned from time(3), and should really
  4848. be defined by be to be time_t.
  4849. long SSL_get_timeout(SSL_SESSION *s);
  4850. long SSL_set_timeout(SSL_SESSION *s,long t);
  4851. These 2 retrieve and set the timeout which is just a number of secconds
  4852. from the 'SSL_get_time()' value. When this time period has elapesed,
  4853. the session will no longer be in the cache (well it will actually be removed
  4854. the next time it is attempted to be retrieved, so you could 'bump'
  4855. the timeout so it remains valid).
  4856. The 'time' and 'timeout' are set on a session when it is created, not reset
  4857. each time it is reused. If you did wish to 'bump it', just after establishing
  4858. a connection, do a
  4859. SSL_set_time(ssl,time(NULL));
  4860. You can also use
  4861. SSL_CTX_set_timeout(SSL_CTX *ctx,unsigned long t) and
  4862. SSL_CTX_get_timeout(SSL_CTX *ctx) to manipulate the default timeouts for
  4863. all SSL connections created against a SSL_CTX. If you set a timeout in
  4864. an SSL_CTX, all new SSL's created will inherit the timeout. It can be over
  4865. written by the SSL_set_timeout(SSL *s,unsigned long t) function call.
  4866. If you 'set' the timeout back to 0, the system default will be used.
  4867. SSL_SESSION *SSL_SESSION_new();
  4868. void SSL_SESSION_free(SSL_SESSION *ses);
  4869. These 2 functions are used to create and dispose of SSL_SESSION functions.
  4870. You should not ever normally need to use them unless you are using
  4871. i2d_SSL_SESSION() and/or d2i_SSL_SESSION(). If you 'load' a SSL_SESSION
  4872. via d2i_SSL_SESSION(), you will need to SSL_SESSION_free() it.
  4873. Both SSL_set_session() and SSL_CTX_add_session() will 'take copies' of the
  4874. structure (via reference counts) when it is passed to them.
  4875. SSL_CTX_flush_sessions(ctx,time);
  4876. The first function will clear all sessions from the cache, which have expired
  4877. relative to 'time' (which could just be time(NULL)).
  4878. SSL_CTX_flush_sessions(ctx,0);
  4879. This is a special case that clears everything.
  4880. As a final comment, a 'session' is not enough to establish a new
  4881. connection. If a session has timed out, a certificate and private key
  4882. need to have been associated with the SSL structure.
  4883. SSL_copy_session_id(SSL *to,SSL *from); will copy not only the session
  4884. strucutre but also the private key and certificate associated with
  4885. 'from'.
  4886. EXAMPLES.
  4887. So lets play at being a weird SSL server.
  4888. /* setup a context */
  4889. ctx=SSL_CTX_new();
  4890. /* Lets load some session from binary into the cache, why one would do
  4891. * this is not toally clear, but passing between programs does make sense
  4892. * Perhaps you are using 4096 bit keys and are happy to keep them
  4893. * valid for a week, to avoid the RSA overhead of 15 seconds, I'm not toally
  4894. * sure, perhaps this is a process called from an SSL inetd and this is being
  4895. * passed to the application. */
  4896. session=d2i_SSL_SESSION(....)
  4897. SSL_CTX_add_session(ctx,session);
  4898. /* Lets even add a session from a file */
  4899. session=PEM_read_SSL_SESSION(....)
  4900. SSL_CTX_add_session(ctx,session);
  4901. /* create a new SSL structure */
  4902. ssl=SSL_new(ctx);
  4903. /* At this point we want to be able to 'create' new session if
  4904. * required, so we need a certificate and RSAkey. */
  4905. SSL_use_RSAPrivateKey_file(ssl,...)
  4906. SSL_use_certificate_file(ssl,...)
  4907. /* Now since we are a server, it make little sence to load a session against
  4908. * the ssl strucutre since a SSL_accept() will either create a new session or
  4909. * grab an existing one from the cache. */
  4910. /* grab a socket descriptor */
  4911. fd=accept(...);
  4912. /* associated it with the ssl strucutre */
  4913. SSL_set_fd(ssl,fd);
  4914. SSL_accept(ssl); /* 'do' SSL using out cert and RSA key */
  4915. /* Lets print out the session details or lets save it to a file,
  4916. * perhaps with a secret key cipher, so that we can pass it to the FBI
  4917. * when they want to decode the session :-). While we have RSA
  4918. * this does not matter much but when I do SSLv3, this will allow a mechanism
  4919. * for the server/client to record the information needed to decode
  4920. * the traffic that went over the wire, even when using Diffie-Hellman */
  4921. PEM_write_SSL_SESSION(SSL_get_session(ssl),stdout,....)
  4922. Lets 'connect' back to the caller using the same session id.
  4923. ssl2=SSL_new(ctx);
  4924. fd2=connect(them);
  4925. SSL_set_fd(ssl2,fd2);
  4926. SSL_set_session(ssl2,SSL_get_session(ssl));
  4927. SSL_connect(ssl2);
  4928. /* what the hell, lets accept no more connections using this session */
  4929. SSL_CTX_remove_session(SSL_get_SSL_CTX(ssl),SSL_get_session(ssl));
  4930. /* we could have just as easily used ssl2 since they both are using the
  4931. * same session.
  4932. * You will note that both ssl and ssl2 are still using the session, and
  4933. * the SSL_SESSION structure will be free()ed when both ssl and ssl2
  4934. * finish using the session. Also note that you could continue to initiate
  4935. * connections using this session by doing SSL_get_session(ssl) to get the
  4936. * existing session, but SSL_accept() will not be able to find it to
  4937. * use for incoming connections.
  4938. * Of corse, the session will timeout at the far end and it will no
  4939. * longer be accepted after a while. The time and timeout are ignored except
  4940. * by SSL_accept(). */
  4941. /* Since we have had our server running for 10 weeks, and memory is getting
  4942. * short, perhaps we should clear the session cache to remove those
  4943. * 100000 session entries that have expired. Some may consider this
  4944. * a memory leak :-) */
  4945. SSL_CTX_flush_sessions(ctx,time(NULL));
  4946. /* Ok, after a bit more time we wish to flush all sessions from the cache
  4947. * so that all new connections will be authenticated and incure the
  4948. * public key operation overhead */
  4949. SSL_CTX_flush_sessions(ctx,0);
  4950. /* As a final note, to copy everything to do with a SSL, use */
  4951. SSL_copy_session_id(SSL *to,SSL *from);
  4952. /* as this also copies the certificate and RSA key so new session can
  4953. * be established using the same details */
  4954. ==== sha.doc ========================================================
  4955. The SHA (Secure Hash Algorithm) library.
  4956. SHA is a message digest algorithm that can be used to condense an arbitrary
  4957. length message down to a 20 byte hash. The functions all need to be passed
  4958. a SHA_CTX which is used to hold the SHA context during multiple SHA_Update()
  4959. function calls. The normal method of use for this library is as follows
  4960. This library contains both SHA and SHA-1 digest algorithms. SHA-1 is
  4961. an update to SHA (which should really be called SHA-0 now) which
  4962. tweaks the algorithm slightly. The SHA-1 algorithm is used by simply
  4963. using SHA1_Init(), SHA1_Update(), SHA1_Final() and SHA1() instead of the
  4964. SHA*() calls
  4965. SHA_Init(...);
  4966. SHA_Update(...);
  4967. ...
  4968. SHA_Update(...);
  4969. SHA_Final(...);
  4970. This library requires the inclusion of 'sha.h'.
  4971. The functions are as follows:
  4972. void SHA_Init(
  4973. SHA_CTX *c);
  4974. This function needs to be called to initiate a SHA_CTX structure for
  4975. use.
  4976. void SHA_Update(
  4977. SHA_CTX *c;
  4978. unsigned char *data;
  4979. unsigned long len);
  4980. This updates the message digest context being generated with 'len'
  4981. bytes from the 'data' pointer. The number of bytes can be any
  4982. length.
  4983. void SHA_Final(
  4984. unsigned char *md;
  4985. SHA_CTX *c;
  4986. This function is called when a message digest of the data digested
  4987. with SHA_Update() is wanted. The message digest is put in the 'md'
  4988. array and is SHA_DIGEST_LENGTH (20) bytes long.
  4989. unsigned char *SHA(
  4990. unsigned char *d;
  4991. unsigned long n;
  4992. unsigned char *md;
  4993. This function performs a SHA_Init(), followed by a SHA_Update()
  4994. followed by a SHA_Final() (using a local SHA_CTX).
  4995. The resulting digest is put into 'md' if it is not NULL.
  4996. Regardless of the value of 'md', the message
  4997. digest is returned from the function. If 'md' was NULL, the message
  4998. digest returned is being stored in a static structure.
  4999. ==== speed.doc ========================================================
  5000. To get an idea of the performance of this library, use
  5001. ssleay speed
  5002. perl util/sp-diff.pl file1 file2
  5003. will print out the relative differences between the 2 files which are
  5004. expected to be the output from the speed program.
  5005. The performace of the library is very dependant on the Compiler
  5006. quality and various flags used to build.
  5007. ---
  5008. These are some numbers I did comparing RSAref and SSLeay on a Pentium 100.
  5009. [ These numbers are all out of date, as of SSL - 0.6.1 the RSA
  5010. operations are about 2 times faster, so check the version number ]
  5011. RSA performance.
  5012. SSLeay 0.6.0
  5013. Pentium 100, 32meg, Windows NT Workstation 3.51
  5014. linux - gcc v 2.7.0 -O3 -fomit-frame-pointer -m486
  5015. and
  5016. Windows NT - Windows NT 3.51 - Visual C++ 4.1 - 586 code + 32bit assember
  5017. Windows 3.1 - Windows NT 3.51 - Visual C++ 1.52c - 286 code + 32bit assember
  5018. NT Dos Shell- Windows NT 3.51 - Visual C++ 1.52c - 286 code + 16bit assember
  5019. Times are how long it takes to do an RSA private key operation.
  5020. 512bits 1024bits
  5021. -------------------------------
  5022. SSLeay NT dll 0.042s 0.202s see above
  5023. SSLeay linux 0.046s 0.218s Assember inner loops (normal build)
  5024. SSLeay linux 0.067s 0.380s Pure C code with BN_LLONG defined
  5025. SSLeay W3.1 dll 0.108s 0.478s see above
  5026. SSLeay linux 0.109s 0.713s C without BN_LLONG.
  5027. RSAref2.0 linux 0.149s 0.936s
  5028. SSLeay MS-DOS 0.197s 1.049s see above
  5029. 486DX66, 32meg, Windows NT Server 3.51
  5030. 512bits 1024bits
  5031. -------------------------------
  5032. SSLeay NT dll 0.084s 0.495s <- SSLeay 0.6.3
  5033. SSLeay NT dll 0.154s 0.882s
  5034. SSLeay W3.1 dll 0.335s 1.538s
  5035. SSLeay MS-DOS 0.490s 2.790s
  5036. What I find cute is that I'm still faster than RSAref when using standard C,
  5037. without using the 'long long' data type :-), %35 faster for 512bit and we
  5038. scale up to 3.2 times faster for the 'default linux' build. I should mention
  5039. that people should 'try' to use either x86-lnx.s (elf), x86-lnxa.s or
  5040. x86-sol.s for any x86 based unix they are building on. The only problems
  5041. with be with syntax but the performance gain is quite large, especially for
  5042. servers. The code is very simple, you just need to modify the 'header'.
  5043. The message is, if you are stuck using RSAref, the RSA performance will be
  5044. bad. Considering the code was compiled for a pentium, the 486DX66 number
  5045. would indicate 'Use RSAref and turn you Pentium 100 into a 486DX66' :-).
  5046. [ As of verson 0.6.1, it would be correct to say 'turn you pentium 100
  5047. into a 486DX33' :-) ]
  5048. I won't tell people if the DLL's are using RSAref or my stuff if no-one
  5049. asks :-).
  5050. eric
  5051. PS while I know I could speed things up further, I will probably not do
  5052. so due to the effort involved. I did do some timings on the
  5053. SSLeay bignum format -> RSAref number format conversion that occurs
  5054. each time RSAref is used by SSLeay, and the numbers are trivial.
  5055. 0.00012s a call for 512bit vs 0.149s for the time spent in the function.
  5056. 0.00018s for 1024bit vs 0.938s. Insignificant.
  5057. So the 'way to go', to support faster RSA libraries, if people are keen,
  5058. is to write 'glue' code in a similar way that I do for RSAref and send it
  5059. to me :-).
  5060. My base library still has the advantage of being able to operate on
  5061. any size numbers, and is not that far from the performance from the
  5062. leaders in the field. (-%30?)
  5063. [ Well as of 0.6.1 I am now the leader in the filed on x86 (we at
  5064. least very close :-) ]
  5065. I suppose I should also mention some other numbers RSAref numbers, again
  5066. on my Pentium.
  5067. DES CBC EDE-DES MD5
  5068. RSAref linux 830k/s 302k/s 4390k/s
  5069. SSLeay linux 855k/s 319k/s 10025k/s
  5070. SSLeay NT 1158k/s 410k/s 10470k/s
  5071. SSLeay w31 378k/s 143k/s 2383k/s (fully 16bit)
  5072. Got to admit that Visual C++ 4.[01] is a damn fine compiler :-)
  5073. --
  5074. Eric Young | BOOL is tri-state according to Bill Gates.
  5075. AARNet: eay@cryptsoft.com | RTFM Win32 GetMessage().
  5076. ==== ssl-ciph.doc ========================================================
  5077. This is a quick high level summery of how things work now.
  5078. Each SSLv2 and SSLv3 cipher is composed of 4 major attributes plus a few extra
  5079. minor ones.
  5080. They are 'The key exchange algorithm', which is RSA for SSLv2 but can also
  5081. be Diffle-Hellman for SSLv3.
  5082. An 'Authenticion algorithm', which can be RSA, Diffle-Helman, DSS or
  5083. none.
  5084. The cipher
  5085. The MAC digest.
  5086. A cipher can also be an export cipher and is either an SSLv2 or a
  5087. SSLv3 ciphers.
  5088. To specify which ciphers to use, one can either specify all the ciphers,
  5089. one at a time, or use 'aliases' to specify the preference and order for
  5090. the ciphers.
  5091. There are a large number of aliases, but the most importaint are
  5092. kRSA, kDHr, kDHd and kEDH for key exchange types.
  5093. aRSA, aDSS, aNULL and aDH for authentication
  5094. DES, 3DES, RC4, RC2, IDEA and eNULL for ciphers
  5095. MD5, SHA0 and SHA1 digests
  5096. Now where this becomes interesting is that these can be put together to
  5097. specify the order and ciphers you wish to use.
  5098. To speed this up there are also aliases for certian groups of ciphers.
  5099. The main ones are
  5100. SSLv2 - all SSLv2 ciphers
  5101. SSLv3 - all SSLv3 ciphers
  5102. EXP - all export ciphers
  5103. LOW - all low strngth ciphers (no export ciphers, normally single DES)
  5104. MEDIUM - 128 bit encryption
  5105. HIGH - Triple DES
  5106. These aliases can be joined in a : separated list which specifies to
  5107. add ciphers, move them to the current location and delete them.
  5108. A simpler way to look at all of this is to use the 'ssleay ciphers -v' command.
  5109. The default library cipher spec is
  5110. !ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP
  5111. which means, first, remove from consideration any ciphers that do not
  5112. authenticate. Next up, use ciphers using RC4 and RSA. Next include the HIGH,
  5113. MEDIUM and the LOW security ciphers. Finish up by adding all the export
  5114. ciphers on the end, then 'pull' all the SSLv2 and export ciphers to
  5115. the end of the list.
  5116. The results are
  5117. $ ssleay ciphers -v '!ADH:RC4+RSA:HIGH:MEDIUM:LOW:EXP:+SSLv2:+EXP'
  5118. RC4-SHA SSLv3 Kx=RSA Au=RSA Enc=RC4(128) Mac=SHA1
  5119. RC4-MD5 SSLv3 Kx=RSA Au=RSA Enc=RC4(128) Mac=MD5
  5120. EDH-RSA-DES-CBC3-SHA SSLv3 Kx=DH Au=RSA Enc=3DES(168) Mac=SHA1
  5121. EDH-DSS-DES-CBC3-SHA SSLv3 Kx=DH Au=DSS Enc=3DES(168) Mac=SHA1
  5122. DES-CBC3-SHA SSLv3 Kx=RSA Au=RSA Enc=3DES(168) Mac=SHA1
  5123. IDEA-CBC-MD5 SSLv3 Kx=RSA Au=RSA Enc=IDEA(128) Mac=SHA1
  5124. EDH-RSA-DES-CBC-SHA SSLv3 Kx=DH Au=RSA Enc=DES(56) Mac=SHA1
  5125. EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH Au=DSS Enc=DES(56) Mac=SHA1
  5126. DES-CBC-SHA SSLv3 Kx=RSA Au=RSA Enc=DES(56) Mac=SHA1
  5127. DES-CBC3-MD5 SSLv2 Kx=RSA Au=RSA Enc=3DES(168) Mac=MD5
  5128. DES-CBC-MD5 SSLv2 Kx=RSA Au=RSA Enc=DES(56) Mac=MD5
  5129. IDEA-CBC-MD5 SSLv2 Kx=RSA Au=RSA Enc=IDEA(128) Mac=MD5
  5130. RC2-CBC-MD5 SSLv2 Kx=RSA Au=RSA Enc=RC2(128) Mac=MD5
  5131. RC4-MD5 SSLv2 Kx=RSA Au=RSA Enc=RC4(128) Mac=MD5
  5132. EXP-EDH-RSA-DES-CBC SSLv3 Kx=DH(512) Au=RSA Enc=DES(40) Mac=SHA1 export
  5133. EXP-EDH-DSS-DES-CBC-SHA SSLv3 Kx=DH(512) Au=DSS Enc=DES(40) Mac=SHA1 export
  5134. EXP-DES-CBC-SHA SSLv3 Kx=RSA(512) Au=RSA Enc=DES(40) Mac=SHA1 export
  5135. EXP-RC2-CBC-MD5 SSLv3 Kx=RSA(512) Au=RSA Enc=RC2(40) Mac=MD5 export
  5136. EXP-RC4-MD5 SSLv3 Kx=RSA(512) Au=RSA Enc=RC4(40) Mac=MD5 export
  5137. EXP-RC2-CBC-MD5 SSLv2 Kx=RSA(512) Au=RSA Enc=RC2(40) Mac=MD5 export
  5138. EXP-RC4-MD5 SSLv2 Kx=RSA(512) Au=RSA Enc=RC4(40) Mac=MD5 export
  5139. I would recoment people use the 'ssleay ciphers -v "text"'
  5140. command to check what they are going to use.
  5141. Anyway, I'm falling asleep here so I'll do some more tomorrow.
  5142. eric
  5143. ==== ssl.doc ========================================================
  5144. SSL_CTX_sessions(SSL_CTX *ctx) - the session-id hash table.
  5145. /* Session-id cache stats */
  5146. SSL_CTX_sess_number
  5147. SSL_CTX_sess_connect
  5148. SSL_CTX_sess_connect_good
  5149. SSL_CTX_sess_accept
  5150. SSL_CTX_sess_accept_good
  5151. SSL_CTX_sess_hits
  5152. SSL_CTX_sess_cb_hits
  5153. SSL_CTX_sess_misses
  5154. SSL_CTX_sess_timeouts
  5155. /* Session-id application notification callbacks */
  5156. SSL_CTX_sess_set_new_cb
  5157. SSL_CTX_sess_get_new_cb
  5158. SSL_CTX_sess_set_get_cb
  5159. SSL_CTX_sess_get_get_cb
  5160. /* Session-id cache operation mode */
  5161. SSL_CTX_set_session_cache_mode
  5162. SSL_CTX_get_session_cache_mode
  5163. /* Set default timeout values to use. */
  5164. SSL_CTX_set_timeout
  5165. SSL_CTX_get_timeout
  5166. /* Global SSL initalisation informational callback */
  5167. SSL_CTX_set_info_callback
  5168. SSL_CTX_get_info_callback
  5169. SSL_set_info_callback
  5170. SSL_get_info_callback
  5171. /* If the SSL_accept/SSL_connect returned with -1, these indicate when
  5172. * we should re-call *.
  5173. SSL_want
  5174. SSL_want_nothing
  5175. SSL_want_read
  5176. SSL_want_write
  5177. SSL_want_x509_lookup
  5178. /* Where we are in SSL initalisation, used in non-blocking, perhaps
  5179. * have a look at ssl/bio_ssl.c */
  5180. SSL_state
  5181. SSL_is_init_finished
  5182. SSL_in_init
  5183. SSL_in_connect_init
  5184. SSL_in_accept_init
  5185. /* Used to set the 'inital' state so SSL_in_connect_init and SSL_in_accept_init
  5186. * can be used to work out which function to call. */
  5187. SSL_set_connect_state
  5188. SSL_set_accept_state
  5189. /* Where to look for certificates for authentication */
  5190. SSL_set_default_verify_paths /* calles SSL_load_verify_locations */
  5191. SSL_load_verify_locations
  5192. /* get info from an established connection */
  5193. SSL_get_session
  5194. SSL_get_certificate
  5195. SSL_get_SSL_CTX
  5196. SSL_CTX_new
  5197. SSL_CTX_free
  5198. SSL_new
  5199. SSL_clear
  5200. SSL_free
  5201. SSL_CTX_set_cipher_list
  5202. SSL_get_cipher
  5203. SSL_set_cipher_list
  5204. SSL_get_cipher_list
  5205. SSL_get_shared_ciphers
  5206. SSL_accept
  5207. SSL_connect
  5208. SSL_read
  5209. SSL_write
  5210. SSL_debug
  5211. SSL_get_read_ahead
  5212. SSL_set_read_ahead
  5213. SSL_set_verify
  5214. SSL_pending
  5215. SSL_set_fd
  5216. SSL_set_rfd
  5217. SSL_set_wfd
  5218. SSL_set_bio
  5219. SSL_get_fd
  5220. SSL_get_rbio
  5221. SSL_get_wbio
  5222. SSL_use_RSAPrivateKey
  5223. SSL_use_RSAPrivateKey_ASN1
  5224. SSL_use_RSAPrivateKey_file
  5225. SSL_use_PrivateKey
  5226. SSL_use_PrivateKey_ASN1
  5227. SSL_use_PrivateKey_file
  5228. SSL_use_certificate
  5229. SSL_use_certificate_ASN1
  5230. SSL_use_certificate_file
  5231. ERR_load_SSL_strings
  5232. SSL_load_error_strings
  5233. /* human readable version of the 'state' of the SSL connection. */
  5234. SSL_state_string
  5235. SSL_state_string_long
  5236. /* These 2 report what kind of IO operation the library was trying to
  5237. * perform last. Probably not very usefull. */
  5238. SSL_rstate_string
  5239. SSL_rstate_string_long
  5240. SSL_get_peer_certificate
  5241. SSL_SESSION_new
  5242. SSL_SESSION_print_fp
  5243. SSL_SESSION_print
  5244. SSL_SESSION_free
  5245. i2d_SSL_SESSION
  5246. d2i_SSL_SESSION
  5247. SSL_get_time
  5248. SSL_set_time
  5249. SSL_get_timeout
  5250. SSL_set_timeout
  5251. SSL_copy_session_id
  5252. SSL_set_session
  5253. SSL_CTX_add_session
  5254. SSL_CTX_remove_session
  5255. SSL_CTX_flush_sessions
  5256. BIO_f_ssl
  5257. /* used to hold information as to why a certificate verification failed */
  5258. SSL_set_verify_result
  5259. SSL_get_verify_result
  5260. /* can be used by the application to associate data with an SSL structure.
  5261. * It needs to be 'free()ed' by the application */
  5262. SSL_set_app_data
  5263. SSL_get_app_data
  5264. /* The following all set values that are kept in the SSL_CTX but
  5265. * are used as the default values when an SSL session is created.
  5266. * They are over writen by the relevent SSL_xxxx functions */
  5267. /* SSL_set_verify */
  5268. void SSL_CTX_set_default_verify
  5269. /* This callback, if set, totaly overrides the normal SSLeay verification
  5270. * functions and should return 1 on success and 0 on failure */
  5271. void SSL_CTX_set_cert_verify_callback
  5272. /* The following are the same as the equivilent SSL_xxx functions.
  5273. * Only one copy of this information is kept and if a particular
  5274. * SSL structure has a local override, it is totally separate structure.
  5275. */
  5276. int SSL_CTX_use_RSAPrivateKey
  5277. int SSL_CTX_use_RSAPrivateKey_ASN1
  5278. int SSL_CTX_use_RSAPrivateKey_file
  5279. int SSL_CTX_use_PrivateKey
  5280. int SSL_CTX_use_PrivateKey_ASN1
  5281. int SSL_CTX_use_PrivateKey_file
  5282. int SSL_CTX_use_certificate
  5283. int SSL_CTX_use_certificate_ASN1
  5284. int SSL_CTX_use_certificate_file
  5285. ==== ssl_ctx.doc ========================================================
  5286. This is now a bit dated, quite a few of the SSL_ functions could be
  5287. SSL_CTX_ functions. I will update this in the future. 30 Aug 1996
  5288. From eay@orb.mincom.oz.au Mon Dec 11 21:37:08 1995
  5289. Received: by orb.mincom.oz.au id AA00696
  5290. (5.65c/IDA-1.4.4 for eay); Mon, 11 Dec 1995 11:37:08 +1000
  5291. Date: Mon, 11 Dec 1995 11:37:08 +1000 (EST)
  5292. From: Eric Young <eay@mincom.oz.au>
  5293. X-Sender: eay@orb
  5294. To: sameer <sameer@c2.org>
  5295. Cc: Eric Young <eay@mincom.oz.au>
  5296. Subject: Re: PEM_readX509 oesn't seem to be working
  5297. In-Reply-To: <199512110102.RAA12521@infinity.c2.org>
  5298. Message-Id: <Pine.SOL.3.91.951211112115.28608D-100000@orb>
  5299. Mime-Version: 1.0
  5300. Content-Type: TEXT/PLAIN; charset=US-ASCII
  5301. Status: RO
  5302. X-Status:
  5303. On Sun, 10 Dec 1995, sameer wrote:
  5304. > OK, that's solved. I've found out that it is saying "no
  5305. > certificate set" in SSL_accept because s->conn == NULL
  5306. > so there is some place I need to initialize s->conn that I am
  5307. > not initializing it.
  5308. The full order of things for a server should be.
  5309. ctx=SSL_CTX_new();
  5310. /* The next line should not really be using ctx->cert but I'll leave it
  5311. * this way right now... I don't want a X509_ routine to know about an SSL
  5312. * structure, there should be an SSL_load_verify_locations... hmm, I may
  5313. * add it tonight.
  5314. */
  5315. X509_load_verify_locations(ctx->cert,CAfile,CApath);
  5316. /* Ok now for each new connection we do the following */
  5317. con=SSL_new(ctx);
  5318. SSL_set_fd(con,s);
  5319. SSL_set_verify(con,verify,verify_callback);
  5320. /* set the certificate and private key to use. */
  5321. SSL_use_certificate_ASN1(con,X509_certificate);
  5322. SSL_use_RSAPrivateKey_ASN1(con,RSA_private_key);
  5323. SSL_accept(con);
  5324. SSL_read(con)/SSL_write(con);
  5325. There is a bit more than that but that is basically the structure.
  5326. Create a context and specify where to lookup certificates.
  5327. foreach connection
  5328. {
  5329. create a SSL structure
  5330. set the certificate and private key
  5331. do a SSL_accept
  5332. we should now be ok
  5333. }
  5334. eric
  5335. --
  5336. Eric Young | Signature removed since it was generating
  5337. AARNet: eay@mincom.oz.au | more followups than the message contents :-)
  5338. ==== ssleay.doc ========================================================
  5339. SSLeay: a cryptographic kitchen sink.
  5340. 1st December 1995
  5341. Way back at the start of April 1995, I was looking for a mindless
  5342. programming project. A friend of mine (Tim Hudson) said "why don't you do SSL,
  5343. it has DES encryption in it and I would not mind using it in a SSL telnet".
  5344. While it was true I had written a DES library in previous years, litle
  5345. did I know what an expansive task SSL would turn into.
  5346. First of all, the SSL protocol contains DES encryption. Well and good. My
  5347. DES library was fast and portable. It also contained the RSA's RC4 stream
  5348. cipher. Again, not a problem, some-one had just posted to sci.crypt
  5349. something that was claimed to be RC4. It also contained IDEA, I had the
  5350. specifications, not a problem to implement. MD5, an RFC, trivial, at most
  5351. I could spend a week or so trying to see if I could speed up the
  5352. implementation. All in all a nice set of ciphers.
  5353. Then the first 'expantion of the scope', RSA public key
  5354. encryption. Since I did not knowing a thing about public key encryption
  5355. or number theory, this appeared quite a daunting task. Just writing a
  5356. big number library would be problomatic in itself, let alone making it fast.
  5357. At this point the scope of 'implementing SSL' expands eponentialy.
  5358. First of all, the RSA private keys were being kept in ASN.1 format.
  5359. Thankfully the RSA PKCS series of documents explains this format. So I now
  5360. needed to be able to encode and decode arbitary ASN.1 objects. The Public
  5361. keys were embeded in X509 certificates. Hmm... these are not only
  5362. ASN.1 objects but they make up a heirachy of authentication. To
  5363. authenticate a X509 certificate one needs to retrieve it's issuers
  5364. certificate etc etc. Hmm..., so I also need to implement some kind
  5365. of certificate management software. I would also have to implement
  5366. software to authenticate certificates. At this point the support code made
  5367. the SSL part of my library look quite small.
  5368. Around this time, the first version of SSLeay was released.
  5369. Ah, but here was the problem, I was not happy with the code so far. As may
  5370. have become obvious, I had been treating all of this as a learning
  5371. exersize, so I have completely written the library myself. As such, due
  5372. to the way it had grown like a fungus, much of the library was not
  5373. 'elagent' or neat. There were global and static variables all over the
  5374. place, the SSL part did not even handle non-blocking IO.
  5375. The Great rewrite began.
  5376. As of this point in time, the 'Great rewrite' has almost finished. So what
  5377. follows is an approximate list of what is actually SSLeay 0.5.0
  5378. /********* This needs to be updated for 0.6.0+ *************/
  5379. ---
  5380. The library contains the following routines. Please note that most of these
  5381. functions are not specfic for SSL or any other particular cipher
  5382. implementation. I have tried to make all the routines as general purpose
  5383. as possible. So you should not think of this library as an SSL
  5384. implemtation, but rather as a library of cryptographic functions
  5385. that also contains SSL. I refer to each of these function groupings as
  5386. libraries since they are often capable of functioning as independant
  5387. libraries
  5388. First up, the general ciphers and message digests supported by the library.
  5389. MD2 rfc???, a standard 'by parts' interface to this algorithm.
  5390. MD5 rfc???, the same type of interface as for the MD2 library except a
  5391. different algorithm.
  5392. SHA THe Secure Hash Algorithm. Again the same type of interface as
  5393. MD2/MD5 except the digest is 20 bytes.
  5394. SHA1 The 'revised' version of SHA. Just about identical to SHA except
  5395. for one tweak of an inner loop.
  5396. DES This is my libdes library that has been floating around for the last
  5397. few years. It has been enhanced for no other reason than completeness.
  5398. It now supports ecb, cbc, cfb, ofb, cfb64, ofb64 in normal mode and
  5399. triple DES modes of ecb, cbc, cfb64 and ofb64. cfb64 and ofb64 are
  5400. functional interfaces to the 64 bit modes of cfb and ofb used in
  5401. such a way thay they function as single character interfaces.
  5402. RC4 The RSA Inc. stream cipher.
  5403. RC2 The RSA Inc. block cipher.
  5404. IDEA An implmentation of the IDEA cipher, the library supports ecb, cbc,
  5405. cfb64 and ofb64 modes of operation.
  5406. Now all the above mentioned ciphers and digests libraries support high
  5407. speed, minimal 'crap in the way' type interfaces. For fastest and
  5408. lowest level access, these routines should be used directly.
  5409. Now there was also the matter of public key crypto systems. These are
  5410. based on large integer arithmatic.
  5411. BN This is my large integer library. It supports all the normal
  5412. arithmentic operations. It uses malloc extensivly and as such has
  5413. no limits of the size of the numbers being manipulated. If you
  5414. wish to use 4000 bit RSA moduli, these routines will handle it.
  5415. This library also contains routines to 'generate' prime numbers and
  5416. to test for primality. The RSA and DH libraries sit on top of this
  5417. library. As of this point in time, I don't support SHA, but
  5418. when I do add it, it will just sit on top of the routines contained
  5419. in this library.
  5420. RSA This implements the RSA public key algorithm. It also contains
  5421. routines that will generate a new private/public key pair.
  5422. All the RSA functions conform to the PKCS#1 standard.
  5423. DH This is an implementation of the
  5424. Diffie-Hellman protocol. There are all the require routines for
  5425. the protocol, plus extra routines that can be used to generate a
  5426. strong prime for use with a specified generator. While this last
  5427. routine is not generally required by applications implementing DH,
  5428. It is present for completeness and because I thing it is much
  5429. better to be able to 'generate' your own 'magic' numbers as oposed
  5430. to using numbers suplied by others. I conform to the PKCS#3
  5431. standard where required.
  5432. You may have noticed the preceeding section mentions the 'generation' of
  5433. prime numbers. Now this requries the use of 'random numbers'.
  5434. RAND This psuedo-random number library is based on MD5 at it's core
  5435. and a large internal state (2k bytes). Once you have entered enough
  5436. seed data into this random number algorithm I don't feel
  5437. you will ever need to worry about it generating predictable output.
  5438. Due to the way I am writing a portable library, I have left the
  5439. issue of how to get good initial random seed data upto the
  5440. application but I do have support routines for saving and loading a
  5441. persistant random number state for use between program runs.
  5442. Now to make all these ciphers easier to use, a higher level
  5443. interface was required. In this form, the same function would be used to
  5444. encrypt 'by parts', via any one of the above mentioned ciphers.
  5445. EVP The Digital EnVeloPe library is quite large. At it's core are
  5446. function to perform encryption and decryption by parts while using
  5447. an initial parameter to specify which of the 17 different ciphers
  5448. or 4 different message digests to use. On top of these are implmented
  5449. the digital signature functions, sign, verify, seal and open.
  5450. Base64 encoding of binary data is also done in this library.
  5451. PEM rfc???? describe the format for Privacy Enhanced eMail.
  5452. As part of this standard, methods of encoding digital enveloped
  5453. data is an ascii format are defined. As such, I use a form of these
  5454. to encode enveloped data. While at this point in time full support
  5455. for PEM has not been built into the library, a minimal subset of
  5456. the secret key and Base64 encoding is present. These reoutines are
  5457. mostly used to Ascii encode binary data with a 'type' associated
  5458. with it and perhaps details of private key encryption used to
  5459. encrypt the data.
  5460. PKCS7 This is another Digital Envelope encoding standard which uses ASN.1
  5461. to encode the data. At this point in time, while there are some
  5462. routines to encode and decode this binary format, full support is
  5463. not present.
  5464. As Mentioned, above, there are several different ways to encode
  5465. data structures.
  5466. ASN1 This library is more a set of primatives used to encode the packing
  5467. and unpacking of data structures. It is used by the X509
  5468. certificate standard and by the PKCS standards which are used by
  5469. this library. It also contains routines for duplicating and signing
  5470. the structures asocisated with X509.
  5471. X509 The X509 library contains routines for packing and unpacking,
  5472. verifying and just about every thing else you would want to do with
  5473. X509 certificates.
  5474. PKCS7 PKCS-7 is a standard for encoding digital envelope data
  5475. structures. At this point in time the routines will load and save
  5476. DER forms of these structees. They need to be re-worked to support
  5477. the BER form which is the normal way PKCS-7 is encoded. If the
  5478. previous 2 sentances don't make much sense, don't worry, this
  5479. library is not used by this version of SSLeay anyway.
  5480. OBJ ASN.1 uses 'object identifiers' to identify objects. A set of
  5481. functions were requred to translate from ASN.1 to an intenger, to a
  5482. character string. This library provieds these translations
  5483. Now I mentioned an X509 library. X509 specified a hieachy of certificates
  5484. which needs to be traversed to authenticate particular certificates.
  5485. METH This library is used to push 'methods' of retrieving certificates
  5486. into the library. There are some supplied 'methods' with SSLeay
  5487. but applications can add new methods if they so desire.
  5488. This library has not been finished and is not being used in this
  5489. version.
  5490. Now all the above are required for use in the initial point of this project.
  5491. SSL The SSL protocol. This is a full implmentation of SSL v 2. It
  5492. support both server and client authentication. SSL v 3 support
  5493. will be added when the SSL v 3 specification is released in it's
  5494. final form.
  5495. Now quite a few of the above mentioned libraries rely on a few 'complex'
  5496. data structures. For each of these I have a library.
  5497. Lhash This is a hash table library which is used extensivly.
  5498. STACK An implemetation of a Stack data structure.
  5499. BUF A simple character array structure that also support a function to
  5500. check that the array is greater that a certain size, if it is not,
  5501. it is realloced so that is it.
  5502. TXT_DB A simple memory based text file data base. The application can specify
  5503. unique indexes that will be enforced at update time.
  5504. CONF Most of the programs written for this library require a configuration
  5505. file. Instead of letting programs constantly re-implment this
  5506. subsystem, the CONF library provides a consistant and flexable
  5507. interface to not only configuration files but also environment
  5508. variables.
  5509. But what about when something goes wrong?
  5510. The one advantage (and perhaps disadvantage) of all of these
  5511. functions being in one library was the ability to implement a
  5512. single error reporting system.
  5513. ERR This library is used to report errors. The error system records
  5514. library number, function number (in the library) and reason
  5515. number. Multiple errors can be reported so that an 'error' trace
  5516. is created. The errors can be printed in numeric or textual form.
  5517. ==== ssluse.doc ========================================================
  5518. We have an SSL_CTX which contains global information for lots of
  5519. SSL connections. The session-id cache and the certificate verificate cache.
  5520. It also contains default values for use when certificates are used.
  5521. SSL_CTX
  5522. default cipher list
  5523. session-id cache
  5524. certificate cache
  5525. default session-id timeout period
  5526. New session-id callback
  5527. Required session-id callback
  5528. session-id stats
  5529. Informational callback
  5530. Callback that is set, overrides the SSLeay X509 certificate
  5531. verification
  5532. The default Certificate/Private Key pair
  5533. Default read ahead mode.
  5534. Default verify mode and verify callback. These are not used
  5535. if the over ride callback mentioned above is used.
  5536. Each SSL can have the following defined for it before a connection is made.
  5537. Certificate
  5538. Private key
  5539. Ciphers to use
  5540. Certificate verify mode and callback
  5541. IO object to use in the comunication.
  5542. Some 'read-ahead' mode information.
  5543. A previous session-id to re-use.
  5544. A connection is made by using SSL_connect or SSL_accept.
  5545. When non-blocking IO is being used, there are functions that can be used
  5546. to determin where and why the SSL_connect or SSL_accept did not complete.
  5547. This information can be used to recall the functions when the 'error'
  5548. condition has dissapeared.
  5549. After the connection has been made, information can be retrived about the
  5550. SSL session and the session-id values that have been decided upon.
  5551. The 'peer' certificate can be retrieved.
  5552. The session-id values include
  5553. 'start time'
  5554. 'timeout length'
  5555. ==== stack.doc ========================================================
  5556. The stack data structure is used to store an ordered list of objects.
  5557. It is basically misnamed to call it a stack but it can function that way
  5558. and that is what I originally used it for. Due to the way element
  5559. pointers are kept in a malloc()ed array, the most efficient way to use this
  5560. structure is to add and delete elements from the end via sk_pop() and
  5561. sk_push(). If you wish to do 'lookups' sk_find() is quite efficient since
  5562. it will sort the stack (if required) and then do a binary search to lookup
  5563. the requested item. This sorting occurs automatically so just sk_push()
  5564. elements on the stack and don't worry about the order. Do remember that if
  5565. you do a sk_find(), the order of the elements will change.
  5566. You should never need to 'touch' this structure directly.
  5567. typedef struct stack_st
  5568. {
  5569. unsigned int num;
  5570. char **data;
  5571. int sorted;
  5572. unsigned int num_alloc;
  5573. int (*comp)();
  5574. } STACK;
  5575. 'num' holds the number of elements in the stack, 'data' is the array of
  5576. elements. 'sorted' is 1 is the list has been sorted, 0 if not.
  5577. num_alloc is the number of 'nodes' allocated in 'data'. When num becomes
  5578. larger than num_alloc, data is realloced to a larger size.
  5579. If 'comp' is set, it is a function that is used to compare 2 of the items
  5580. in the stack. The function should return -1, 0 or 1, depending on the
  5581. ordering.
  5582. #define sk_num(sk) ((sk)->num)
  5583. #define sk_value(sk,n) ((sk)->data[n])
  5584. These 2 macros should be used to access the number of elements in the
  5585. 'stack' and to access a pointer to one of the values.
  5586. STACK *sk_new(int (*c)());
  5587. This creates a new stack. If 'c', the comparison function, is not
  5588. specified, the various functions that operate on a sorted 'stack' will not
  5589. work (sk_find()). NULL is returned on failure.
  5590. void sk_free(STACK *);
  5591. This function free()'s a stack structure. The elements in the
  5592. stack will not be freed so one should 'pop' and free all elements from the
  5593. stack before calling this function or call sk_pop_free() instead.
  5594. void sk_pop_free(STACK *st; void (*func)());
  5595. This function calls 'func' for each element on the stack, passing
  5596. the element as the argument. sk_free() is then called to free the 'stack'
  5597. structure.
  5598. int sk_insert(STACK *sk,char *data,int where);
  5599. This function inserts 'data' into stack 'sk' at location 'where'.
  5600. If 'where' is larger that the number of elements in the stack, the element
  5601. is put at the end. This function tends to be used by other 'stack'
  5602. functions. Returns 0 on failure, otherwise the number of elements in the
  5603. new stack.
  5604. char *sk_delete(STACK *st,int loc);
  5605. Remove the item a location 'loc' from the stack and returns it.
  5606. Returns NULL if the 'loc' is out of range.
  5607. char *sk_delete_ptr(STACK *st, char *p);
  5608. If the data item pointed to by 'p' is in the stack, it is deleted
  5609. from the stack and returned. NULL is returned if the element is not in the
  5610. stack.
  5611. int sk_find(STACK *st,char *data);
  5612. Returns the location that contains a value that is equal to
  5613. the 'data' item. If the comparison function was not set, this function
  5614. does a linear search. This function actually qsort()s the stack if it is not
  5615. in order and then uses bsearch() to do the initial search. If the
  5616. search fails,, -1 is returned. For mutliple items with the same
  5617. value, the index of the first in the array is returned.
  5618. int sk_push(STACK *st,char *data);
  5619. Append 'data' to the stack. 0 is returned if there is a failure
  5620. (due to a malloc failure), else 1. This is
  5621. sk_insert(st,data,sk_num(st));
  5622. int sk_unshift(STACK *st,char *data);
  5623. Prepend 'data' to the front (location 0) of the stack. This is
  5624. sk_insert(st,data,0);
  5625. char *sk_shift(STACK *st);
  5626. Return and delete from the stack the first element in the stack.
  5627. This is sk_delete(st,0);
  5628. char *sk_pop(STACK *st);
  5629. Return and delete the last element on the stack. This is
  5630. sk_delete(st,sk_num(sk)-1);
  5631. void sk_zero(STACK *st);
  5632. Removes all items from the stack. It does not 'free'
  5633. pointers but is a quick way to clear a 'stack of references'.
  5634. ==== threads.doc ========================================================
  5635. How to compile SSLeay for multi-threading.
  5636. Well basically it is quite simple, set the compiler flags and build.
  5637. I have only really done much testing under Solaris and Windows NT.
  5638. If you library supports localtime_r() and gmtime_r() add,
  5639. -DTHREADS to the makefile parameters. You can probably survive with out
  5640. this define unless you are going to have multiple threads generating
  5641. certificates at once. It will not affect the SSL side of things.
  5642. The approach I have taken to doing locking is to make the application provide
  5643. callbacks to perform locking and so that the SSLeay library can distinguish
  5644. between threads (for the error state).
  5645. To have a look at an example program, 'cd mt; vi mttest.c'.
  5646. To build under solaris, sh solaris.sh, for Windows NT or Windows 95,
  5647. win32.bat
  5648. This will build mttest which will fire up 10 threads that talk SSL
  5649. to each other 10 times.
  5650. To enable everything to work, the application needs to call
  5651. CRYPTO_set_id_callback(id_function);
  5652. CRYPTO_set_locking_callback(locking_function);
  5653. before any multithreading is started.
  5654. id_function does not need to be defined under Windows NT or 95, the
  5655. correct function will be called if it is not. Under unix, getpid()
  5656. is call if the id_callback is not defined, for Solaris this is wrong
  5657. (since threads id's are not pid's) but under Linux it is correct
  5658. (threads are just processes sharing the data segement).
  5659. The locking_callback is used to perform locking by the SSLeay library.
  5660. eg.
  5661. void solaris_locking_callback(mode,type,file,line)
  5662. int mode;
  5663. int type;
  5664. char *file;
  5665. int line;
  5666. {
  5667. if (mode & CRYPTO_LOCK)
  5668. mutex_lock(&(lock_cs[type]));
  5669. else
  5670. mutex_unlock(&(lock_cs[type]));
  5671. }
  5672. Now in this case I have used mutexes instead of read/write locks, since they
  5673. are faster and there are not many read locks in SSLeay, you may as well
  5674. always use write locks. file and line are __FILE__ and __LINE__ from
  5675. the compile and can be usefull when debugging.
  5676. Now as you can see, 'type' can be one of a range of values, these values are
  5677. defined in crypto/crypto.h
  5678. CRYPTO_get_lock_name(type) will return a text version of what the lock is.
  5679. There are CRYPTO_NUM_LOCKS locks required, so under solaris, the setup
  5680. for multi-threading can be
  5681. static mutex_t lock_cs[CRYPTO_NUM_LOCKS];
  5682. void thread_setup()
  5683. {
  5684. int i;
  5685. for (i=0; i<CRYPTO_NUM_LOCKS; i++)
  5686. mutex_init(&(lock_cs[i]),USYNC_THREAD,NULL);
  5687. CRYPTO_set_id_callback((unsigned long (*)())solaris_thread_id);
  5688. CRYPTO_set_locking_callback((void (*)())solaris_locking_callback);
  5689. }
  5690. As a final note, under Windows NT or Windows 95, you have to be careful
  5691. not to mix the various threaded, unthreaded and debug libraries.
  5692. Normally if they are mixed incorrectly, mttest will crash just after printing
  5693. out some usage statistics at the end. This is because the
  5694. different system libraries use different malloc routines and if
  5695. data is malloc()ed inside crypt32.dll or ssl32.dll and then free()ed by a
  5696. different library malloc, things get very confused.
  5697. The default SSLeay DLL builds use /MD, so if you use this on your
  5698. application, things will work as expected. If you use /MDd,
  5699. you will probably have to rebuild SSLeay using this flag.
  5700. I should modify util/mk1mf.pl so it does all this correctly, but
  5701. this has not been done yet.
  5702. One last warning. Because locking overheads are actually quite large, the
  5703. statistics collected against the SSL_CTX for successfull connections etc
  5704. are not locked when updated. This does make it possible for these
  5705. values to be slightly lower than they should be, if you are
  5706. running multithreaded on a multi-processor box, but this does not really
  5707. matter much.
  5708. ==== txt_db.doc ========================================================
  5709. TXT_DB, a simple text based in memory database.
  5710. It holds rows of ascii data, for which the only special character is '\0'.
  5711. The rows can be of an unlimited length.
  5712. ==== why.doc ========================================================
  5713. This file is more of a note for other people who wish to understand why
  5714. the build environment is the way it is :-).
  5715. The include files 'depend' as follows.
  5716. Each of
  5717. crypto/*/*.c includes crypto/cryptlib.h
  5718. ssl/*.c include ssl/ssl_locl.h
  5719. apps/*.c include apps/apps.h
  5720. crypto/cryptlib.h, ssl/ssl_locl.h and apps/apps.h
  5721. all include e_os.h which contains OS/environment specific information.
  5722. If you need to add something todo with a particular environment,
  5723. add it to this file. It is worth remembering that quite a few libraries,
  5724. like lhash, des, md, sha etc etc do not include crypto/cryptlib.h. This
  5725. is because these libraries should be 'independantly compilable' and so I
  5726. try to keep them this way.
  5727. e_os.h is not so much a part of SSLeay, as the placing in one spot all the
  5728. evil OS dependant muck.
  5729. I wanted to automate as many things as possible. This includes
  5730. error number generation. A
  5731. make errors
  5732. will scan the source files for error codes, append them to the correct
  5733. header files, and generate the functions to print the text version
  5734. of the error numbers. So don't even think about adding error numbers by
  5735. hand, put them in the form
  5736. XXXerr(XXXX_F_XXXX,YYYY_R_YYYY);
  5737. on line and it will be automatically picked up my a make errors.
  5738. In a similar vein, programs to be added into ssleay in the apps directory
  5739. just need to have an entry added to E_EXE in makefile.ssl and
  5740. everthing will work as expected. Don't edit progs.h by hand.
  5741. make links re-generates the symbolic links that are used. The reason why
  5742. I keep everything in its own directory, and don't put all the
  5743. test programs and header files in 'test' and 'include' is because I want
  5744. to keep the 'sub-libraries' independant. I still 'pull' out
  5745. indervidual libraries for use in specific projects where the code is
  5746. required. I have used the 'lhash' library in just about every software
  5747. project I have worked on :-).
  5748. make depend generates dependancies and
  5749. make dclean removes them.
  5750. You will notice that I use perl quite a bit when I could be using 'sed'.
  5751. The reason I decided to do this was to just stick to one 'extra' program.
  5752. For Windows NT, I have perl and no sed.
  5753. The util/mk1mf.pl program can be used to generate a single makefile.
  5754. I use this because makefiles under Microsoft are horrific.
  5755. Each C compiler seems to have different linker formats, which have
  5756. to be used because the retarted C compilers explode when you do
  5757. cl -o file *.o.
  5758. Now some would argue that I should just use the single makefile. I don't
  5759. like it during develoment for 2 reasons. First, the actuall make
  5760. command takes a long time. For my current setup, if I'm in
  5761. crypto/bn and I type make, only the crypto/bn directory gets rebuilt,
  5762. which is nice when you are modifying prototypes in bn.h which
  5763. half the SSLeay depends on. The second is that to add a new souce file
  5764. I just plonk it in at the required spot in the local makefile. This
  5765. then alows me to keep things local, I don't need to modify a 'global'
  5766. tables (the make for unix, the make for NT, the make for w31...).
  5767. When I am ripping apart a library structure, it is nice to only
  5768. have to worry about one directory :-).
  5769. Having said all this, for the hell of it I put together 2 files that
  5770. #include all the souce code (generated by doing a ls */*.o after a build).
  5771. crypto.c takes only 30 seconds to build under NT and 2 minutes under linux
  5772. for my pentium100. Much faster that the normal build :-).
  5773. Again, the problem is that when using libraries, every program linked
  5774. to libcrypto.a would suddenly get 330k of library when it may only need
  5775. 1k. This technique does look like a nice way to do shared libraries though.
  5776. Oh yes, as a final note, to 'build' a distribution, I just type
  5777. make dist.
  5778. This cleans and packages everything. The directory needs to be called
  5779. SSLeay since the make does a 'cd ..' and renames and tars things up.
  5780. ==== req.1 ========================================================
  5781. The 'req' command is used to manipulate and deal with pkcs#10
  5782. certificate requests.
  5783. It's default mode of operation is to load a certificate and then
  5784. write it out again.
  5785. By default the 'req' is read from stdin in 'PEM' format.
  5786. The -inform option can be used to specify 'pem' format or 'der'
  5787. format. PEM format is the base64 encoding of the DER format.
  5788. By default 'req' then writes the request back out. -outform can be used
  5789. to indicate the desired output format, be it 'pem' or 'der'.
  5790. To specify an input file, use the '-in' option and the '-out' option
  5791. can be used to specify the output file.
  5792. If you wish to perform a command and not output the certificate
  5793. request afterwards, use the '-noout' option.
  5794. When a certificate is loaded, it can be printed in a human readable
  5795. ascii format via the '-text' option.
  5796. To check that the signature on a certificate request is correct, use
  5797. the '-verify' option to make sure that the private key contained in the
  5798. certificate request corresponds to the signature.
  5799. Besides the default mode, there is also the 'generate a certificate
  5800. request' mode. There are several flags that trigger this mode.
  5801. -new will generate a new RSA key (if required) and then prompts
  5802. the user for details for the certificate request.
  5803. -newkey has an argument that is the number of bits to make the new
  5804. key. This function also triggers '-new'.
  5805. The '-new' option can have a key to use specified instead of having to
  5806. load one, '-key' is used to specify the file containg the key.
  5807. -keyform can be used to specify the format of the key. Only
  5808. 'pem' and 'der' formats are supported, later, 'netscape' format may be added.
  5809. Finally there is the '-x509' options which makes req output a self
  5810. signed x509 certificate instead of a certificate request.
  5811. Now as you may have noticed, there are lots of default options that
  5812. cannot be specified via the command line. They are held in a 'template'
  5813. or 'configuration file'. The -config option specifies which configuration
  5814. file to use. See conf.doc for details on the syntax of this file.
  5815. The req command uses the 'req' section of the config file.
  5816. ---
  5817. # The following variables are defined. For this example I will populate
  5818. # the various values
  5819. [ req ]
  5820. default_bits = 512 # default number of bits to use.
  5821. default_keyfile = testkey.pem # Where to write the generated keyfile
  5822. # if not specified.
  5823. distinguished_name= req_dn # The section that contains the
  5824. # information about which 'object' we
  5825. # want to put in the DN.
  5826. attributes = req_attr # The objects we want for the
  5827. # attributes field.
  5828. encrypt_rsa_key = no # Should we encrypt newly generated
  5829. # keys. I strongly recommend 'yes'.
  5830. # The distinguished name section. For the following entries, the
  5831. # object names must exist in the SSLeay header file objects.h. If they
  5832. # do not, they will be silently ignored. The entries have the following
  5833. # format.
  5834. # <object_name> => string to prompt with
  5835. # <object_name>_default => default value for people
  5836. # <object_name>_value => Automatically use this value for this field.
  5837. # <object_name>_min => minimum number of characters for data (def. 0)
  5838. # <object_name>_max => maximum number of characters for data (def. inf.)
  5839. # All of these entries are optional except for the first one.
  5840. [ req_dn ]
  5841. countryName = Country Name (2 letter code)
  5842. countryName_default = AU
  5843. stateOrProvinceName = State or Province Name (full name)
  5844. stateOrProvinceName_default = Queensland
  5845. localityName = Locality Name (eg, city)
  5846. organizationName = Organization Name (eg, company)
  5847. organizationName_default = Mincom Pty Ltd
  5848. organizationalUnitName = Organizational Unit Name (eg, section)
  5849. organizationalUnitName_default = MTR
  5850. commonName = Common Name (eg, YOUR name)
  5851. commonName_max = 64
  5852. emailAddress = Email Address
  5853. emailAddress_max = 40
  5854. # The next section is the attributes section. This is exactly the
  5855. # same as for the previous section except that the resulting objects are
  5856. # put in the attributes field.
  5857. [ req_attr ]
  5858. challengePassword = A challenge password
  5859. challengePassword_min = 4
  5860. challengePassword_max = 20
  5861. unstructuredName = An optional company name
  5862. ----
  5863. Also note that the order that attributes appear in this file is the
  5864. order they will be put into the distinguished name.
  5865. Once this request has been generated, it can be sent to a CA for
  5866. certifying.
  5867. ----
  5868. A few quick examples....
  5869. To generate a new request and a new key
  5870. req -new
  5871. To generate a new request and a 1058 bit key
  5872. req -newkey 1058
  5873. To generate a new request using a pre-existing key
  5874. req -new -key key.pem
  5875. To generate a self signed x509 certificate from a certificate
  5876. request using a supplied key, and we want to see the text form of the
  5877. output certificate (which we will put in the file selfSign.pem
  5878. req -x509 -in req.pem -key key.pem -text -out selfSign.pem
  5879. Verify that the signature is correct on a certificate request.
  5880. req -verify -in req.pem
  5881. Verify that the signature was made using a specified public key.
  5882. req -verify -in req.pem -key key.pem
  5883. Print the contents of a certificate request
  5884. req -text -in req.pem
  5885. ==== danger ========================================================
  5886. If you specify a SSLv2 cipher, and the mode is SSLv23 and the server
  5887. can talk SSLv3, it will claim there is no cipher since you should be
  5888. using SSLv3.
  5889. When tracing debug stuff, remember BIO_s_socket() is different to
  5890. BIO_s_connect().
  5891. BSD/OS assember is not working