x509.js 99 KB

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