x509.js 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271
  1. /**
  2. * Javascript implementation of X.509 and related components (such as
  3. * Certification Signing Requests) of a Public Key Infrastructure.
  4. *
  5. * @author Dave Longley
  6. *
  7. * Copyright (c) 2010-2014 Digital Bazaar, Inc.
  8. *
  9. * The ASN.1 representation of an X.509v3 certificate is as follows
  10. * (see RFC 2459):
  11. *
  12. * Certificate ::= SEQUENCE {
  13. * tbsCertificate TBSCertificate,
  14. * signatureAlgorithm AlgorithmIdentifier,
  15. * signatureValue BIT STRING
  16. * }
  17. *
  18. * TBSCertificate ::= SEQUENCE {
  19. * version [0] EXPLICIT Version DEFAULT v1,
  20. * serialNumber CertificateSerialNumber,
  21. * signature AlgorithmIdentifier,
  22. * issuer Name,
  23. * validity Validity,
  24. * subject Name,
  25. * subjectPublicKeyInfo SubjectPublicKeyInfo,
  26. * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
  27. * -- If present, version shall be v2 or v3
  28. * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
  29. * -- If present, version shall be v2 or v3
  30. * extensions [3] EXPLICIT Extensions OPTIONAL
  31. * -- If present, version shall be v3
  32. * }
  33. *
  34. * Version ::= INTEGER { v1(0), v2(1), v3(2) }
  35. *
  36. * CertificateSerialNumber ::= INTEGER
  37. *
  38. * Name ::= CHOICE {
  39. * // only one possible choice for now
  40. * RDNSequence
  41. * }
  42. *
  43. * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  44. *
  45. * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue
  46. *
  47. * AttributeTypeAndValue ::= SEQUENCE {
  48. * type AttributeType,
  49. * value AttributeValue
  50. * }
  51. * AttributeType ::= OBJECT IDENTIFIER
  52. * AttributeValue ::= ANY DEFINED BY AttributeType
  53. *
  54. * Validity ::= SEQUENCE {
  55. * notBefore Time,
  56. * notAfter Time
  57. * }
  58. *
  59. * Time ::= CHOICE {
  60. * utcTime UTCTime,
  61. * generalTime GeneralizedTime
  62. * }
  63. *
  64. * UniqueIdentifier ::= BIT STRING
  65. *
  66. * SubjectPublicKeyInfo ::= SEQUENCE {
  67. * algorithm AlgorithmIdentifier,
  68. * subjectPublicKey BIT STRING
  69. * }
  70. *
  71. * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
  72. *
  73. * Extension ::= SEQUENCE {
  74. * extnID OBJECT IDENTIFIER,
  75. * critical BOOLEAN DEFAULT FALSE,
  76. * extnValue OCTET STRING
  77. * }
  78. *
  79. * The only key algorithm currently supported for PKI is RSA.
  80. *
  81. * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055.
  82. *
  83. * PKCS#10 v1.7 describes certificate signing requests:
  84. *
  85. * CertificationRequestInfo:
  86. *
  87. * CertificationRequestInfo ::= SEQUENCE {
  88. * version INTEGER { v1(0) } (v1,...),
  89. * subject Name,
  90. * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }},
  91. * attributes [0] Attributes{{ CRIAttributes }}
  92. * }
  93. *
  94. * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
  95. *
  96. * CRIAttributes ATTRIBUTE ::= {
  97. * ... -- add any locally defined attributes here -- }
  98. *
  99. * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
  100. * type ATTRIBUTE.&id({IOSet}),
  101. * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
  102. * }
  103. *
  104. * CertificationRequest ::= SEQUENCE {
  105. * certificationRequestInfo CertificationRequestInfo,
  106. * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }},
  107. * signature BIT STRING
  108. * }
  109. */
  110. var forge = require('./forge');
  111. require('./aes');
  112. require('./asn1');
  113. require('./des');
  114. require('./md');
  115. require('./mgf');
  116. require('./oids');
  117. require('./pem');
  118. require('./pss');
  119. require('./rsa');
  120. require('./util');
  121. // shortcut for asn.1 API
  122. var asn1 = forge.asn1;
  123. /* Public Key Infrastructure (PKI) implementation. */
  124. var pki = module.exports = forge.pki = forge.pki || {};
  125. var oids = pki.oids;
  126. // short name OID mappings
  127. var _shortNames = {};
  128. _shortNames['CN'] = oids['commonName'];
  129. _shortNames['commonName'] = 'CN';
  130. _shortNames['C'] = oids['countryName'];
  131. _shortNames['countryName'] = 'C';
  132. _shortNames['L'] = oids['localityName'];
  133. _shortNames['localityName'] = 'L';
  134. _shortNames['ST'] = oids['stateOrProvinceName'];
  135. _shortNames['stateOrProvinceName'] = 'ST';
  136. _shortNames['O'] = oids['organizationName'];
  137. _shortNames['organizationName'] = 'O';
  138. _shortNames['OU'] = oids['organizationalUnitName'];
  139. _shortNames['organizationalUnitName'] = 'OU';
  140. _shortNames['E'] = oids['emailAddress'];
  141. _shortNames['emailAddress'] = 'E';
  142. // validator for an SubjectPublicKeyInfo structure
  143. // Note: Currently only works with an RSA public key
  144. var publicKeyValidator = forge.pki.rsa.publicKeyValidator;
  145. // validator for an X.509v3 certificate
  146. var x509CertificateValidator = {
  147. name: 'Certificate',
  148. tagClass: asn1.Class.UNIVERSAL,
  149. type: asn1.Type.SEQUENCE,
  150. constructed: true,
  151. value: [{
  152. name: 'Certificate.TBSCertificate',
  153. tagClass: asn1.Class.UNIVERSAL,
  154. type: asn1.Type.SEQUENCE,
  155. constructed: true,
  156. captureAsn1: 'tbsCertificate',
  157. value: [{
  158. name: 'Certificate.TBSCertificate.version',
  159. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  160. type: 0,
  161. constructed: true,
  162. optional: true,
  163. value: [{
  164. name: 'Certificate.TBSCertificate.version.integer',
  165. tagClass: asn1.Class.UNIVERSAL,
  166. type: asn1.Type.INTEGER,
  167. constructed: false,
  168. capture: 'certVersion'
  169. }]
  170. }, {
  171. name: 'Certificate.TBSCertificate.serialNumber',
  172. tagClass: asn1.Class.UNIVERSAL,
  173. type: asn1.Type.INTEGER,
  174. constructed: false,
  175. capture: 'certSerialNumber'
  176. }, {
  177. name: 'Certificate.TBSCertificate.signature',
  178. tagClass: asn1.Class.UNIVERSAL,
  179. type: asn1.Type.SEQUENCE,
  180. constructed: true,
  181. value: [{
  182. name: 'Certificate.TBSCertificate.signature.algorithm',
  183. tagClass: asn1.Class.UNIVERSAL,
  184. type: asn1.Type.OID,
  185. constructed: false,
  186. capture: 'certinfoSignatureOid'
  187. }, {
  188. name: 'Certificate.TBSCertificate.signature.parameters',
  189. tagClass: asn1.Class.UNIVERSAL,
  190. optional: true,
  191. captureAsn1: 'certinfoSignatureParams'
  192. }]
  193. }, {
  194. name: 'Certificate.TBSCertificate.issuer',
  195. tagClass: asn1.Class.UNIVERSAL,
  196. type: asn1.Type.SEQUENCE,
  197. constructed: true,
  198. captureAsn1: 'certIssuer'
  199. }, {
  200. name: 'Certificate.TBSCertificate.validity',
  201. tagClass: asn1.Class.UNIVERSAL,
  202. type: asn1.Type.SEQUENCE,
  203. constructed: true,
  204. // Note: UTC and generalized times may both appear so the capture
  205. // names are based on their detected order, the names used below
  206. // are only for the common case, which validity time really means
  207. // "notBefore" and which means "notAfter" will be determined by order
  208. value: [{
  209. // notBefore (Time) (UTC time case)
  210. name: 'Certificate.TBSCertificate.validity.notBefore (utc)',
  211. tagClass: asn1.Class.UNIVERSAL,
  212. type: asn1.Type.UTCTIME,
  213. constructed: false,
  214. optional: true,
  215. capture: 'certValidity1UTCTime'
  216. }, {
  217. // notBefore (Time) (generalized time case)
  218. name: 'Certificate.TBSCertificate.validity.notBefore (generalized)',
  219. tagClass: asn1.Class.UNIVERSAL,
  220. type: asn1.Type.GENERALIZEDTIME,
  221. constructed: false,
  222. optional: true,
  223. capture: 'certValidity2GeneralizedTime'
  224. }, {
  225. // notAfter (Time) (only UTC time is supported)
  226. name: 'Certificate.TBSCertificate.validity.notAfter (utc)',
  227. tagClass: asn1.Class.UNIVERSAL,
  228. type: asn1.Type.UTCTIME,
  229. constructed: false,
  230. optional: true,
  231. capture: 'certValidity3UTCTime'
  232. }, {
  233. // notAfter (Time) (only UTC time is supported)
  234. name: 'Certificate.TBSCertificate.validity.notAfter (generalized)',
  235. tagClass: asn1.Class.UNIVERSAL,
  236. type: asn1.Type.GENERALIZEDTIME,
  237. constructed: false,
  238. optional: true,
  239. capture: 'certValidity4GeneralizedTime'
  240. }]
  241. }, {
  242. // Name (subject) (RDNSequence)
  243. name: 'Certificate.TBSCertificate.subject',
  244. tagClass: asn1.Class.UNIVERSAL,
  245. type: asn1.Type.SEQUENCE,
  246. constructed: true,
  247. captureAsn1: 'certSubject'
  248. },
  249. // SubjectPublicKeyInfo
  250. publicKeyValidator,
  251. {
  252. // issuerUniqueID (optional)
  253. name: 'Certificate.TBSCertificate.issuerUniqueID',
  254. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  255. type: 1,
  256. constructed: true,
  257. optional: true,
  258. value: [{
  259. name: 'Certificate.TBSCertificate.issuerUniqueID.id',
  260. tagClass: asn1.Class.UNIVERSAL,
  261. type: asn1.Type.BITSTRING,
  262. constructed: false,
  263. // TODO: support arbitrary bit length ids
  264. captureBitStringValue: 'certIssuerUniqueId'
  265. }]
  266. }, {
  267. // subjectUniqueID (optional)
  268. name: 'Certificate.TBSCertificate.subjectUniqueID',
  269. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  270. type: 2,
  271. constructed: true,
  272. optional: true,
  273. value: [{
  274. name: 'Certificate.TBSCertificate.subjectUniqueID.id',
  275. tagClass: asn1.Class.UNIVERSAL,
  276. type: asn1.Type.BITSTRING,
  277. constructed: false,
  278. // TODO: support arbitrary bit length ids
  279. captureBitStringValue: 'certSubjectUniqueId'
  280. }]
  281. }, {
  282. // Extensions (optional)
  283. name: 'Certificate.TBSCertificate.extensions',
  284. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  285. type: 3,
  286. constructed: true,
  287. captureAsn1: 'certExtensions',
  288. optional: true
  289. }]
  290. }, {
  291. // AlgorithmIdentifier (signature algorithm)
  292. name: 'Certificate.signatureAlgorithm',
  293. tagClass: asn1.Class.UNIVERSAL,
  294. type: asn1.Type.SEQUENCE,
  295. constructed: true,
  296. value: [{
  297. // algorithm
  298. name: 'Certificate.signatureAlgorithm.algorithm',
  299. tagClass: asn1.Class.UNIVERSAL,
  300. type: asn1.Type.OID,
  301. constructed: false,
  302. capture: 'certSignatureOid'
  303. }, {
  304. name: 'Certificate.TBSCertificate.signature.parameters',
  305. tagClass: asn1.Class.UNIVERSAL,
  306. optional: true,
  307. captureAsn1: 'certSignatureParams'
  308. }]
  309. }, {
  310. // SignatureValue
  311. name: 'Certificate.signatureValue',
  312. tagClass: asn1.Class.UNIVERSAL,
  313. type: asn1.Type.BITSTRING,
  314. constructed: false,
  315. captureBitStringValue: 'certSignature'
  316. }]
  317. };
  318. var rsassaPssParameterValidator = {
  319. name: 'rsapss',
  320. tagClass: asn1.Class.UNIVERSAL,
  321. type: asn1.Type.SEQUENCE,
  322. constructed: true,
  323. value: [{
  324. name: 'rsapss.hashAlgorithm',
  325. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  326. type: 0,
  327. constructed: true,
  328. value: [{
  329. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier',
  330. tagClass: asn1.Class.UNIVERSAL,
  331. type: asn1.Class.SEQUENCE,
  332. constructed: true,
  333. optional: true,
  334. value: [{
  335. name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm',
  336. tagClass: asn1.Class.UNIVERSAL,
  337. type: asn1.Type.OID,
  338. constructed: false,
  339. capture: 'hashOid'
  340. /* parameter block omitted, for SHA1 NULL anyhow. */
  341. }]
  342. }]
  343. }, {
  344. name: 'rsapss.maskGenAlgorithm',
  345. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  346. type: 1,
  347. constructed: true,
  348. value: [{
  349. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier',
  350. tagClass: asn1.Class.UNIVERSAL,
  351. type: asn1.Class.SEQUENCE,
  352. constructed: true,
  353. optional: true,
  354. value: [{
  355. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm',
  356. tagClass: asn1.Class.UNIVERSAL,
  357. type: asn1.Type.OID,
  358. constructed: false,
  359. capture: 'maskGenOid'
  360. }, {
  361. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params',
  362. tagClass: asn1.Class.UNIVERSAL,
  363. type: asn1.Type.SEQUENCE,
  364. constructed: true,
  365. value: [{
  366. name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm',
  367. tagClass: asn1.Class.UNIVERSAL,
  368. type: asn1.Type.OID,
  369. constructed: false,
  370. capture: 'maskGenHashOid'
  371. /* parameter block omitted, for SHA1 NULL anyhow. */
  372. }]
  373. }]
  374. }]
  375. }, {
  376. name: 'rsapss.saltLength',
  377. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  378. type: 2,
  379. optional: true,
  380. value: [{
  381. name: 'rsapss.saltLength.saltLength',
  382. tagClass: asn1.Class.UNIVERSAL,
  383. type: asn1.Class.INTEGER,
  384. constructed: false,
  385. capture: 'saltLength'
  386. }]
  387. }, {
  388. name: 'rsapss.trailerField',
  389. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  390. type: 3,
  391. optional: true,
  392. value: [{
  393. name: 'rsapss.trailer.trailer',
  394. tagClass: asn1.Class.UNIVERSAL,
  395. type: asn1.Class.INTEGER,
  396. constructed: false,
  397. capture: 'trailer'
  398. }]
  399. }]
  400. };
  401. // validator for a CertificationRequestInfo structure
  402. var certificationRequestInfoValidator = {
  403. name: 'CertificationRequestInfo',
  404. tagClass: asn1.Class.UNIVERSAL,
  405. type: asn1.Type.SEQUENCE,
  406. constructed: true,
  407. captureAsn1: 'certificationRequestInfo',
  408. value: [{
  409. name: 'CertificationRequestInfo.integer',
  410. tagClass: asn1.Class.UNIVERSAL,
  411. type: asn1.Type.INTEGER,
  412. constructed: false,
  413. capture: 'certificationRequestInfoVersion'
  414. }, {
  415. // Name (subject) (RDNSequence)
  416. name: 'CertificationRequestInfo.subject',
  417. tagClass: asn1.Class.UNIVERSAL,
  418. type: asn1.Type.SEQUENCE,
  419. constructed: true,
  420. captureAsn1: 'certificationRequestInfoSubject'
  421. },
  422. // SubjectPublicKeyInfo
  423. publicKeyValidator,
  424. {
  425. name: 'CertificationRequestInfo.attributes',
  426. tagClass: asn1.Class.CONTEXT_SPECIFIC,
  427. type: 0,
  428. constructed: true,
  429. optional: true,
  430. capture: 'certificationRequestInfoAttributes',
  431. value: [{
  432. name: 'CertificationRequestInfo.attributes',
  433. tagClass: asn1.Class.UNIVERSAL,
  434. type: asn1.Type.SEQUENCE,
  435. constructed: true,
  436. value: [{
  437. name: 'CertificationRequestInfo.attributes.type',
  438. tagClass: asn1.Class.UNIVERSAL,
  439. type: asn1.Type.OID,
  440. constructed: false
  441. }, {
  442. name: 'CertificationRequestInfo.attributes.value',
  443. tagClass: asn1.Class.UNIVERSAL,
  444. type: asn1.Type.SET,
  445. constructed: true
  446. }]
  447. }]
  448. }]
  449. };
  450. // validator for a CertificationRequest structure
  451. var certificationRequestValidator = {
  452. name: 'CertificationRequest',
  453. tagClass: asn1.Class.UNIVERSAL,
  454. type: asn1.Type.SEQUENCE,
  455. constructed: true,
  456. captureAsn1: 'csr',
  457. value: [
  458. certificationRequestInfoValidator, {
  459. // AlgorithmIdentifier (signature algorithm)
  460. name: 'CertificationRequest.signatureAlgorithm',
  461. tagClass: asn1.Class.UNIVERSAL,
  462. type: asn1.Type.SEQUENCE,
  463. constructed: true,
  464. value: [{
  465. // algorithm
  466. name: 'CertificationRequest.signatureAlgorithm.algorithm',
  467. tagClass: asn1.Class.UNIVERSAL,
  468. type: asn1.Type.OID,
  469. constructed: false,
  470. capture: 'csrSignatureOid'
  471. }, {
  472. name: 'CertificationRequest.signatureAlgorithm.parameters',
  473. tagClass: asn1.Class.UNIVERSAL,
  474. optional: true,
  475. captureAsn1: 'csrSignatureParams'
  476. }]
  477. }, {
  478. // signature
  479. name: 'CertificationRequest.signature',
  480. tagClass: asn1.Class.UNIVERSAL,
  481. type: asn1.Type.BITSTRING,
  482. constructed: false,
  483. captureBitStringValue: 'csrSignature'
  484. }]
  485. };
  486. /**
  487. * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName
  488. * sets into an array with objects that have type and value properties.
  489. *
  490. * @param rdn the RDNSequence to convert.
  491. * @param md a message digest to append type and value to if provided.
  492. */
  493. pki.RDNAttributesAsArray = function(rdn, md) {
  494. var rval = [];
  495. // each value in 'rdn' in is a SET of RelativeDistinguishedName
  496. var set, attr, obj;
  497. for(var si = 0; si < rdn.value.length; ++si) {
  498. // get the RelativeDistinguishedName set
  499. set = rdn.value[si];
  500. // each value in the SET is an AttributeTypeAndValue sequence
  501. // containing first a type (an OID) and second a value (defined by
  502. // the OID)
  503. for(var i = 0; i < set.value.length; ++i) {
  504. obj = {};
  505. attr = set.value[i];
  506. obj.type = asn1.derToOid(attr.value[0].value);
  507. obj.value = attr.value[1].value;
  508. obj.valueTagClass = attr.value[1].type;
  509. // if the OID is known, get its name and short name
  510. if(obj.type in oids) {
  511. obj.name = oids[obj.type];
  512. if(obj.name in _shortNames) {
  513. obj.shortName = _shortNames[obj.name];
  514. }
  515. }
  516. if(md) {
  517. md.update(obj.type);
  518. md.update(obj.value);
  519. }
  520. rval.push(obj);
  521. }
  522. }
  523. return rval;
  524. };
  525. /**
  526. * Converts ASN.1 CRIAttributes into an array with objects that have type and
  527. * value properties.
  528. *
  529. * @param attributes the CRIAttributes to convert.
  530. */
  531. pki.CRIAttributesAsArray = function(attributes) {
  532. var rval = [];
  533. // each value in 'attributes' in is a SEQUENCE with an OID and a SET
  534. for(var si = 0; si < attributes.length; ++si) {
  535. // get the attribute sequence
  536. var seq = attributes[si];
  537. // each value in the SEQUENCE containing first a type (an OID) and
  538. // second a set of values (defined by the OID)
  539. var type = asn1.derToOid(seq.value[0].value);
  540. var values = seq.value[1].value;
  541. for(var vi = 0; vi < values.length; ++vi) {
  542. var obj = {};
  543. obj.type = type;
  544. obj.value = values[vi].value;
  545. obj.valueTagClass = values[vi].type;
  546. // if the OID is known, get its name and short name
  547. if(obj.type in oids) {
  548. obj.name = oids[obj.type];
  549. if(obj.name in _shortNames) {
  550. obj.shortName = _shortNames[obj.name];
  551. }
  552. }
  553. // parse extensions
  554. if(obj.type === oids.extensionRequest) {
  555. obj.extensions = [];
  556. for(var ei = 0; ei < obj.value.length; ++ei) {
  557. obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei]));
  558. }
  559. }
  560. rval.push(obj);
  561. }
  562. }
  563. return rval;
  564. };
  565. /**
  566. * Gets an issuer or subject attribute from its name, type, or short name.
  567. *
  568. * @param obj the issuer or subject object.
  569. * @param options a short name string or an object with:
  570. * shortName the short name for the attribute.
  571. * name the name for the attribute.
  572. * type the type for the attribute.
  573. *
  574. * @return the attribute.
  575. */
  576. function _getAttribute(obj, options) {
  577. if(typeof options === 'string') {
  578. options = {shortName: options};
  579. }
  580. var rval = null;
  581. var attr;
  582. for(var i = 0; rval === null && i < obj.attributes.length; ++i) {
  583. attr = obj.attributes[i];
  584. if(options.type && options.type === attr.type) {
  585. rval = attr;
  586. } else if(options.name && options.name === attr.name) {
  587. rval = attr;
  588. } else if(options.shortName && options.shortName === attr.shortName) {
  589. rval = attr;
  590. }
  591. }
  592. return rval;
  593. }
  594. /**
  595. * Converts signature parameters from ASN.1 structure.
  596. *
  597. * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had
  598. * no parameters.
  599. *
  600. * RSASSA-PSS-params ::= SEQUENCE {
  601. * hashAlgorithm [0] HashAlgorithm DEFAULT
  602. * sha1Identifier,
  603. * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT
  604. * mgf1SHA1Identifier,
  605. * saltLength [2] INTEGER DEFAULT 20,
  606. * trailerField [3] INTEGER DEFAULT 1
  607. * }
  608. *
  609. * HashAlgorithm ::= AlgorithmIdentifier
  610. *
  611. * MaskGenAlgorithm ::= AlgorithmIdentifier
  612. *
  613. * AlgorithmIdentifer ::= SEQUENCE {
  614. * algorithm OBJECT IDENTIFIER,
  615. * parameters ANY DEFINED BY algorithm OPTIONAL
  616. * }
  617. *
  618. * @param oid The OID specifying the signature algorithm
  619. * @param obj The ASN.1 structure holding the parameters
  620. * @param fillDefaults Whether to use return default values where omitted
  621. * @return signature parameter object
  622. */
  623. var _readSignatureParameters = function(oid, obj, fillDefaults) {
  624. var params = {};
  625. if(oid !== oids['RSASSA-PSS']) {
  626. return params;
  627. }
  628. if(fillDefaults) {
  629. params = {
  630. hash: {
  631. algorithmOid: oids['sha1']
  632. },
  633. mgf: {
  634. algorithmOid: oids['mgf1'],
  635. hash: {
  636. algorithmOid: oids['sha1']
  637. }
  638. },
  639. saltLength: 20
  640. };
  641. }
  642. var capture = {};
  643. var errors = [];
  644. if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) {
  645. var error = new Error('Cannot read RSASSA-PSS parameter block.');
  646. error.errors = errors;
  647. throw error;
  648. }
  649. if(capture.hashOid !== undefined) {
  650. params.hash = params.hash || {};
  651. params.hash.algorithmOid = asn1.derToOid(capture.hashOid);
  652. }
  653. if(capture.maskGenOid !== undefined) {
  654. params.mgf = params.mgf || {};
  655. params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid);
  656. params.mgf.hash = params.mgf.hash || {};
  657. params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid);
  658. }
  659. if(capture.saltLength !== undefined) {
  660. params.saltLength = capture.saltLength.charCodeAt(0);
  661. }
  662. return params;
  663. };
  664. /**
  665. * Converts an X.509 certificate from PEM format.
  666. *
  667. * Note: If the certificate is to be verified then compute hash should
  668. * be set to true. This will scan the TBSCertificate part of the ASN.1
  669. * object while it is converted so it doesn't need to be converted back
  670. * to ASN.1-DER-encoding later.
  671. *
  672. * @param pem the PEM-formatted certificate.
  673. * @param computeHash true to compute the hash for verification.
  674. * @param strict true to be strict when checking ASN.1 value lengths, false to
  675. * allow truncated values (default: true).
  676. *
  677. * @return the certificate.
  678. */
  679. pki.certificateFromPem = function(pem, computeHash, strict) {
  680. var msg = forge.pem.decode(pem)[0];
  681. if(msg.type !== 'CERTIFICATE' &&
  682. msg.type !== 'X509 CERTIFICATE' &&
  683. msg.type !== 'TRUSTED CERTIFICATE') {
  684. var error = new Error('Could not convert certificate from PEM; PEM header type ' +
  685. 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');
  686. error.headerType = msg.type;
  687. throw error;
  688. }
  689. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  690. throw new Error('Could not convert certificate from PEM; PEM is encrypted.');
  691. }
  692. // convert DER to ASN.1 object
  693. var obj = asn1.fromDer(msg.body, strict);
  694. return pki.certificateFromAsn1(obj, computeHash);
  695. };
  696. /**
  697. * Converts an X.509 certificate to PEM format.
  698. *
  699. * @param cert the certificate.
  700. * @param maxline the maximum characters per line, defaults to 64.
  701. *
  702. * @return the PEM-formatted certificate.
  703. */
  704. pki.certificateToPem = function(cert, maxline) {
  705. // convert to ASN.1, then DER, then PEM-encode
  706. var msg = {
  707. type: 'CERTIFICATE',
  708. body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes()
  709. };
  710. return forge.pem.encode(msg, {maxline: maxline});
  711. };
  712. /**
  713. * Converts an RSA public key from PEM format.
  714. *
  715. * @param pem the PEM-formatted public key.
  716. *
  717. * @return the public key.
  718. */
  719. pki.publicKeyFromPem = function(pem) {
  720. var msg = forge.pem.decode(pem)[0];
  721. if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') {
  722. var error = new Error('Could not convert public key from PEM; PEM header ' +
  723. 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');
  724. error.headerType = msg.type;
  725. throw error;
  726. }
  727. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  728. throw new Error('Could not convert public key from PEM; PEM is encrypted.');
  729. }
  730. // convert DER to ASN.1 object
  731. var obj = asn1.fromDer(msg.body);
  732. return pki.publicKeyFromAsn1(obj);
  733. };
  734. /**
  735. * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo).
  736. *
  737. * @param key the public key.
  738. * @param maxline the maximum characters per line, defaults to 64.
  739. *
  740. * @return the PEM-formatted public key.
  741. */
  742. pki.publicKeyToPem = function(key, maxline) {
  743. // convert to ASN.1, then DER, then PEM-encode
  744. var msg = {
  745. type: 'PUBLIC KEY',
  746. body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes()
  747. };
  748. return forge.pem.encode(msg, {maxline: maxline});
  749. };
  750. /**
  751. * Converts an RSA public key to PEM format (using an RSAPublicKey).
  752. *
  753. * @param key the public key.
  754. * @param maxline the maximum characters per line, defaults to 64.
  755. *
  756. * @return the PEM-formatted public key.
  757. */
  758. pki.publicKeyToRSAPublicKeyPem = function(key, maxline) {
  759. // convert to ASN.1, then DER, then PEM-encode
  760. var msg = {
  761. type: 'RSA PUBLIC KEY',
  762. body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes()
  763. };
  764. return forge.pem.encode(msg, {maxline: maxline});
  765. };
  766. /**
  767. * Gets a fingerprint for the given public key.
  768. *
  769. * @param options the options to use.
  770. * [md] the message digest object to use (defaults to forge.md.sha1).
  771. * [type] the type of fingerprint, such as 'RSAPublicKey',
  772. * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey').
  773. * [encoding] an alternative output encoding, such as 'hex'
  774. * (defaults to none, outputs a byte buffer).
  775. * [delimiter] the delimiter to use between bytes for 'hex' encoded
  776. * output, eg: ':' (defaults to none).
  777. *
  778. * @return the fingerprint as a byte buffer or other encoding based on options.
  779. */
  780. pki.getPublicKeyFingerprint = function(key, options) {
  781. options = options || {};
  782. var md = options.md || forge.md.sha1.create();
  783. var type = options.type || 'RSAPublicKey';
  784. var bytes;
  785. switch(type) {
  786. case 'RSAPublicKey':
  787. bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes();
  788. break;
  789. case 'SubjectPublicKeyInfo':
  790. bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes();
  791. break;
  792. default:
  793. throw new Error('Unknown fingerprint type "' + options.type + '".');
  794. }
  795. // hash public key bytes
  796. md.start();
  797. md.update(bytes);
  798. var digest = md.digest();
  799. if(options.encoding === 'hex') {
  800. var hex = digest.toHex();
  801. if(options.delimiter) {
  802. return hex.match(/.{2}/g).join(options.delimiter);
  803. }
  804. return hex;
  805. } else if(options.encoding === 'binary') {
  806. return digest.getBytes();
  807. } else if(options.encoding) {
  808. throw new Error('Unknown encoding "' + options.encoding + '".');
  809. }
  810. return digest;
  811. };
  812. /**
  813. * Converts a PKCS#10 certification request (CSR) from PEM format.
  814. *
  815. * Note: If the certification request is to be verified then compute hash
  816. * should be set to true. This will scan the CertificationRequestInfo part of
  817. * the ASN.1 object while it is converted so it doesn't need to be converted
  818. * back to ASN.1-DER-encoding later.
  819. *
  820. * @param pem the PEM-formatted certificate.
  821. * @param computeHash true to compute the hash for verification.
  822. * @param strict true to be strict when checking ASN.1 value lengths, false to
  823. * allow truncated values (default: true).
  824. *
  825. * @return the certification request (CSR).
  826. */
  827. pki.certificationRequestFromPem = function(pem, computeHash, strict) {
  828. var msg = forge.pem.decode(pem)[0];
  829. if(msg.type !== 'CERTIFICATE REQUEST') {
  830. var error = new Error('Could not convert certification request from PEM; ' +
  831. 'PEM header type is not "CERTIFICATE REQUEST".');
  832. error.headerType = msg.type;
  833. throw error;
  834. }
  835. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  836. throw new Error('Could not convert certification request from PEM; ' +
  837. 'PEM is encrypted.');
  838. }
  839. // convert DER to ASN.1 object
  840. var obj = asn1.fromDer(msg.body, strict);
  841. return pki.certificationRequestFromAsn1(obj, computeHash);
  842. };
  843. /**
  844. * Converts a PKCS#10 certification request (CSR) to PEM format.
  845. *
  846. * @param csr the certification request.
  847. * @param maxline the maximum characters per line, defaults to 64.
  848. *
  849. * @return the PEM-formatted certification request.
  850. */
  851. pki.certificationRequestToPem = function(csr, maxline) {
  852. // convert to ASN.1, then DER, then PEM-encode
  853. var msg = {
  854. type: 'CERTIFICATE REQUEST',
  855. body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes()
  856. };
  857. return forge.pem.encode(msg, {maxline: maxline});
  858. };
  859. /**
  860. * Creates an empty X.509v3 RSA certificate.
  861. *
  862. * @return the certificate.
  863. */
  864. pki.createCertificate = function() {
  865. var cert = {};
  866. cert.version = 0x02;
  867. cert.serialNumber = '00';
  868. cert.signatureOid = null;
  869. cert.signature = null;
  870. cert.siginfo = {};
  871. cert.siginfo.algorithmOid = null;
  872. cert.validity = {};
  873. cert.validity.notBefore = new Date();
  874. cert.validity.notAfter = new Date();
  875. cert.issuer = {};
  876. cert.issuer.getField = function(sn) {
  877. return _getAttribute(cert.issuer, sn);
  878. };
  879. cert.issuer.addField = function(attr) {
  880. _fillMissingFields([attr]);
  881. cert.issuer.attributes.push(attr);
  882. };
  883. cert.issuer.attributes = [];
  884. cert.issuer.hash = null;
  885. cert.subject = {};
  886. cert.subject.getField = function(sn) {
  887. return _getAttribute(cert.subject, sn);
  888. };
  889. cert.subject.addField = function(attr) {
  890. _fillMissingFields([attr]);
  891. cert.subject.attributes.push(attr);
  892. };
  893. cert.subject.attributes = [];
  894. cert.subject.hash = null;
  895. cert.extensions = [];
  896. cert.publicKey = null;
  897. cert.md = null;
  898. /**
  899. * Sets the subject of this certificate.
  900. *
  901. * @param attrs the array of subject attributes to use.
  902. * @param uniqueId an optional a unique ID to use.
  903. */
  904. cert.setSubject = function(attrs, uniqueId) {
  905. // set new attributes, clear hash
  906. _fillMissingFields(attrs);
  907. cert.subject.attributes = attrs;
  908. delete cert.subject.uniqueId;
  909. if(uniqueId) {
  910. // TODO: support arbitrary bit length ids
  911. cert.subject.uniqueId = uniqueId;
  912. }
  913. cert.subject.hash = null;
  914. };
  915. /**
  916. * Sets the issuer of this certificate.
  917. *
  918. * @param attrs the array of issuer attributes to use.
  919. * @param uniqueId an optional a unique ID to use.
  920. */
  921. cert.setIssuer = function(attrs, uniqueId) {
  922. // set new attributes, clear hash
  923. _fillMissingFields(attrs);
  924. cert.issuer.attributes = attrs;
  925. delete cert.issuer.uniqueId;
  926. if(uniqueId) {
  927. // TODO: support arbitrary bit length ids
  928. cert.issuer.uniqueId = uniqueId;
  929. }
  930. cert.issuer.hash = null;
  931. };
  932. /**
  933. * Sets the extensions of this certificate.
  934. *
  935. * @param exts the array of extensions to use.
  936. */
  937. cert.setExtensions = function(exts) {
  938. for(var i = 0; i < exts.length; ++i) {
  939. _fillMissingExtensionFields(exts[i], {cert: cert});
  940. }
  941. // set new extensions
  942. cert.extensions = exts;
  943. };
  944. /**
  945. * Gets an extension by its name or id.
  946. *
  947. * @param options the name to use or an object with:
  948. * name the name to use.
  949. * id the id to use.
  950. *
  951. * @return the extension or null if not found.
  952. */
  953. cert.getExtension = function(options) {
  954. if(typeof options === 'string') {
  955. options = {name: options};
  956. }
  957. var rval = null;
  958. var ext;
  959. for(var i = 0; rval === null && i < cert.extensions.length; ++i) {
  960. ext = cert.extensions[i];
  961. if(options.id && ext.id === options.id) {
  962. rval = ext;
  963. } else if(options.name && ext.name === options.name) {
  964. rval = ext;
  965. }
  966. }
  967. return rval;
  968. };
  969. /**
  970. * Signs this certificate using the given private key.
  971. *
  972. * @param key the private key to sign with.
  973. * @param md the message digest object to use (defaults to forge.md.sha1).
  974. */
  975. cert.sign = function(key, md) {
  976. // TODO: get signature OID from private key
  977. cert.md = md || forge.md.sha1.create();
  978. var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption'];
  979. if(!algorithmOid) {
  980. var error = new Error('Could not compute certificate digest. ' +
  981. 'Unknown message digest algorithm OID.');
  982. error.algorithm = cert.md.algorithm;
  983. throw error;
  984. }
  985. cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid;
  986. // get TBSCertificate, convert to DER
  987. cert.tbsCertificate = pki.getTBSCertificate(cert);
  988. var bytes = asn1.toDer(cert.tbsCertificate);
  989. // digest and sign
  990. cert.md.update(bytes.getBytes());
  991. cert.signature = key.sign(cert.md);
  992. };
  993. /**
  994. * Attempts verify the signature on the passed certificate using this
  995. * certificate's public key.
  996. *
  997. * @param child the certificate to verify.
  998. *
  999. * @return true if verified, false if not.
  1000. */
  1001. cert.verify = function(child) {
  1002. var rval = false;
  1003. if(!cert.issued(child)) {
  1004. var issuer = child.issuer;
  1005. var subject = cert.subject;
  1006. var error = new Error('The parent certificate did not issue the given child ' +
  1007. 'certificate; the child certificate\'s issuer does not match the ' +
  1008. 'parent\'s subject.');
  1009. error.expectedIssuer = issuer.attributes;
  1010. error.actualIssuer = subject.attributes;
  1011. throw error;
  1012. }
  1013. var md = child.md;
  1014. if(md === null) {
  1015. // check signature OID for supported signature types
  1016. if(child.signatureOid in oids) {
  1017. var oid = oids[child.signatureOid];
  1018. switch(oid) {
  1019. case 'sha1WithRSAEncryption':
  1020. md = forge.md.sha1.create();
  1021. break;
  1022. case 'md5WithRSAEncryption':
  1023. md = forge.md.md5.create();
  1024. break;
  1025. case 'sha256WithRSAEncryption':
  1026. md = forge.md.sha256.create();
  1027. break;
  1028. case 'sha384WithRSAEncryption':
  1029. md = forge.md.sha384.create();
  1030. break;
  1031. case 'sha512WithRSAEncryption':
  1032. md = forge.md.sha512.create();
  1033. break;
  1034. case 'RSASSA-PSS':
  1035. md = forge.md.sha256.create();
  1036. break;
  1037. }
  1038. }
  1039. if(md === null) {
  1040. var error = new Error('Could not compute certificate digest. ' +
  1041. 'Unknown signature OID.');
  1042. error.signatureOid = child.signatureOid;
  1043. throw error;
  1044. }
  1045. // produce DER formatted TBSCertificate and digest it
  1046. var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child);
  1047. var bytes = asn1.toDer(tbsCertificate);
  1048. md.update(bytes.getBytes());
  1049. }
  1050. if(md !== null) {
  1051. var scheme;
  1052. switch(child.signatureOid) {
  1053. case oids.sha1WithRSAEncryption:
  1054. scheme = undefined; /* use PKCS#1 v1.5 padding scheme */
  1055. break;
  1056. case oids['RSASSA-PSS']:
  1057. var hash, mgf;
  1058. /* initialize mgf */
  1059. hash = oids[child.signatureParameters.mgf.hash.algorithmOid];
  1060. if(hash === undefined || forge.md[hash] === undefined) {
  1061. var error = new Error('Unsupported MGF hash function.');
  1062. error.oid = child.signatureParameters.mgf.hash.algorithmOid;
  1063. error.name = hash;
  1064. throw error;
  1065. }
  1066. mgf = oids[child.signatureParameters.mgf.algorithmOid];
  1067. if(mgf === undefined || forge.mgf[mgf] === undefined) {
  1068. var error = new Error('Unsupported MGF function.');
  1069. error.oid = child.signatureParameters.mgf.algorithmOid;
  1070. error.name = mgf;
  1071. throw error;
  1072. }
  1073. mgf = forge.mgf[mgf].create(forge.md[hash].create());
  1074. /* initialize hash function */
  1075. hash = oids[child.signatureParameters.hash.algorithmOid];
  1076. if(hash === undefined || forge.md[hash] === undefined) {
  1077. throw {
  1078. message: 'Unsupported RSASSA-PSS hash function.',
  1079. oid: child.signatureParameters.hash.algorithmOid,
  1080. name: hash
  1081. };
  1082. }
  1083. scheme = forge.pss.create(forge.md[hash].create(), mgf,
  1084. child.signatureParameters.saltLength);
  1085. break;
  1086. }
  1087. // verify signature on cert using public key
  1088. rval = cert.publicKey.verify(
  1089. md.digest().getBytes(), child.signature, scheme);
  1090. }
  1091. return rval;
  1092. };
  1093. /**
  1094. * Returns true if this certificate's issuer matches the passed
  1095. * certificate's subject. Note that no signature check is performed.
  1096. *
  1097. * @param parent the certificate to check.
  1098. *
  1099. * @return true if this certificate's issuer matches the passed certificate's
  1100. * subject.
  1101. */
  1102. cert.isIssuer = function(parent) {
  1103. var rval = false;
  1104. var i = cert.issuer;
  1105. var s = parent.subject;
  1106. // compare hashes if present
  1107. if(i.hash && s.hash) {
  1108. rval = (i.hash === s.hash);
  1109. } else if(i.attributes.length === s.attributes.length) {
  1110. // all attributes are the same so issuer matches subject
  1111. rval = true;
  1112. var iattr, sattr;
  1113. for(var n = 0; rval && n < i.attributes.length; ++n) {
  1114. iattr = i.attributes[n];
  1115. sattr = s.attributes[n];
  1116. if(iattr.type !== sattr.type || iattr.value !== sattr.value) {
  1117. // attribute mismatch
  1118. rval = false;
  1119. }
  1120. }
  1121. }
  1122. return rval;
  1123. };
  1124. /**
  1125. * Returns true if this certificate's subject matches the issuer of the
  1126. * given certificate). Note that not signature check is performed.
  1127. *
  1128. * @param child the certificate to check.
  1129. *
  1130. * @return true if this certificate's subject matches the passed
  1131. * certificate's issuer.
  1132. */
  1133. cert.issued = function(child) {
  1134. return child.isIssuer(cert);
  1135. };
  1136. /**
  1137. * Generates the subjectKeyIdentifier for this certificate as byte buffer.
  1138. *
  1139. * @return the subjectKeyIdentifier for this certificate as byte buffer.
  1140. */
  1141. cert.generateSubjectKeyIdentifier = function() {
  1142. /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either:
  1143. (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  1144. value of the BIT STRING subjectPublicKey (excluding the tag,
  1145. length, and number of unused bits).
  1146. (2) The keyIdentifier is composed of a four bit type field with
  1147. the value 0100 followed by the least significant 60 bits of the
  1148. SHA-1 hash of the value of the BIT STRING subjectPublicKey
  1149. (excluding the tag, length, and number of unused bit string bits).
  1150. */
  1151. // skipping the tag, length, and number of unused bits is the same
  1152. // as just using the RSAPublicKey (for RSA keys, which are the
  1153. // only ones supported)
  1154. return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'});
  1155. };
  1156. /**
  1157. * Verifies the subjectKeyIdentifier extension value for this certificate
  1158. * against its public key. If no extension is found, false will be
  1159. * returned.
  1160. *
  1161. * @return true if verified, false if not.
  1162. */
  1163. cert.verifySubjectKeyIdentifier = function() {
  1164. var oid = oids['subjectKeyIdentifier'];
  1165. for(var i = 0; i < cert.extensions.length; ++i) {
  1166. var ext = cert.extensions[i];
  1167. if(ext.id === oid) {
  1168. var ski = cert.generateSubjectKeyIdentifier().getBytes();
  1169. return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski);
  1170. }
  1171. }
  1172. return false;
  1173. };
  1174. return cert;
  1175. };
  1176. /**
  1177. * Converts an X.509v3 RSA certificate from an ASN.1 object.
  1178. *
  1179. * Note: If the certificate is to be verified then compute hash should
  1180. * be set to true. There is currently no implementation for converting
  1181. * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1
  1182. * object needs to be scanned before the cert object is created.
  1183. *
  1184. * @param obj the asn1 representation of an X.509v3 RSA certificate.
  1185. * @param computeHash true to compute the hash for verification.
  1186. *
  1187. * @return the certificate.
  1188. */
  1189. pki.certificateFromAsn1 = function(obj, computeHash) {
  1190. // validate certificate and capture data
  1191. var capture = {};
  1192. var errors = [];
  1193. if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) {
  1194. var error = new Error('Cannot read X.509 certificate. ' +
  1195. 'ASN.1 object is not an X509v3 Certificate.');
  1196. error.errors = errors;
  1197. throw error;
  1198. }
  1199. // get oid
  1200. var oid = asn1.derToOid(capture.publicKeyOid);
  1201. if(oid !== pki.oids.rsaEncryption) {
  1202. throw new Error('Cannot read public key. OID is not RSA.');
  1203. }
  1204. // create certificate
  1205. var cert = pki.createCertificate();
  1206. cert.version = capture.certVersion ?
  1207. capture.certVersion.charCodeAt(0) : 0;
  1208. var serial = forge.util.createBuffer(capture.certSerialNumber);
  1209. cert.serialNumber = serial.toHex();
  1210. cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid);
  1211. cert.signatureParameters = _readSignatureParameters(
  1212. cert.signatureOid, capture.certSignatureParams, true);
  1213. cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid);
  1214. cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid,
  1215. capture.certinfoSignatureParams, false);
  1216. cert.signature = capture.certSignature;
  1217. var validity = [];
  1218. if(capture.certValidity1UTCTime !== undefined) {
  1219. validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime));
  1220. }
  1221. if(capture.certValidity2GeneralizedTime !== undefined) {
  1222. validity.push(asn1.generalizedTimeToDate(
  1223. capture.certValidity2GeneralizedTime));
  1224. }
  1225. if(capture.certValidity3UTCTime !== undefined) {
  1226. validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime));
  1227. }
  1228. if(capture.certValidity4GeneralizedTime !== undefined) {
  1229. validity.push(asn1.generalizedTimeToDate(
  1230. capture.certValidity4GeneralizedTime));
  1231. }
  1232. if(validity.length > 2) {
  1233. throw new Error('Cannot read notBefore/notAfter validity times; more ' +
  1234. 'than two times were provided in the certificate.');
  1235. }
  1236. if(validity.length < 2) {
  1237. throw new Error('Cannot read notBefore/notAfter validity times; they ' +
  1238. 'were not provided as either UTCTime or GeneralizedTime.');
  1239. }
  1240. cert.validity.notBefore = validity[0];
  1241. cert.validity.notAfter = validity[1];
  1242. // keep TBSCertificate to preserve signature when exporting
  1243. cert.tbsCertificate = capture.tbsCertificate;
  1244. if(computeHash) {
  1245. // check signature OID for supported signature types
  1246. cert.md = null;
  1247. if(cert.signatureOid in oids) {
  1248. var oid = oids[cert.signatureOid];
  1249. switch(oid) {
  1250. case 'sha1WithRSAEncryption':
  1251. cert.md = forge.md.sha1.create();
  1252. break;
  1253. case 'md5WithRSAEncryption':
  1254. cert.md = forge.md.md5.create();
  1255. break;
  1256. case 'sha256WithRSAEncryption':
  1257. cert.md = forge.md.sha256.create();
  1258. break;
  1259. case 'sha384WithRSAEncryption':
  1260. cert.md = forge.md.sha384.create();
  1261. break;
  1262. case 'sha512WithRSAEncryption':
  1263. cert.md = forge.md.sha512.create();
  1264. break;
  1265. case 'RSASSA-PSS':
  1266. cert.md = forge.md.sha256.create();
  1267. break;
  1268. }
  1269. }
  1270. if(cert.md === null) {
  1271. var error = new Error('Could not compute certificate digest. ' +
  1272. 'Unknown signature OID.');
  1273. error.signatureOid = cert.signatureOid;
  1274. throw error;
  1275. }
  1276. // produce DER formatted TBSCertificate and digest it
  1277. var bytes = asn1.toDer(cert.tbsCertificate);
  1278. cert.md.update(bytes.getBytes());
  1279. }
  1280. // handle issuer, build issuer message digest
  1281. var imd = forge.md.sha1.create();
  1282. cert.issuer.getField = function(sn) {
  1283. return _getAttribute(cert.issuer, sn);
  1284. };
  1285. cert.issuer.addField = function(attr) {
  1286. _fillMissingFields([attr]);
  1287. cert.issuer.attributes.push(attr);
  1288. };
  1289. cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer, imd);
  1290. if(capture.certIssuerUniqueId) {
  1291. cert.issuer.uniqueId = capture.certIssuerUniqueId;
  1292. }
  1293. cert.issuer.hash = imd.digest().toHex();
  1294. // handle subject, build subject message digest
  1295. var smd = forge.md.sha1.create();
  1296. cert.subject.getField = function(sn) {
  1297. return _getAttribute(cert.subject, sn);
  1298. };
  1299. cert.subject.addField = function(attr) {
  1300. _fillMissingFields([attr]);
  1301. cert.subject.attributes.push(attr);
  1302. };
  1303. cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject, smd);
  1304. if(capture.certSubjectUniqueId) {
  1305. cert.subject.uniqueId = capture.certSubjectUniqueId;
  1306. }
  1307. cert.subject.hash = smd.digest().toHex();
  1308. // handle extensions
  1309. if(capture.certExtensions) {
  1310. cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions);
  1311. } else {
  1312. cert.extensions = [];
  1313. }
  1314. // convert RSA public key from ASN.1
  1315. cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  1316. return cert;
  1317. };
  1318. /**
  1319. * Converts an ASN.1 extensions object (with extension sequences as its
  1320. * values) into an array of extension objects with types and values.
  1321. *
  1322. * Supported extensions:
  1323. *
  1324. * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 }
  1325. * KeyUsage ::= BIT STRING {
  1326. * digitalSignature (0),
  1327. * nonRepudiation (1),
  1328. * keyEncipherment (2),
  1329. * dataEncipherment (3),
  1330. * keyAgreement (4),
  1331. * keyCertSign (5),
  1332. * cRLSign (6),
  1333. * encipherOnly (7),
  1334. * decipherOnly (8)
  1335. * }
  1336. *
  1337. * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 }
  1338. * BasicConstraints ::= SEQUENCE {
  1339. * cA BOOLEAN DEFAULT FALSE,
  1340. * pathLenConstraint INTEGER (0..MAX) OPTIONAL
  1341. * }
  1342. *
  1343. * subjectAltName EXTENSION ::= {
  1344. * SYNTAX GeneralNames
  1345. * IDENTIFIED BY id-ce-subjectAltName
  1346. * }
  1347. *
  1348. * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
  1349. *
  1350. * GeneralName ::= CHOICE {
  1351. * otherName [0] INSTANCE OF OTHER-NAME,
  1352. * rfc822Name [1] IA5String,
  1353. * dNSName [2] IA5String,
  1354. * x400Address [3] ORAddress,
  1355. * directoryName [4] Name,
  1356. * ediPartyName [5] EDIPartyName,
  1357. * uniformResourceIdentifier [6] IA5String,
  1358. * IPAddress [7] OCTET STRING,
  1359. * registeredID [8] OBJECT IDENTIFIER
  1360. * }
  1361. *
  1362. * OTHER-NAME ::= TYPE-IDENTIFIER
  1363. *
  1364. * EDIPartyName ::= SEQUENCE {
  1365. * nameAssigner [0] DirectoryString {ub-name} OPTIONAL,
  1366. * partyName [1] DirectoryString {ub-name}
  1367. * }
  1368. *
  1369. * @param exts the extensions ASN.1 with extension sequences to parse.
  1370. *
  1371. * @return the array.
  1372. */
  1373. pki.certificateExtensionsFromAsn1 = function(exts) {
  1374. var rval = [];
  1375. for(var i = 0; i < exts.value.length; ++i) {
  1376. // get extension sequence
  1377. var extseq = exts.value[i];
  1378. for(var ei = 0; ei < extseq.value.length; ++ei) {
  1379. rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei]));
  1380. }
  1381. }
  1382. return rval;
  1383. };
  1384. /**
  1385. * Parses a single certificate extension from ASN.1.
  1386. *
  1387. * @param ext the extension in ASN.1 format.
  1388. *
  1389. * @return the parsed extension as an object.
  1390. */
  1391. pki.certificateExtensionFromAsn1 = function(ext) {
  1392. // an extension has:
  1393. // [0] extnID OBJECT IDENTIFIER
  1394. // [1] critical BOOLEAN DEFAULT FALSE
  1395. // [2] extnValue OCTET STRING
  1396. var e = {};
  1397. e.id = asn1.derToOid(ext.value[0].value);
  1398. e.critical = false;
  1399. if(ext.value[1].type === asn1.Type.BOOLEAN) {
  1400. e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00);
  1401. e.value = ext.value[2].value;
  1402. } else {
  1403. e.value = ext.value[1].value;
  1404. }
  1405. // if the oid is known, get its name
  1406. if(e.id in oids) {
  1407. e.name = oids[e.id];
  1408. // handle key usage
  1409. if(e.name === 'keyUsage') {
  1410. // get value as BIT STRING
  1411. var ev = asn1.fromDer(e.value);
  1412. var b2 = 0x00;
  1413. var b3 = 0x00;
  1414. if(ev.value.length > 1) {
  1415. // skip first byte, just indicates unused bits which
  1416. // will be padded with 0s anyway
  1417. // get bytes with flag bits
  1418. b2 = ev.value.charCodeAt(1);
  1419. b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0;
  1420. }
  1421. // set flags
  1422. e.digitalSignature = (b2 & 0x80) === 0x80;
  1423. e.nonRepudiation = (b2 & 0x40) === 0x40;
  1424. e.keyEncipherment = (b2 & 0x20) === 0x20;
  1425. e.dataEncipherment = (b2 & 0x10) === 0x10;
  1426. e.keyAgreement = (b2 & 0x08) === 0x08;
  1427. e.keyCertSign = (b2 & 0x04) === 0x04;
  1428. e.cRLSign = (b2 & 0x02) === 0x02;
  1429. e.encipherOnly = (b2 & 0x01) === 0x01;
  1430. e.decipherOnly = (b3 & 0x80) === 0x80;
  1431. } else if(e.name === 'basicConstraints') {
  1432. // handle basic constraints
  1433. // get value as SEQUENCE
  1434. var ev = asn1.fromDer(e.value);
  1435. // get cA BOOLEAN flag (defaults to false)
  1436. if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) {
  1437. e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00);
  1438. } else {
  1439. e.cA = false;
  1440. }
  1441. // get path length constraint
  1442. var value = null;
  1443. if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) {
  1444. value = ev.value[0].value;
  1445. } else if(ev.value.length > 1) {
  1446. value = ev.value[1].value;
  1447. }
  1448. if(value !== null) {
  1449. e.pathLenConstraint = asn1.derToInteger(value);
  1450. }
  1451. } else if(e.name === 'extKeyUsage') {
  1452. // handle extKeyUsage
  1453. // value is a SEQUENCE of OIDs
  1454. var ev = asn1.fromDer(e.value);
  1455. for(var vi = 0; vi < ev.value.length; ++vi) {
  1456. var oid = asn1.derToOid(ev.value[vi].value);
  1457. if(oid in oids) {
  1458. e[oids[oid]] = true;
  1459. } else {
  1460. e[oid] = true;
  1461. }
  1462. }
  1463. } else if(e.name === 'nsCertType') {
  1464. // handle nsCertType
  1465. // get value as BIT STRING
  1466. var ev = asn1.fromDer(e.value);
  1467. var b2 = 0x00;
  1468. if(ev.value.length > 1) {
  1469. // skip first byte, just indicates unused bits which
  1470. // will be padded with 0s anyway
  1471. // get bytes with flag bits
  1472. b2 = ev.value.charCodeAt(1);
  1473. }
  1474. // set flags
  1475. e.client = (b2 & 0x80) === 0x80;
  1476. e.server = (b2 & 0x40) === 0x40;
  1477. e.email = (b2 & 0x20) === 0x20;
  1478. e.objsign = (b2 & 0x10) === 0x10;
  1479. e.reserved = (b2 & 0x08) === 0x08;
  1480. e.sslCA = (b2 & 0x04) === 0x04;
  1481. e.emailCA = (b2 & 0x02) === 0x02;
  1482. e.objCA = (b2 & 0x01) === 0x01;
  1483. } else if(
  1484. e.name === 'subjectAltName' ||
  1485. e.name === 'issuerAltName') {
  1486. // handle subjectAltName/issuerAltName
  1487. e.altNames = [];
  1488. // ev is a SYNTAX SEQUENCE
  1489. var gn;
  1490. var ev = asn1.fromDer(e.value);
  1491. for(var n = 0; n < ev.value.length; ++n) {
  1492. // get GeneralName
  1493. gn = ev.value[n];
  1494. var altName = {
  1495. type: gn.type,
  1496. value: gn.value
  1497. };
  1498. e.altNames.push(altName);
  1499. // Note: Support for types 1,2,6,7,8
  1500. switch(gn.type) {
  1501. // rfc822Name
  1502. case 1:
  1503. // dNSName
  1504. case 2:
  1505. // uniformResourceIdentifier (URI)
  1506. case 6:
  1507. break;
  1508. // IPAddress
  1509. case 7:
  1510. // convert to IPv4/IPv6 string representation
  1511. altName.ip = forge.util.bytesToIP(gn.value);
  1512. break;
  1513. // registeredID
  1514. case 8:
  1515. altName.oid = asn1.derToOid(gn.value);
  1516. break;
  1517. default:
  1518. // unsupported
  1519. }
  1520. }
  1521. } else if(e.name === 'subjectKeyIdentifier') {
  1522. // value is an OCTETSTRING w/the hash of the key-type specific
  1523. // public key structure (eg: RSAPublicKey)
  1524. var ev = asn1.fromDer(e.value);
  1525. e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value);
  1526. }
  1527. }
  1528. return e;
  1529. };
  1530. /**
  1531. * Converts a PKCS#10 certification request (CSR) from an ASN.1 object.
  1532. *
  1533. * Note: If the certification request is to be verified then compute hash
  1534. * should be set to true. There is currently no implementation for converting
  1535. * a certificate back to ASN.1 so the CertificationRequestInfo part of the
  1536. * ASN.1 object needs to be scanned before the csr object is created.
  1537. *
  1538. * @param obj the asn1 representation of a PKCS#10 certification request (CSR).
  1539. * @param computeHash true to compute the hash for verification.
  1540. *
  1541. * @return the certification request (CSR).
  1542. */
  1543. pki.certificationRequestFromAsn1 = function(obj, computeHash) {
  1544. // validate certification request and capture data
  1545. var capture = {};
  1546. var errors = [];
  1547. if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) {
  1548. var error = new Error('Cannot read PKCS#10 certificate request. ' +
  1549. 'ASN.1 object is not a PKCS#10 CertificationRequest.');
  1550. error.errors = errors;
  1551. throw error;
  1552. }
  1553. // get oid
  1554. var oid = asn1.derToOid(capture.publicKeyOid);
  1555. if(oid !== pki.oids.rsaEncryption) {
  1556. throw new Error('Cannot read public key. OID is not RSA.');
  1557. }
  1558. // create certification request
  1559. var csr = pki.createCertificationRequest();
  1560. csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0;
  1561. csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid);
  1562. csr.signatureParameters = _readSignatureParameters(
  1563. csr.signatureOid, capture.csrSignatureParams, true);
  1564. csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid);
  1565. csr.siginfo.parameters = _readSignatureParameters(
  1566. csr.siginfo.algorithmOid, capture.csrSignatureParams, false);
  1567. csr.signature = capture.csrSignature;
  1568. // keep CertificationRequestInfo to preserve signature when exporting
  1569. csr.certificationRequestInfo = capture.certificationRequestInfo;
  1570. if(computeHash) {
  1571. // check signature OID for supported signature types
  1572. csr.md = null;
  1573. if(csr.signatureOid in oids) {
  1574. var oid = oids[csr.signatureOid];
  1575. switch(oid) {
  1576. case 'sha1WithRSAEncryption':
  1577. csr.md = forge.md.sha1.create();
  1578. break;
  1579. case 'md5WithRSAEncryption':
  1580. csr.md = forge.md.md5.create();
  1581. break;
  1582. case 'sha256WithRSAEncryption':
  1583. csr.md = forge.md.sha256.create();
  1584. break;
  1585. case 'sha384WithRSAEncryption':
  1586. csr.md = forge.md.sha384.create();
  1587. break;
  1588. case 'sha512WithRSAEncryption':
  1589. csr.md = forge.md.sha512.create();
  1590. break;
  1591. case 'RSASSA-PSS':
  1592. csr.md = forge.md.sha256.create();
  1593. break;
  1594. }
  1595. }
  1596. if(csr.md === null) {
  1597. var error = new Error('Could not compute certification request digest. ' +
  1598. 'Unknown signature OID.');
  1599. error.signatureOid = csr.signatureOid;
  1600. throw error;
  1601. }
  1602. // produce DER formatted CertificationRequestInfo and digest it
  1603. var bytes = asn1.toDer(csr.certificationRequestInfo);
  1604. csr.md.update(bytes.getBytes());
  1605. }
  1606. // handle subject, build subject message digest
  1607. var smd = forge.md.sha1.create();
  1608. csr.subject.getField = function(sn) {
  1609. return _getAttribute(csr.subject, sn);
  1610. };
  1611. csr.subject.addField = function(attr) {
  1612. _fillMissingFields([attr]);
  1613. csr.subject.attributes.push(attr);
  1614. };
  1615. csr.subject.attributes = pki.RDNAttributesAsArray(
  1616. capture.certificationRequestInfoSubject, smd);
  1617. csr.subject.hash = smd.digest().toHex();
  1618. // convert RSA public key from ASN.1
  1619. csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo);
  1620. // convert attributes from ASN.1
  1621. csr.getAttribute = function(sn) {
  1622. return _getAttribute(csr, sn);
  1623. };
  1624. csr.addAttribute = function(attr) {
  1625. _fillMissingFields([attr]);
  1626. csr.attributes.push(attr);
  1627. };
  1628. csr.attributes = pki.CRIAttributesAsArray(
  1629. capture.certificationRequestInfoAttributes || []);
  1630. return csr;
  1631. };
  1632. /**
  1633. * Creates an empty certification request (a CSR or certificate signing
  1634. * request). Once created, its public key and attributes can be set and then
  1635. * it can be signed.
  1636. *
  1637. * @return the empty certification request.
  1638. */
  1639. pki.createCertificationRequest = function() {
  1640. var csr = {};
  1641. csr.version = 0x00;
  1642. csr.signatureOid = null;
  1643. csr.signature = null;
  1644. csr.siginfo = {};
  1645. csr.siginfo.algorithmOid = null;
  1646. csr.subject = {};
  1647. csr.subject.getField = function(sn) {
  1648. return _getAttribute(csr.subject, sn);
  1649. };
  1650. csr.subject.addField = function(attr) {
  1651. _fillMissingFields([attr]);
  1652. csr.subject.attributes.push(attr);
  1653. };
  1654. csr.subject.attributes = [];
  1655. csr.subject.hash = null;
  1656. csr.publicKey = null;
  1657. csr.attributes = [];
  1658. csr.getAttribute = function(sn) {
  1659. return _getAttribute(csr, sn);
  1660. };
  1661. csr.addAttribute = function(attr) {
  1662. _fillMissingFields([attr]);
  1663. csr.attributes.push(attr);
  1664. };
  1665. csr.md = null;
  1666. /**
  1667. * Sets the subject of this certification request.
  1668. *
  1669. * @param attrs the array of subject attributes to use.
  1670. */
  1671. csr.setSubject = function(attrs) {
  1672. // set new attributes
  1673. _fillMissingFields(attrs);
  1674. csr.subject.attributes = attrs;
  1675. csr.subject.hash = null;
  1676. };
  1677. /**
  1678. * Sets the attributes of this certification request.
  1679. *
  1680. * @param attrs the array of attributes to use.
  1681. */
  1682. csr.setAttributes = function(attrs) {
  1683. // set new attributes
  1684. _fillMissingFields(attrs);
  1685. csr.attributes = attrs;
  1686. };
  1687. /**
  1688. * Signs this certification request using the given private key.
  1689. *
  1690. * @param key the private key to sign with.
  1691. * @param md the message digest object to use (defaults to forge.md.sha1).
  1692. */
  1693. csr.sign = function(key, md) {
  1694. // TODO: get signature OID from private key
  1695. csr.md = md || forge.md.sha1.create();
  1696. var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption'];
  1697. if(!algorithmOid) {
  1698. var error = new Error('Could not compute certification request digest. ' +
  1699. 'Unknown message digest algorithm OID.');
  1700. error.algorithm = csr.md.algorithm;
  1701. throw error;
  1702. }
  1703. csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid;
  1704. // get CertificationRequestInfo, convert to DER
  1705. csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr);
  1706. var bytes = asn1.toDer(csr.certificationRequestInfo);
  1707. // digest and sign
  1708. csr.md.update(bytes.getBytes());
  1709. csr.signature = key.sign(csr.md);
  1710. };
  1711. /**
  1712. * Attempts verify the signature on the passed certification request using
  1713. * its public key.
  1714. *
  1715. * A CSR that has been exported to a file in PEM format can be verified using
  1716. * OpenSSL using this command:
  1717. *
  1718. * openssl req -in <the-csr-pem-file> -verify -noout -text
  1719. *
  1720. * @return true if verified, false if not.
  1721. */
  1722. csr.verify = function() {
  1723. var rval = false;
  1724. var md = csr.md;
  1725. if(md === null) {
  1726. // check signature OID for supported signature types
  1727. if(csr.signatureOid in oids) {
  1728. // TODO: create DRY `OID to md` function
  1729. var oid = oids[csr.signatureOid];
  1730. switch(oid) {
  1731. case 'sha1WithRSAEncryption':
  1732. md = forge.md.sha1.create();
  1733. break;
  1734. case 'md5WithRSAEncryption':
  1735. md = forge.md.md5.create();
  1736. break;
  1737. case 'sha256WithRSAEncryption':
  1738. md = forge.md.sha256.create();
  1739. break;
  1740. case 'sha384WithRSAEncryption':
  1741. md = forge.md.sha384.create();
  1742. break;
  1743. case 'sha512WithRSAEncryption':
  1744. md = forge.md.sha512.create();
  1745. break;
  1746. case 'RSASSA-PSS':
  1747. md = forge.md.sha256.create();
  1748. break;
  1749. }
  1750. }
  1751. if(md === null) {
  1752. var error = new Error('Could not compute certification request digest. ' +
  1753. 'Unknown signature OID.');
  1754. error.signatureOid = csr.signatureOid;
  1755. throw error;
  1756. }
  1757. // produce DER formatted CertificationRequestInfo and digest it
  1758. var cri = csr.certificationRequestInfo ||
  1759. pki.getCertificationRequestInfo(csr);
  1760. var bytes = asn1.toDer(cri);
  1761. md.update(bytes.getBytes());
  1762. }
  1763. if(md !== null) {
  1764. var scheme;
  1765. switch(csr.signatureOid) {
  1766. case oids.sha1WithRSAEncryption:
  1767. /* use PKCS#1 v1.5 padding scheme */
  1768. break;
  1769. case oids['RSASSA-PSS']:
  1770. var hash, mgf;
  1771. /* initialize mgf */
  1772. hash = oids[csr.signatureParameters.mgf.hash.algorithmOid];
  1773. if(hash === undefined || forge.md[hash] === undefined) {
  1774. var error = new Error('Unsupported MGF hash function.');
  1775. error.oid = csr.signatureParameters.mgf.hash.algorithmOid;
  1776. error.name = hash;
  1777. throw error;
  1778. }
  1779. mgf = oids[csr.signatureParameters.mgf.algorithmOid];
  1780. if(mgf === undefined || forge.mgf[mgf] === undefined) {
  1781. var error = new Error('Unsupported MGF function.');
  1782. error.oid = csr.signatureParameters.mgf.algorithmOid;
  1783. error.name = mgf;
  1784. throw error;
  1785. }
  1786. mgf = forge.mgf[mgf].create(forge.md[hash].create());
  1787. /* initialize hash function */
  1788. hash = oids[csr.signatureParameters.hash.algorithmOid];
  1789. if(hash === undefined || forge.md[hash] === undefined) {
  1790. var error = new Error('Unsupported RSASSA-PSS hash function.');
  1791. error.oid = csr.signatureParameters.hash.algorithmOid;
  1792. error.name = hash;
  1793. throw error;
  1794. }
  1795. scheme = forge.pss.create(forge.md[hash].create(), mgf,
  1796. csr.signatureParameters.saltLength);
  1797. break;
  1798. }
  1799. // verify signature on csr using its public key
  1800. rval = csr.publicKey.verify(
  1801. md.digest().getBytes(), csr.signature, scheme);
  1802. }
  1803. return rval;
  1804. };
  1805. return csr;
  1806. };
  1807. /**
  1808. * Converts an X.509 subject or issuer to an ASN.1 RDNSequence.
  1809. *
  1810. * @param obj the subject or issuer (distinguished name).
  1811. *
  1812. * @return the ASN.1 RDNSequence.
  1813. */
  1814. function _dnToAsn1(obj) {
  1815. // create an empty RDNSequence
  1816. var rval = asn1.create(
  1817. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  1818. // iterate over attributes
  1819. var attr, set;
  1820. var attrs = obj.attributes;
  1821. for(var i = 0; i < attrs.length; ++i) {
  1822. attr = attrs[i];
  1823. var value = attr.value;
  1824. // reuse tag class for attribute value if available
  1825. var valueTagClass = asn1.Type.PRINTABLESTRING;
  1826. if('valueTagClass' in attr) {
  1827. valueTagClass = attr.valueTagClass;
  1828. if(valueTagClass === asn1.Type.UTF8) {
  1829. value = forge.util.encodeUtf8(value);
  1830. }
  1831. // FIXME: handle more encodings
  1832. }
  1833. // create a RelativeDistinguishedName set
  1834. // each value in the set is an AttributeTypeAndValue first
  1835. // containing the type (an OID) and second the value
  1836. set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  1837. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  1838. // AttributeType
  1839. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  1840. asn1.oidToDer(attr.type).getBytes()),
  1841. // AttributeValue
  1842. asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value)
  1843. ])
  1844. ]);
  1845. rval.value.push(set);
  1846. }
  1847. return rval;
  1848. }
  1849. /**
  1850. * Gets all printable attributes (typically of an issuer or subject) in a
  1851. * simplified JSON format for display.
  1852. *
  1853. * @param attrs the attributes.
  1854. *
  1855. * @return the JSON for display.
  1856. */
  1857. function _getAttributesAsJson(attrs) {
  1858. var rval = {};
  1859. for(var i = 0; i < attrs.length; ++i) {
  1860. var attr = attrs[i];
  1861. if(attr.shortName && (
  1862. attr.valueTagClass === asn1.Type.UTF8 ||
  1863. attr.valueTagClass === asn1.Type.PRINTABLESTRING ||
  1864. attr.valueTagClass === asn1.Type.IA5STRING)) {
  1865. var value = attr.value;
  1866. if(attr.valueTagClass === asn1.Type.UTF8) {
  1867. value = forge.util.encodeUtf8(attr.value);
  1868. }
  1869. if(!(attr.shortName in rval)) {
  1870. rval[attr.shortName] = value;
  1871. } else if(forge.util.isArray(rval[attr.shortName])) {
  1872. rval[attr.shortName].push(value);
  1873. } else {
  1874. rval[attr.shortName] = [rval[attr.shortName], value];
  1875. }
  1876. }
  1877. }
  1878. return rval;
  1879. }
  1880. /**
  1881. * Fills in missing fields in attributes.
  1882. *
  1883. * @param attrs the attributes to fill missing fields in.
  1884. */
  1885. function _fillMissingFields(attrs) {
  1886. var attr;
  1887. for(var i = 0; i < attrs.length; ++i) {
  1888. attr = attrs[i];
  1889. // populate missing name
  1890. if(typeof attr.name === 'undefined') {
  1891. if(attr.type && attr.type in pki.oids) {
  1892. attr.name = pki.oids[attr.type];
  1893. } else if(attr.shortName && attr.shortName in _shortNames) {
  1894. attr.name = pki.oids[_shortNames[attr.shortName]];
  1895. }
  1896. }
  1897. // populate missing type (OID)
  1898. if(typeof attr.type === 'undefined') {
  1899. if(attr.name && attr.name in pki.oids) {
  1900. attr.type = pki.oids[attr.name];
  1901. } else {
  1902. var error = new Error('Attribute type not specified.');
  1903. error.attribute = attr;
  1904. throw error;
  1905. }
  1906. }
  1907. // populate missing shortname
  1908. if(typeof attr.shortName === 'undefined') {
  1909. if(attr.name && attr.name in _shortNames) {
  1910. attr.shortName = _shortNames[attr.name];
  1911. }
  1912. }
  1913. // convert extensions to value
  1914. if(attr.type === oids.extensionRequest) {
  1915. attr.valueConstructed = true;
  1916. attr.valueTagClass = asn1.Type.SEQUENCE;
  1917. if(!attr.value && attr.extensions) {
  1918. attr.value = [];
  1919. for(var ei = 0; ei < attr.extensions.length; ++ei) {
  1920. attr.value.push(pki.certificateExtensionToAsn1(
  1921. _fillMissingExtensionFields(attr.extensions[ei])));
  1922. }
  1923. }
  1924. }
  1925. if(typeof attr.value === 'undefined') {
  1926. var error = new Error('Attribute value not specified.');
  1927. error.attribute = attr;
  1928. throw error;
  1929. }
  1930. }
  1931. }
  1932. /**
  1933. * Fills in missing fields in certificate extensions.
  1934. *
  1935. * @param e the extension.
  1936. * @param [options] the options to use.
  1937. * [cert] the certificate the extensions are for.
  1938. *
  1939. * @return the extension.
  1940. */
  1941. function _fillMissingExtensionFields(e, options) {
  1942. options = options || {};
  1943. // populate missing name
  1944. if(typeof e.name === 'undefined') {
  1945. if(e.id && e.id in pki.oids) {
  1946. e.name = pki.oids[e.id];
  1947. }
  1948. }
  1949. // populate missing id
  1950. if(typeof e.id === 'undefined') {
  1951. if(e.name && e.name in pki.oids) {
  1952. e.id = pki.oids[e.name];
  1953. } else {
  1954. var error = new Error('Extension ID not specified.');
  1955. error.extension = e;
  1956. throw error;
  1957. }
  1958. }
  1959. if(typeof e.value !== 'undefined') {
  1960. return e;
  1961. }
  1962. // handle missing value:
  1963. // value is a BIT STRING
  1964. if(e.name === 'keyUsage') {
  1965. // build flags
  1966. var unused = 0;
  1967. var b2 = 0x00;
  1968. var b3 = 0x00;
  1969. if(e.digitalSignature) {
  1970. b2 |= 0x80;
  1971. unused = 7;
  1972. }
  1973. if(e.nonRepudiation) {
  1974. b2 |= 0x40;
  1975. unused = 6;
  1976. }
  1977. if(e.keyEncipherment) {
  1978. b2 |= 0x20;
  1979. unused = 5;
  1980. }
  1981. if(e.dataEncipherment) {
  1982. b2 |= 0x10;
  1983. unused = 4;
  1984. }
  1985. if(e.keyAgreement) {
  1986. b2 |= 0x08;
  1987. unused = 3;
  1988. }
  1989. if(e.keyCertSign) {
  1990. b2 |= 0x04;
  1991. unused = 2;
  1992. }
  1993. if(e.cRLSign) {
  1994. b2 |= 0x02;
  1995. unused = 1;
  1996. }
  1997. if(e.encipherOnly) {
  1998. b2 |= 0x01;
  1999. unused = 0;
  2000. }
  2001. if(e.decipherOnly) {
  2002. b3 |= 0x80;
  2003. unused = 7;
  2004. }
  2005. // create bit string
  2006. var value = String.fromCharCode(unused);
  2007. if(b3 !== 0) {
  2008. value += String.fromCharCode(b2) + String.fromCharCode(b3);
  2009. } else if(b2 !== 0) {
  2010. value += String.fromCharCode(b2);
  2011. }
  2012. e.value = asn1.create(
  2013. asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
  2014. } else if(e.name === 'basicConstraints') {
  2015. // basicConstraints is a SEQUENCE
  2016. e.value = asn1.create(
  2017. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2018. // cA BOOLEAN flag defaults to false
  2019. if(e.cA) {
  2020. e.value.value.push(asn1.create(
  2021. asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
  2022. String.fromCharCode(0xFF)));
  2023. }
  2024. if('pathLenConstraint' in e) {
  2025. e.value.value.push(asn1.create(
  2026. asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2027. asn1.integerToDer(e.pathLenConstraint).getBytes()));
  2028. }
  2029. } else if(e.name === 'extKeyUsage') {
  2030. // extKeyUsage is a SEQUENCE of OIDs
  2031. e.value = asn1.create(
  2032. asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2033. var seq = e.value.value;
  2034. for(var key in e) {
  2035. if(e[key] !== true) {
  2036. continue;
  2037. }
  2038. // key is name in OID map
  2039. if(key in oids) {
  2040. seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,
  2041. false, asn1.oidToDer(oids[key]).getBytes()));
  2042. } else if(key.indexOf('.') !== -1) {
  2043. // assume key is an OID
  2044. seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID,
  2045. false, asn1.oidToDer(key).getBytes()));
  2046. }
  2047. }
  2048. } else if(e.name === 'nsCertType') {
  2049. // nsCertType is a BIT STRING
  2050. // build flags
  2051. var unused = 0;
  2052. var b2 = 0x00;
  2053. if(e.client) {
  2054. b2 |= 0x80;
  2055. unused = 7;
  2056. }
  2057. if(e.server) {
  2058. b2 |= 0x40;
  2059. unused = 6;
  2060. }
  2061. if(e.email) {
  2062. b2 |= 0x20;
  2063. unused = 5;
  2064. }
  2065. if(e.objsign) {
  2066. b2 |= 0x10;
  2067. unused = 4;
  2068. }
  2069. if(e.reserved) {
  2070. b2 |= 0x08;
  2071. unused = 3;
  2072. }
  2073. if(e.sslCA) {
  2074. b2 |= 0x04;
  2075. unused = 2;
  2076. }
  2077. if(e.emailCA) {
  2078. b2 |= 0x02;
  2079. unused = 1;
  2080. }
  2081. if(e.objCA) {
  2082. b2 |= 0x01;
  2083. unused = 0;
  2084. }
  2085. // create bit string
  2086. var value = String.fromCharCode(unused);
  2087. if(b2 !== 0) {
  2088. value += String.fromCharCode(b2);
  2089. }
  2090. e.value = asn1.create(
  2091. asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value);
  2092. } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') {
  2093. // SYNTAX SEQUENCE
  2094. e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2095. var altName;
  2096. for(var n = 0; n < e.altNames.length; ++n) {
  2097. altName = e.altNames[n];
  2098. var value = altName.value;
  2099. // handle IP
  2100. if(altName.type === 7 && altName.ip) {
  2101. value = forge.util.bytesFromIP(altName.ip);
  2102. if(value === null) {
  2103. var error = new Error(
  2104. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  2105. error.extension = e;
  2106. throw error;
  2107. }
  2108. } else if(altName.type === 8) {
  2109. // handle OID
  2110. if(altName.oid) {
  2111. value = asn1.oidToDer(asn1.oidToDer(altName.oid));
  2112. } else {
  2113. // deprecated ... convert value to OID
  2114. value = asn1.oidToDer(value);
  2115. }
  2116. }
  2117. e.value.value.push(asn1.create(
  2118. asn1.Class.CONTEXT_SPECIFIC, altName.type, false,
  2119. value));
  2120. }
  2121. } else if(e.name === 'subjectKeyIdentifier' && options.cert) {
  2122. var ski = options.cert.generateSubjectKeyIdentifier();
  2123. e.subjectKeyIdentifier = ski.toHex();
  2124. // OCTETSTRING w/digest
  2125. e.value = asn1.create(
  2126. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes());
  2127. } else if(e.name === 'authorityKeyIdentifier' && options.cert) {
  2128. // SYNTAX SEQUENCE
  2129. e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2130. var seq = e.value.value;
  2131. if(e.keyIdentifier) {
  2132. var keyIdentifier = (e.keyIdentifier === true ?
  2133. options.cert.generateSubjectKeyIdentifier().getBytes() :
  2134. e.keyIdentifier);
  2135. seq.push(
  2136. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier));
  2137. }
  2138. if(e.authorityCertIssuer) {
  2139. var authorityCertIssuer = [
  2140. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [
  2141. _dnToAsn1(e.authorityCertIssuer === true ?
  2142. options.cert.issuer : e.authorityCertIssuer)
  2143. ])
  2144. ];
  2145. seq.push(
  2146. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer));
  2147. }
  2148. if(e.serialNumber) {
  2149. var serialNumber = forge.util.hexToBytes(e.serialNumber === true ?
  2150. options.cert.serialNumber : e.serialNumber);
  2151. seq.push(
  2152. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber));
  2153. }
  2154. } else if (e.name === 'cRLDistributionPoints') {
  2155. e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2156. var seq = e.value.value;
  2157. // Create sub SEQUENCE of DistributionPointName
  2158. var subSeq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2159. // Create fullName CHOICE
  2160. var fullNameGeneralNames = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  2161. var altName;
  2162. for(var n = 0; n < e.altNames.length; ++n) {
  2163. altName = e.altNames[n];
  2164. var value = altName.value;
  2165. // handle IP
  2166. if(altName.type === 7 && altName.ip) {
  2167. value = forge.util.bytesFromIP(altName.ip);
  2168. if(value === null) {
  2169. var error = new Error(
  2170. 'Extension "ip" value is not a valid IPv4 or IPv6 address.');
  2171. error.extension = e;
  2172. throw error;
  2173. }
  2174. } else if(altName.type === 8) {
  2175. // handle OID
  2176. if(altName.oid) {
  2177. value = asn1.oidToDer(asn1.oidToDer(altName.oid));
  2178. } else {
  2179. // deprecated ... convert value to OID
  2180. value = asn1.oidToDer(value);
  2181. }
  2182. }
  2183. fullNameGeneralNames.value.push(asn1.create(
  2184. asn1.Class.CONTEXT_SPECIFIC, altName.type, false,
  2185. value));
  2186. }
  2187. // Add to the parent SEQUENCE
  2188. subSeq.value.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames]));
  2189. seq.push(subSeq);
  2190. }
  2191. // ensure value has been defined by now
  2192. if(typeof e.value === 'undefined') {
  2193. var error = new Error('Extension value not specified.');
  2194. error.extension = e;
  2195. throw error;
  2196. }
  2197. return e;
  2198. }
  2199. /**
  2200. * Convert signature parameters object to ASN.1
  2201. *
  2202. * @param {String} oid Signature algorithm OID
  2203. * @param params The signature parametrs object
  2204. * @return ASN.1 object representing signature parameters
  2205. */
  2206. function _signatureParametersToAsn1(oid, params) {
  2207. switch(oid) {
  2208. case oids['RSASSA-PSS']:
  2209. var parts = [];
  2210. if(params.hash.algorithmOid !== undefined) {
  2211. parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  2212. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2213. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2214. asn1.oidToDer(params.hash.algorithmOid).getBytes()),
  2215. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  2216. ])
  2217. ]));
  2218. }
  2219. if(params.mgf.algorithmOid !== undefined) {
  2220. parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
  2221. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2222. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2223. asn1.oidToDer(params.mgf.algorithmOid).getBytes()),
  2224. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2225. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2226. asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()),
  2227. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')
  2228. ])
  2229. ])
  2230. ]));
  2231. }
  2232. if(params.saltLength !== undefined) {
  2233. parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
  2234. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2235. asn1.integerToDer(params.saltLength).getBytes())
  2236. ]));
  2237. }
  2238. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts);
  2239. default:
  2240. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '');
  2241. }
  2242. }
  2243. /**
  2244. * Converts a certification request's attributes to an ASN.1 set of
  2245. * CRIAttributes.
  2246. *
  2247. * @param csr certification request.
  2248. *
  2249. * @return the ASN.1 set of CRIAttributes.
  2250. */
  2251. function _CRIAttributesToAsn1(csr) {
  2252. // create an empty context-specific container
  2253. var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []);
  2254. // no attributes, return empty container
  2255. if(csr.attributes.length === 0) {
  2256. return rval;
  2257. }
  2258. // each attribute has a sequence with a type and a set of values
  2259. var attrs = csr.attributes;
  2260. for(var i = 0; i < attrs.length; ++i) {
  2261. var attr = attrs[i];
  2262. var value = attr.value;
  2263. // reuse tag class for attribute value if available
  2264. var valueTagClass = asn1.Type.UTF8;
  2265. if('valueTagClass' in attr) {
  2266. valueTagClass = attr.valueTagClass;
  2267. }
  2268. if(valueTagClass === asn1.Type.UTF8) {
  2269. value = forge.util.encodeUtf8(value);
  2270. }
  2271. var valueConstructed = false;
  2272. if('valueConstructed' in attr) {
  2273. valueConstructed = attr.valueConstructed;
  2274. }
  2275. // FIXME: handle more encodings
  2276. // create a RelativeDistinguishedName set
  2277. // each value in the set is an AttributeTypeAndValue first
  2278. // containing the type (an OID) and second the value
  2279. var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2280. // AttributeType
  2281. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2282. asn1.oidToDer(attr.type).getBytes()),
  2283. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [
  2284. // AttributeValue
  2285. asn1.create(
  2286. asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value)
  2287. ])
  2288. ]);
  2289. rval.value.push(seq);
  2290. }
  2291. return rval;
  2292. }
  2293. /**
  2294. * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate.
  2295. *
  2296. * @param cert the certificate.
  2297. *
  2298. * @return the asn1 TBSCertificate.
  2299. */
  2300. pki.getTBSCertificate = function(cert) {
  2301. // TBSCertificate
  2302. var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2303. // version
  2304. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [
  2305. // integer
  2306. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2307. asn1.integerToDer(cert.version).getBytes())
  2308. ]),
  2309. // serialNumber
  2310. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2311. forge.util.hexToBytes(cert.serialNumber)),
  2312. // signature
  2313. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2314. // algorithm
  2315. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2316. asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()),
  2317. // parameters
  2318. _signatureParametersToAsn1(
  2319. cert.siginfo.algorithmOid, cert.siginfo.parameters)
  2320. ]),
  2321. // issuer
  2322. _dnToAsn1(cert.issuer),
  2323. // validity
  2324. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2325. // notBefore
  2326. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,
  2327. asn1.dateToUtcTime(cert.validity.notBefore)),
  2328. // notAfter
  2329. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false,
  2330. asn1.dateToUtcTime(cert.validity.notAfter))
  2331. ]),
  2332. // subject
  2333. _dnToAsn1(cert.subject),
  2334. // SubjectPublicKeyInfo
  2335. pki.publicKeyToAsn1(cert.publicKey)
  2336. ]);
  2337. if(cert.issuer.uniqueId) {
  2338. // issuerUniqueID (optional)
  2339. tbs.value.push(
  2340. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [
  2341. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2342. // TODO: support arbitrary bit length ids
  2343. String.fromCharCode(0x00) +
  2344. cert.issuer.uniqueId
  2345. )
  2346. ])
  2347. );
  2348. }
  2349. if(cert.subject.uniqueId) {
  2350. // subjectUniqueID (optional)
  2351. tbs.value.push(
  2352. asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [
  2353. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2354. // TODO: support arbitrary bit length ids
  2355. String.fromCharCode(0x00) +
  2356. cert.subject.uniqueId
  2357. )
  2358. ])
  2359. );
  2360. }
  2361. if(cert.extensions.length > 0) {
  2362. // extensions (optional)
  2363. tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions));
  2364. }
  2365. return tbs;
  2366. };
  2367. /**
  2368. * Gets the ASN.1 CertificationRequestInfo part of a
  2369. * PKCS#10 CertificationRequest.
  2370. *
  2371. * @param csr the certification request.
  2372. *
  2373. * @return the asn1 CertificationRequestInfo.
  2374. */
  2375. pki.getCertificationRequestInfo = function(csr) {
  2376. // CertificationRequestInfo
  2377. var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2378. // version
  2379. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false,
  2380. asn1.integerToDer(csr.version).getBytes()),
  2381. // subject
  2382. _dnToAsn1(csr.subject),
  2383. // SubjectPublicKeyInfo
  2384. pki.publicKeyToAsn1(csr.publicKey),
  2385. // attributes
  2386. _CRIAttributesToAsn1(csr)
  2387. ]);
  2388. return cri;
  2389. };
  2390. /**
  2391. * Converts a DistinguishedName (subject or issuer) to an ASN.1 object.
  2392. *
  2393. * @param dn the DistinguishedName.
  2394. *
  2395. * @return the asn1 representation of a DistinguishedName.
  2396. */
  2397. pki.distinguishedNameToAsn1 = function(dn) {
  2398. return _dnToAsn1(dn);
  2399. };
  2400. /**
  2401. * Converts an X.509v3 RSA certificate to an ASN.1 object.
  2402. *
  2403. * @param cert the certificate.
  2404. *
  2405. * @return the asn1 representation of an X.509v3 RSA certificate.
  2406. */
  2407. pki.certificateToAsn1 = function(cert) {
  2408. // prefer cached TBSCertificate over generating one
  2409. var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert);
  2410. // Certificate
  2411. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2412. // TBSCertificate
  2413. tbsCertificate,
  2414. // AlgorithmIdentifier (signature algorithm)
  2415. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2416. // algorithm
  2417. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2418. asn1.oidToDer(cert.signatureOid).getBytes()),
  2419. // parameters
  2420. _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters)
  2421. ]),
  2422. // SignatureValue
  2423. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2424. String.fromCharCode(0x00) + cert.signature)
  2425. ]);
  2426. };
  2427. /**
  2428. * Converts X.509v3 certificate extensions to ASN.1.
  2429. *
  2430. * @param exts the extensions to convert.
  2431. *
  2432. * @return the extensions in ASN.1 format.
  2433. */
  2434. pki.certificateExtensionsToAsn1 = function(exts) {
  2435. // create top-level extension container
  2436. var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []);
  2437. // create extension sequence (stores a sequence for each extension)
  2438. var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2439. rval.value.push(seq);
  2440. for(var i = 0; i < exts.length; ++i) {
  2441. seq.value.push(pki.certificateExtensionToAsn1(exts[i]));
  2442. }
  2443. return rval;
  2444. };
  2445. /**
  2446. * Converts a single certificate extension to ASN.1.
  2447. *
  2448. * @param ext the extension to convert.
  2449. *
  2450. * @return the extension in ASN.1 format.
  2451. */
  2452. pki.certificateExtensionToAsn1 = function(ext) {
  2453. // create a sequence for each extension
  2454. var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []);
  2455. // extnID (OID)
  2456. extseq.value.push(asn1.create(
  2457. asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2458. asn1.oidToDer(ext.id).getBytes()));
  2459. // critical defaults to false
  2460. if(ext.critical) {
  2461. // critical BOOLEAN DEFAULT FALSE
  2462. extseq.value.push(asn1.create(
  2463. asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false,
  2464. String.fromCharCode(0xFF)));
  2465. }
  2466. var value = ext.value;
  2467. if(typeof ext.value !== 'string') {
  2468. // value is asn.1
  2469. value = asn1.toDer(value).getBytes();
  2470. }
  2471. // extnValue (OCTET STRING)
  2472. extseq.value.push(asn1.create(
  2473. asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value));
  2474. return extseq;
  2475. };
  2476. /**
  2477. * Converts a PKCS#10 certification request to an ASN.1 object.
  2478. *
  2479. * @param csr the certification request.
  2480. *
  2481. * @return the asn1 representation of a certification request.
  2482. */
  2483. pki.certificationRequestToAsn1 = function(csr) {
  2484. // prefer cached CertificationRequestInfo over generating one
  2485. var cri = csr.certificationRequestInfo ||
  2486. pki.getCertificationRequestInfo(csr);
  2487. // Certificate
  2488. return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2489. // CertificationRequestInfo
  2490. cri,
  2491. // AlgorithmIdentifier (signature algorithm)
  2492. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
  2493. // algorithm
  2494. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false,
  2495. asn1.oidToDer(csr.signatureOid).getBytes()),
  2496. // parameters
  2497. _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters)
  2498. ]),
  2499. // signature
  2500. asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false,
  2501. String.fromCharCode(0x00) + csr.signature)
  2502. ]);
  2503. };
  2504. /**
  2505. * Creates a CA store.
  2506. *
  2507. * @param certs an optional array of certificate objects or PEM-formatted
  2508. * certificate strings to add to the CA store.
  2509. *
  2510. * @return the CA store.
  2511. */
  2512. pki.createCaStore = function(certs) {
  2513. // create CA store
  2514. var caStore = {
  2515. // stored certificates
  2516. certs: {}
  2517. };
  2518. /**
  2519. * Gets the certificate that issued the passed certificate or its
  2520. * 'parent'.
  2521. *
  2522. * @param cert the certificate to get the parent for.
  2523. *
  2524. * @return the parent certificate or null if none was found.
  2525. */
  2526. caStore.getIssuer = function(cert) {
  2527. var rval = getBySubject(cert.issuer);
  2528. // see if there are multiple matches
  2529. /*if(forge.util.isArray(rval)) {
  2530. // TODO: resolve multiple matches by checking
  2531. // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc.
  2532. // FIXME: or alternatively do authority key mapping
  2533. // if possible (X.509v1 certs can't work?)
  2534. throw new Error('Resolving multiple issuer matches not implemented yet.');
  2535. }*/
  2536. return rval;
  2537. };
  2538. /**
  2539. * Adds a trusted certificate to the store.
  2540. *
  2541. * @param cert the certificate to add as a trusted certificate (either a
  2542. * pki.certificate object or a PEM-formatted certificate).
  2543. */
  2544. caStore.addCertificate = function(cert) {
  2545. // convert from pem if necessary
  2546. if(typeof cert === 'string') {
  2547. cert = forge.pki.certificateFromPem(cert);
  2548. }
  2549. ensureSubjectHasHash(cert.subject);
  2550. if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store
  2551. if(cert.subject.hash in caStore.certs) {
  2552. // subject hash already exists, append to array
  2553. var tmp = caStore.certs[cert.subject.hash];
  2554. if(!forge.util.isArray(tmp)) {
  2555. tmp = [tmp];
  2556. }
  2557. tmp.push(cert);
  2558. caStore.certs[cert.subject.hash] = tmp;
  2559. } else {
  2560. caStore.certs[cert.subject.hash] = cert;
  2561. }
  2562. }
  2563. };
  2564. /**
  2565. * Checks to see if the given certificate is in the store.
  2566. *
  2567. * @param cert the certificate to check (either a pki.certificate or a
  2568. * PEM-formatted certificate).
  2569. *
  2570. * @return true if the certificate is in the store, false if not.
  2571. */
  2572. caStore.hasCertificate = function(cert) {
  2573. // convert from pem if necessary
  2574. if(typeof cert === 'string') {
  2575. cert = forge.pki.certificateFromPem(cert);
  2576. }
  2577. var match = getBySubject(cert.subject);
  2578. if(!match) {
  2579. return false;
  2580. }
  2581. if(!forge.util.isArray(match)) {
  2582. match = [match];
  2583. }
  2584. // compare DER-encoding of certificates
  2585. var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();
  2586. for(var i = 0; i < match.length; ++i) {
  2587. var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();
  2588. if(der1 === der2) {
  2589. return true;
  2590. }
  2591. }
  2592. return false;
  2593. };
  2594. /**
  2595. * Lists all of the certificates kept in the store.
  2596. *
  2597. * @return an array of all of the pki.certificate objects in the store.
  2598. */
  2599. caStore.listAllCertificates = function() {
  2600. var certList = [];
  2601. for(var hash in caStore.certs) {
  2602. if(caStore.certs.hasOwnProperty(hash)) {
  2603. var value = caStore.certs[hash];
  2604. if(!forge.util.isArray(value)) {
  2605. certList.push(value);
  2606. } else {
  2607. for(var i = 0; i < value.length; ++i) {
  2608. certList.push(value[i]);
  2609. }
  2610. }
  2611. }
  2612. }
  2613. return certList;
  2614. };
  2615. /**
  2616. * Removes a certificate from the store.
  2617. *
  2618. * @param cert the certificate to remove (either a pki.certificate or a
  2619. * PEM-formatted certificate).
  2620. *
  2621. * @return the certificate that was removed or null if the certificate
  2622. * wasn't in store.
  2623. */
  2624. caStore.removeCertificate = function(cert) {
  2625. var result;
  2626. // convert from pem if necessary
  2627. if(typeof cert === 'string') {
  2628. cert = forge.pki.certificateFromPem(cert);
  2629. }
  2630. ensureSubjectHasHash(cert.subject);
  2631. if(!caStore.hasCertificate(cert)) {
  2632. return null;
  2633. }
  2634. var match = getBySubject(cert.subject);
  2635. if(!forge.util.isArray(match)) {
  2636. result = caStore.certs[cert.subject.hash];
  2637. delete caStore.certs[cert.subject.hash];
  2638. return result;
  2639. }
  2640. // compare DER-encoding of certificates
  2641. var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes();
  2642. for(var i = 0; i < match.length; ++i) {
  2643. var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes();
  2644. if(der1 === der2) {
  2645. result = match[i];
  2646. match.splice(i, 1);
  2647. }
  2648. }
  2649. if(match.length === 0) {
  2650. delete caStore.certs[cert.subject.hash];
  2651. }
  2652. return result;
  2653. };
  2654. function getBySubject(subject) {
  2655. ensureSubjectHasHash(subject);
  2656. return caStore.certs[subject.hash] || null;
  2657. }
  2658. function ensureSubjectHasHash(subject) {
  2659. // produce subject hash if it doesn't exist
  2660. if(!subject.hash) {
  2661. var md = forge.md.sha1.create();
  2662. subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md);
  2663. subject.hash = md.digest().toHex();
  2664. }
  2665. }
  2666. // auto-add passed in certs
  2667. if(certs) {
  2668. // parse PEM-formatted certificates as necessary
  2669. for(var i = 0; i < certs.length; ++i) {
  2670. var cert = certs[i];
  2671. caStore.addCertificate(cert);
  2672. }
  2673. }
  2674. return caStore;
  2675. };
  2676. /**
  2677. * Certificate verification errors, based on TLS.
  2678. */
  2679. pki.certificateError = {
  2680. bad_certificate: 'forge.pki.BadCertificate',
  2681. unsupported_certificate: 'forge.pki.UnsupportedCertificate',
  2682. certificate_revoked: 'forge.pki.CertificateRevoked',
  2683. certificate_expired: 'forge.pki.CertificateExpired',
  2684. certificate_unknown: 'forge.pki.CertificateUnknown',
  2685. unknown_ca: 'forge.pki.UnknownCertificateAuthority'
  2686. };
  2687. /**
  2688. * Verifies a certificate chain against the given Certificate Authority store
  2689. * with an optional custom verify callback.
  2690. *
  2691. * @param caStore a certificate store to verify against.
  2692. * @param chain the certificate chain to verify, with the root or highest
  2693. * authority at the end (an array of certificates).
  2694. * @param verify called for every certificate in the chain.
  2695. *
  2696. * The verify callback has the following signature:
  2697. *
  2698. * verified - Set to true if certificate was verified, otherwise the
  2699. * pki.certificateError for why the certificate failed.
  2700. * depth - The current index in the chain, where 0 is the end point's cert.
  2701. * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous
  2702. * end point.
  2703. *
  2704. * The function returns true on success and on failure either the appropriate
  2705. * pki.certificateError or an object with 'error' set to the appropriate
  2706. * pki.certificateError and 'message' set to a custom error message.
  2707. *
  2708. * @return true if successful, error thrown if not.
  2709. */
  2710. pki.verifyCertificateChain = function(caStore, chain, verify) {
  2711. /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate
  2712. Section 6: Certification Path Validation
  2713. See inline parentheticals related to this particular implementation.
  2714. The primary goal of path validation is to verify the binding between
  2715. a subject distinguished name or a subject alternative name and subject
  2716. public key, as represented in the end entity certificate, based on the
  2717. public key of the trust anchor. This requires obtaining a sequence of
  2718. certificates that support that binding. That sequence should be provided
  2719. in the passed 'chain'. The trust anchor should be in the given CA
  2720. store. The 'end entity' certificate is the certificate provided by the
  2721. end point (typically a server) and is the first in the chain.
  2722. To meet this goal, the path validation process verifies, among other
  2723. things, that a prospective certification path (a sequence of n
  2724. certificates or a 'chain') satisfies the following conditions:
  2725. (a) for all x in {1, ..., n-1}, the subject of certificate x is
  2726. the issuer of certificate x+1;
  2727. (b) certificate 1 is issued by the trust anchor;
  2728. (c) certificate n is the certificate to be validated; and
  2729. (d) for all x in {1, ..., n}, the certificate was valid at the
  2730. time in question.
  2731. Note that here 'n' is index 0 in the chain and 1 is the last certificate
  2732. in the chain and it must be signed by a certificate in the connection's
  2733. CA store.
  2734. The path validation process also determines the set of certificate
  2735. policies that are valid for this path, based on the certificate policies
  2736. extension, policy mapping extension, policy constraints extension, and
  2737. inhibit any-policy extension.
  2738. Note: Policy mapping extension not supported (Not Required).
  2739. Note: If the certificate has an unsupported critical extension, then it
  2740. must be rejected.
  2741. Note: A certificate is self-issued if the DNs that appear in the subject
  2742. and issuer fields are identical and are not empty.
  2743. The path validation algorithm assumes the following seven inputs are
  2744. provided to the path processing logic. What this specific implementation
  2745. will use is provided parenthetically:
  2746. (a) a prospective certification path of length n (the 'chain')
  2747. (b) the current date/time: ('now').
  2748. (c) user-initial-policy-set: A set of certificate policy identifiers
  2749. naming the policies that are acceptable to the certificate user.
  2750. The user-initial-policy-set contains the special value any-policy
  2751. if the user is not concerned about certificate policy
  2752. (Not implemented. Any policy is accepted).
  2753. (d) trust anchor information, describing a CA that serves as a trust
  2754. anchor for the certification path. The trust anchor information
  2755. includes:
  2756. (1) the trusted issuer name,
  2757. (2) the trusted public key algorithm,
  2758. (3) the trusted public key, and
  2759. (4) optionally, the trusted public key parameters associated
  2760. with the public key.
  2761. (Trust anchors are provided via certificates in the CA store).
  2762. The trust anchor information may be provided to the path processing
  2763. procedure in the form of a self-signed certificate. The trusted anchor
  2764. information is trusted because it was delivered to the path processing
  2765. procedure by some trustworthy out-of-band procedure. If the trusted
  2766. public key algorithm requires parameters, then the parameters are
  2767. provided along with the trusted public key (No parameters used in this
  2768. implementation).
  2769. (e) initial-policy-mapping-inhibit, which indicates if policy mapping is
  2770. allowed in the certification path.
  2771. (Not implemented, no policy checking)
  2772. (f) initial-explicit-policy, which indicates if the path must be valid
  2773. for at least one of the certificate policies in the user-initial-
  2774. policy-set.
  2775. (Not implemented, no policy checking)
  2776. (g) initial-any-policy-inhibit, which indicates whether the
  2777. anyPolicy OID should be processed if it is included in a
  2778. certificate.
  2779. (Not implemented, so any policy is valid provided that it is
  2780. not marked as critical) */
  2781. /* Basic Path Processing:
  2782. For each certificate in the 'chain', the following is checked:
  2783. 1. The certificate validity period includes the current time.
  2784. 2. The certificate was signed by its parent (where the parent is either
  2785. the next in the chain or from the CA store). Allow processing to
  2786. continue to the next step if no parent is found but the certificate is
  2787. in the CA store.
  2788. 3. TODO: The certificate has not been revoked.
  2789. 4. The certificate issuer name matches the parent's subject name.
  2790. 5. TODO: If the certificate is self-issued and not the final certificate
  2791. in the chain, skip this step, otherwise verify that the subject name
  2792. is within one of the permitted subtrees of X.500 distinguished names
  2793. and that each of the alternative names in the subjectAltName extension
  2794. (critical or non-critical) is within one of the permitted subtrees for
  2795. that name type.
  2796. 6. TODO: If the certificate is self-issued and not the final certificate
  2797. in the chain, skip this step, otherwise verify that the subject name
  2798. is not within one of the excluded subtrees for X.500 distinguished
  2799. names and none of the subjectAltName extension names are excluded for
  2800. that name type.
  2801. 7. The other steps in the algorithm for basic path processing involve
  2802. handling the policy extension which is not presently supported in this
  2803. implementation. Instead, if a critical policy extension is found, the
  2804. certificate is rejected as not supported.
  2805. 8. If the certificate is not the first or if its the only certificate in
  2806. the chain (having no parent from the CA store or is self-signed) and it
  2807. has a critical key usage extension, verify that the keyCertSign bit is
  2808. set. If the key usage extension exists, verify that the basic
  2809. constraints extension exists. If the basic constraints extension exists,
  2810. verify that the cA flag is set. If pathLenConstraint is set, ensure that
  2811. the number of certificates that precede in the chain (come earlier
  2812. in the chain as implemented below), excluding the very first in the
  2813. chain (typically the end-entity one), isn't greater than the
  2814. pathLenConstraint. This constraint limits the number of intermediate
  2815. CAs that may appear below a CA before only end-entity certificates
  2816. may be issued. */
  2817. // copy cert chain references to another array to protect against changes
  2818. // in verify callback
  2819. chain = chain.slice(0);
  2820. var certs = chain.slice(0);
  2821. // get current date
  2822. var now = new Date();
  2823. // verify each cert in the chain using its parent, where the parent
  2824. // is either the next in the chain or from the CA store
  2825. var first = true;
  2826. var error = null;
  2827. var depth = 0;
  2828. do {
  2829. var cert = chain.shift();
  2830. var parent = null;
  2831. var selfSigned = false;
  2832. // 1. check valid time
  2833. if(now < cert.validity.notBefore || now > cert.validity.notAfter) {
  2834. error = {
  2835. message: 'Certificate is not valid yet or has expired.',
  2836. error: pki.certificateError.certificate_expired,
  2837. notBefore: cert.validity.notBefore,
  2838. notAfter: cert.validity.notAfter,
  2839. now: now
  2840. };
  2841. }
  2842. // 2. verify with parent from chain or CA store
  2843. if(error === null) {
  2844. parent = chain[0] || caStore.getIssuer(cert);
  2845. if(parent === null) {
  2846. // check for self-signed cert
  2847. if(cert.isIssuer(cert)) {
  2848. selfSigned = true;
  2849. parent = cert;
  2850. }
  2851. }
  2852. if(parent) {
  2853. // FIXME: current CA store implementation might have multiple
  2854. // certificates where the issuer can't be determined from the
  2855. // certificate (happens rarely with, eg: old certificates) so normalize
  2856. // by always putting parents into an array
  2857. // TODO: there's may be an extreme degenerate case currently uncovered
  2858. // where an old intermediate certificate seems to have a matching parent
  2859. // but none of the parents actually verify ... but the intermediate
  2860. // is in the CA and it should pass this check; needs investigation
  2861. var parents = parent;
  2862. if(!forge.util.isArray(parents)) {
  2863. parents = [parents];
  2864. }
  2865. // try to verify with each possible parent (typically only one)
  2866. var verified = false;
  2867. while(!verified && parents.length > 0) {
  2868. parent = parents.shift();
  2869. try {
  2870. verified = parent.verify(cert);
  2871. } catch(ex) {
  2872. // failure to verify, don't care why, try next one
  2873. }
  2874. }
  2875. if(!verified) {
  2876. error = {
  2877. message: 'Certificate signature is invalid.',
  2878. error: pki.certificateError.bad_certificate
  2879. };
  2880. }
  2881. }
  2882. if(error === null && (!parent || selfSigned) &&
  2883. !caStore.hasCertificate(cert)) {
  2884. // no parent issuer and certificate itself is not trusted
  2885. error = {
  2886. message: 'Certificate is not trusted.',
  2887. error: pki.certificateError.unknown_ca
  2888. };
  2889. }
  2890. }
  2891. // TODO: 3. check revoked
  2892. // 4. check for matching issuer/subject
  2893. if(error === null && parent && !cert.isIssuer(parent)) {
  2894. // parent is not issuer
  2895. error = {
  2896. message: 'Certificate issuer is invalid.',
  2897. error: pki.certificateError.bad_certificate
  2898. };
  2899. }
  2900. // 5. TODO: check names with permitted names tree
  2901. // 6. TODO: check names against excluded names tree
  2902. // 7. check for unsupported critical extensions
  2903. if(error === null) {
  2904. // supported extensions
  2905. var se = {
  2906. keyUsage: true,
  2907. basicConstraints: true
  2908. };
  2909. for(var i = 0; error === null && i < cert.extensions.length; ++i) {
  2910. var ext = cert.extensions[i];
  2911. if(ext.critical && !(ext.name in se)) {
  2912. error = {
  2913. message:
  2914. 'Certificate has an unsupported critical extension.',
  2915. error: pki.certificateError.unsupported_certificate
  2916. };
  2917. }
  2918. }
  2919. }
  2920. // 8. check for CA if cert is not first or is the only certificate
  2921. // remaining in chain with no parent or is self-signed
  2922. if(error === null &&
  2923. (!first || (chain.length === 0 && (!parent || selfSigned)))) {
  2924. // first check keyUsage extension and then basic constraints
  2925. var bcExt = cert.getExtension('basicConstraints');
  2926. var keyUsageExt = cert.getExtension('keyUsage');
  2927. if(keyUsageExt !== null) {
  2928. // keyCertSign must be true and there must be a basic
  2929. // constraints extension
  2930. if(!keyUsageExt.keyCertSign || bcExt === null) {
  2931. // bad certificate
  2932. error = {
  2933. message:
  2934. 'Certificate keyUsage or basicConstraints conflict ' +
  2935. 'or indicate that the certificate is not a CA. ' +
  2936. 'If the certificate is the only one in the chain or ' +
  2937. 'isn\'t the first then the certificate must be a ' +
  2938. 'valid CA.',
  2939. error: pki.certificateError.bad_certificate
  2940. };
  2941. }
  2942. }
  2943. // basic constraints cA flag must be set
  2944. if(error === null && bcExt !== null && !bcExt.cA) {
  2945. // bad certificate
  2946. error = {
  2947. message:
  2948. 'Certificate basicConstraints indicates the certificate ' +
  2949. 'is not a CA.',
  2950. error: pki.certificateError.bad_certificate
  2951. };
  2952. }
  2953. // if error is not null and keyUsage is available, then we know it
  2954. // has keyCertSign and there is a basic constraints extension too,
  2955. // which means we can check pathLenConstraint (if it exists)
  2956. if(error === null && keyUsageExt !== null &&
  2957. 'pathLenConstraint' in bcExt) {
  2958. // pathLen is the maximum # of intermediate CA certs that can be
  2959. // found between the current certificate and the end-entity (depth 0)
  2960. // certificate; this number does not include the end-entity (depth 0,
  2961. // last in the chain) even if it happens to be a CA certificate itself
  2962. var pathLen = depth - 1;
  2963. if(pathLen > bcExt.pathLenConstraint) {
  2964. // pathLenConstraint violated, bad certificate
  2965. error = {
  2966. message:
  2967. 'Certificate basicConstraints pathLenConstraint violated.',
  2968. error: pki.certificateError.bad_certificate
  2969. };
  2970. }
  2971. }
  2972. }
  2973. // call application callback
  2974. var vfd = (error === null) ? true : error.error;
  2975. var ret = verify ? verify(vfd, depth, certs) : vfd;
  2976. if(ret === true) {
  2977. // clear any set error
  2978. error = null;
  2979. } else {
  2980. // if passed basic tests, set default message and alert
  2981. if(vfd === true) {
  2982. error = {
  2983. message: 'The application rejected the certificate.',
  2984. error: pki.certificateError.bad_certificate
  2985. };
  2986. }
  2987. // check for custom error info
  2988. if(ret || ret === 0) {
  2989. // set custom message and error
  2990. if(typeof ret === 'object' && !forge.util.isArray(ret)) {
  2991. if(ret.message) {
  2992. error.message = ret.message;
  2993. }
  2994. if(ret.error) {
  2995. error.error = ret.error;
  2996. }
  2997. } else if(typeof ret === 'string') {
  2998. // set custom error
  2999. error.error = ret;
  3000. }
  3001. }
  3002. // throw error
  3003. throw error;
  3004. }
  3005. // no longer first cert in chain
  3006. first = false;
  3007. ++depth;
  3008. } while(chain.length > 0);
  3009. return true;
  3010. };