tls.js 130 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282
  1. /**
  2. * A Javascript implementation of Transport Layer Security (TLS).
  3. *
  4. * @author Dave Longley
  5. *
  6. * Copyright (c) 2009-2014 Digital Bazaar, Inc.
  7. *
  8. * The TLS Handshake Protocol involves the following steps:
  9. *
  10. * - Exchange hello messages to agree on algorithms, exchange random values,
  11. * and check for session resumption.
  12. *
  13. * - Exchange the necessary cryptographic parameters to allow the client and
  14. * server to agree on a premaster secret.
  15. *
  16. * - Exchange certificates and cryptographic information to allow the client
  17. * and server to authenticate themselves.
  18. *
  19. * - Generate a master secret from the premaster secret and exchanged random
  20. * values.
  21. *
  22. * - Provide security parameters to the record layer.
  23. *
  24. * - Allow the client and server to verify that their peer has calculated the
  25. * same security parameters and that the handshake occurred without tampering
  26. * by an attacker.
  27. *
  28. * Up to 4 different messages may be sent during a key exchange. The server
  29. * certificate, the server key exchange, the client certificate, and the
  30. * client key exchange.
  31. *
  32. * A typical handshake (from the client's perspective).
  33. *
  34. * 1. Client sends ClientHello.
  35. * 2. Client receives ServerHello.
  36. * 3. Client receives optional Certificate.
  37. * 4. Client receives optional ServerKeyExchange.
  38. * 5. Client receives ServerHelloDone.
  39. * 6. Client sends optional Certificate.
  40. * 7. Client sends ClientKeyExchange.
  41. * 8. Client sends optional CertificateVerify.
  42. * 9. Client sends ChangeCipherSpec.
  43. * 10. Client sends Finished.
  44. * 11. Client receives ChangeCipherSpec.
  45. * 12. Client receives Finished.
  46. * 13. Client sends/receives application data.
  47. *
  48. * To reuse an existing session:
  49. *
  50. * 1. Client sends ClientHello with session ID for reuse.
  51. * 2. Client receives ServerHello with same session ID if reusing.
  52. * 3. Client receives ChangeCipherSpec message if reusing.
  53. * 4. Client receives Finished.
  54. * 5. Client sends ChangeCipherSpec.
  55. * 6. Client sends Finished.
  56. *
  57. * Note: Client ignores HelloRequest if in the middle of a handshake.
  58. *
  59. * Record Layer:
  60. *
  61. * The record layer fragments information blocks into TLSPlaintext records
  62. * carrying data in chunks of 2^14 bytes or less. Client message boundaries are
  63. * not preserved in the record layer (i.e., multiple client messages of the
  64. * same ContentType MAY be coalesced into a single TLSPlaintext record, or a
  65. * single message MAY be fragmented across several records).
  66. *
  67. * struct {
  68. * uint8 major;
  69. * uint8 minor;
  70. * } ProtocolVersion;
  71. *
  72. * struct {
  73. * ContentType type;
  74. * ProtocolVersion version;
  75. * uint16 length;
  76. * opaque fragment[TLSPlaintext.length];
  77. * } TLSPlaintext;
  78. *
  79. * type:
  80. * The higher-level protocol used to process the enclosed fragment.
  81. *
  82. * version:
  83. * The version of the protocol being employed. TLS Version 1.2 uses version
  84. * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that
  85. * supports multiple versions of TLS may not know what version will be
  86. * employed before it receives the ServerHello.
  87. *
  88. * length:
  89. * The length (in bytes) of the following TLSPlaintext.fragment. The length
  90. * MUST NOT exceed 2^14 = 16384 bytes.
  91. *
  92. * fragment:
  93. * The application data. This data is transparent and treated as an
  94. * independent block to be dealt with by the higher-level protocol specified
  95. * by the type field.
  96. *
  97. * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or
  98. * ChangeCipherSpec content types. Zero-length fragments of Application data
  99. * MAY be sent as they are potentially useful as a traffic analysis
  100. * countermeasure.
  101. *
  102. * Note: Data of different TLS record layer content types MAY be interleaved.
  103. * Application data is generally of lower precedence for transmission than
  104. * other content types. However, records MUST be delivered to the network in
  105. * the same order as they are protected by the record layer. Recipients MUST
  106. * receive and process interleaved application layer traffic during handshakes
  107. * subsequent to the first one on a connection.
  108. *
  109. * struct {
  110. * ContentType type; // same as TLSPlaintext.type
  111. * ProtocolVersion version;// same as TLSPlaintext.version
  112. * uint16 length;
  113. * opaque fragment[TLSCompressed.length];
  114. * } TLSCompressed;
  115. *
  116. * length:
  117. * The length (in bytes) of the following TLSCompressed.fragment.
  118. * The length MUST NOT exceed 2^14 + 1024.
  119. *
  120. * fragment:
  121. * The compressed form of TLSPlaintext.fragment.
  122. *
  123. * Note: A CompressionMethod.null operation is an identity operation; no fields
  124. * are altered. In this implementation, since no compression is supported,
  125. * uncompressed records are always the same as compressed records.
  126. *
  127. * Encryption Information:
  128. *
  129. * The encryption and MAC functions translate a TLSCompressed structure into a
  130. * TLSCiphertext. The decryption functions reverse the process. The MAC of the
  131. * record also includes a sequence number so that missing, extra, or repeated
  132. * messages are detectable.
  133. *
  134. * struct {
  135. * ContentType type;
  136. * ProtocolVersion version;
  137. * uint16 length;
  138. * select (SecurityParameters.cipher_type) {
  139. * case stream: GenericStreamCipher;
  140. * case block: GenericBlockCipher;
  141. * case aead: GenericAEADCipher;
  142. * } fragment;
  143. * } TLSCiphertext;
  144. *
  145. * type:
  146. * The type field is identical to TLSCompressed.type.
  147. *
  148. * version:
  149. * The version field is identical to TLSCompressed.version.
  150. *
  151. * length:
  152. * The length (in bytes) of the following TLSCiphertext.fragment.
  153. * The length MUST NOT exceed 2^14 + 2048.
  154. *
  155. * fragment:
  156. * The encrypted form of TLSCompressed.fragment, with the MAC.
  157. *
  158. * Note: Only CBC Block Ciphers are supported by this implementation.
  159. *
  160. * The TLSCompressed.fragment structures are converted to/from block
  161. * TLSCiphertext.fragment structures.
  162. *
  163. * struct {
  164. * opaque IV[SecurityParameters.record_iv_length];
  165. * block-ciphered struct {
  166. * opaque content[TLSCompressed.length];
  167. * opaque MAC[SecurityParameters.mac_length];
  168. * uint8 padding[GenericBlockCipher.padding_length];
  169. * uint8 padding_length;
  170. * };
  171. * } GenericBlockCipher;
  172. *
  173. * The MAC is generated as described in Section 6.2.3.1.
  174. *
  175. * IV:
  176. * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be
  177. * unpredictable. Note that in versions of TLS prior to 1.1, there was no
  178. * IV field, and the last ciphertext block of the previous record (the "CBC
  179. * residue") was used as the IV. This was changed to prevent the attacks
  180. * described in [CBCATT]. For block ciphers, the IV length is of length
  181. * SecurityParameters.record_iv_length, which is equal to the
  182. * SecurityParameters.block_size.
  183. *
  184. * padding:
  185. * Padding that is added to force the length of the plaintext to be an
  186. * integral multiple of the block cipher's block length. The padding MAY be
  187. * any length up to 255 bytes, as long as it results in the
  188. * TLSCiphertext.length being an integral multiple of the block length.
  189. * Lengths longer than necessary might be desirable to frustrate attacks on
  190. * a protocol that are based on analysis of the lengths of exchanged
  191. * messages. Each uint8 in the padding data vector MUST be filled with the
  192. * padding length value. The receiver MUST check this padding and MUST use
  193. * the bad_record_mac alert to indicate padding errors.
  194. *
  195. * padding_length:
  196. * The padding length MUST be such that the total size of the
  197. * GenericBlockCipher structure is a multiple of the cipher's block length.
  198. * Legal values range from zero to 255, inclusive. This length specifies the
  199. * length of the padding field exclusive of the padding_length field itself.
  200. *
  201. * The encrypted data length (TLSCiphertext.length) is one more than the sum of
  202. * SecurityParameters.block_length, TLSCompressed.length,
  203. * SecurityParameters.mac_length, and padding_length.
  204. *
  205. * Example: If the block length is 8 bytes, the content length
  206. * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the
  207. * length before padding is 82 bytes (this does not include the IV. Thus, the
  208. * padding length modulo 8 must be equal to 6 in order to make the total length
  209. * an even multiple of 8 bytes (the block length). The padding length can be
  210. * 6, 14, 22, and so on, through 254. If the padding length were the minimum
  211. * necessary, 6, the padding would be 6 bytes, each containing the value 6.
  212. * Thus, the last 8 octets of the GenericBlockCipher before block encryption
  213. * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC.
  214. *
  215. * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical
  216. * that the entire plaintext of the record be known before any ciphertext is
  217. * transmitted. Otherwise, it is possible for the attacker to mount the attack
  218. * described in [CBCATT].
  219. *
  220. * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing
  221. * attack on CBC padding based on the time required to compute the MAC. In
  222. * order to defend against this attack, implementations MUST ensure that
  223. * record processing time is essentially the same whether or not the padding
  224. * is correct. In general, the best way to do this is to compute the MAC even
  225. * if the padding is incorrect, and only then reject the packet. For instance,
  226. * if the pad appears to be incorrect, the implementation might assume a
  227. * zero-length pad and then compute the MAC. This leaves a small timing
  228. * channel, since MAC performance depends, to some extent, on the size of the
  229. * data fragment, but it is not believed to be large enough to be exploitable,
  230. * due to the large block size of existing MACs and the small size of the
  231. * timing signal.
  232. */
  233. var forge = require('./forge');
  234. require('./asn1');
  235. require('./hmac');
  236. require('./md5');
  237. require('./pem');
  238. require('./pki');
  239. require('./random');
  240. require('./sha1');
  241. require('./util');
  242. /**
  243. * Generates pseudo random bytes by mixing the result of two hash functions,
  244. * MD5 and SHA-1.
  245. *
  246. * prf_TLS1(secret, label, seed) =
  247. * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed);
  248. *
  249. * Each P_hash function functions as follows:
  250. *
  251. * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
  252. * HMAC_hash(secret, A(2) + seed) +
  253. * HMAC_hash(secret, A(3) + seed) + ...
  254. * A() is defined as:
  255. * A(0) = seed
  256. * A(i) = HMAC_hash(secret, A(i-1))
  257. *
  258. * The '+' operator denotes concatenation.
  259. *
  260. * As many iterations A(N) as are needed are performed to generate enough
  261. * pseudo random byte output. If an iteration creates more data than is
  262. * necessary, then it is truncated.
  263. *
  264. * Therefore:
  265. * A(1) = HMAC_hash(secret, A(0))
  266. * = HMAC_hash(secret, seed)
  267. * A(2) = HMAC_hash(secret, A(1))
  268. * = HMAC_hash(secret, HMAC_hash(secret, seed))
  269. *
  270. * Therefore:
  271. * P_hash(secret, seed) =
  272. * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) +
  273. * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) +
  274. * ...
  275. *
  276. * Therefore:
  277. * P_hash(secret, seed) =
  278. * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) +
  279. * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) +
  280. * ...
  281. *
  282. * @param secret the secret to use.
  283. * @param label the label to use.
  284. * @param seed the seed value to use.
  285. * @param length the number of bytes to generate.
  286. *
  287. * @return the pseudo random bytes in a byte buffer.
  288. */
  289. var prf_TLS1 = function(secret, label, seed, length) {
  290. var rval = forge.util.createBuffer();
  291. /* For TLS 1.0, the secret is split in half, into two secrets of equal
  292. length. If the secret has an odd length then the last byte of the first
  293. half will be the same as the first byte of the second. The length of the
  294. two secrets is half of the secret rounded up. */
  295. var idx = (secret.length >> 1);
  296. var slen = idx + (secret.length & 1);
  297. var s1 = secret.substr(0, slen);
  298. var s2 = secret.substr(idx, slen);
  299. var ai = forge.util.createBuffer();
  300. var hmac = forge.hmac.create();
  301. seed = label + seed;
  302. // determine the number of iterations that must be performed to generate
  303. // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20
  304. var md5itr = Math.ceil(length / 16);
  305. var sha1itr = Math.ceil(length / 20);
  306. // do md5 iterations
  307. hmac.start('MD5', s1);
  308. var md5bytes = forge.util.createBuffer();
  309. ai.putBytes(seed);
  310. for(var i = 0; i < md5itr; ++i) {
  311. // HMAC_hash(secret, A(i-1))
  312. hmac.start(null, null);
  313. hmac.update(ai.getBytes());
  314. ai.putBuffer(hmac.digest());
  315. // HMAC_hash(secret, A(i) + seed)
  316. hmac.start(null, null);
  317. hmac.update(ai.bytes() + seed);
  318. md5bytes.putBuffer(hmac.digest());
  319. }
  320. // do sha1 iterations
  321. hmac.start('SHA1', s2);
  322. var sha1bytes = forge.util.createBuffer();
  323. ai.clear();
  324. ai.putBytes(seed);
  325. for(var i = 0; i < sha1itr; ++i) {
  326. // HMAC_hash(secret, A(i-1))
  327. hmac.start(null, null);
  328. hmac.update(ai.getBytes());
  329. ai.putBuffer(hmac.digest());
  330. // HMAC_hash(secret, A(i) + seed)
  331. hmac.start(null, null);
  332. hmac.update(ai.bytes() + seed);
  333. sha1bytes.putBuffer(hmac.digest());
  334. }
  335. // XOR the md5 bytes with the sha1 bytes
  336. rval.putBytes(forge.util.xorBytes(
  337. md5bytes.getBytes(), sha1bytes.getBytes(), length));
  338. return rval;
  339. };
  340. /**
  341. * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2.
  342. *
  343. * @param secret the secret to use.
  344. * @param label the label to use.
  345. * @param seed the seed value to use.
  346. * @param length the number of bytes to generate.
  347. *
  348. * @return the pseudo random bytes in a byte buffer.
  349. */
  350. var prf_sha256 = function(secret, label, seed, length) {
  351. // FIXME: implement me for TLS 1.2
  352. };
  353. /**
  354. * Gets a MAC for a record using the SHA-1 hash algorithm.
  355. *
  356. * @param key the mac key.
  357. * @param state the sequence number (array of two 32-bit integers).
  358. * @param record the record.
  359. *
  360. * @return the sha-1 hash (20 bytes) for the given record.
  361. */
  362. var hmac_sha1 = function(key, seqNum, record) {
  363. /* MAC is computed like so:
  364. HMAC_hash(
  365. key, seqNum +
  366. TLSCompressed.type +
  367. TLSCompressed.version +
  368. TLSCompressed.length +
  369. TLSCompressed.fragment)
  370. */
  371. var hmac = forge.hmac.create();
  372. hmac.start('SHA1', key);
  373. var b = forge.util.createBuffer();
  374. b.putInt32(seqNum[0]);
  375. b.putInt32(seqNum[1]);
  376. b.putByte(record.type);
  377. b.putByte(record.version.major);
  378. b.putByte(record.version.minor);
  379. b.putInt16(record.length);
  380. b.putBytes(record.fragment.bytes());
  381. hmac.update(b.getBytes());
  382. return hmac.digest().getBytes();
  383. };
  384. /**
  385. * Compresses the TLSPlaintext record into a TLSCompressed record using the
  386. * deflate algorithm.
  387. *
  388. * @param c the TLS connection.
  389. * @param record the TLSPlaintext record to compress.
  390. * @param s the ConnectionState to use.
  391. *
  392. * @return true on success, false on failure.
  393. */
  394. var deflate = function(c, record, s) {
  395. var rval = false;
  396. try {
  397. var bytes = c.deflate(record.fragment.getBytes());
  398. record.fragment = forge.util.createBuffer(bytes);
  399. record.length = bytes.length;
  400. rval = true;
  401. } catch(ex) {
  402. // deflate error, fail out
  403. }
  404. return rval;
  405. };
  406. /**
  407. * Decompresses the TLSCompressed record into a TLSPlaintext record using the
  408. * deflate algorithm.
  409. *
  410. * @param c the TLS connection.
  411. * @param record the TLSCompressed record to decompress.
  412. * @param s the ConnectionState to use.
  413. *
  414. * @return true on success, false on failure.
  415. */
  416. var inflate = function(c, record, s) {
  417. var rval = false;
  418. try {
  419. var bytes = c.inflate(record.fragment.getBytes());
  420. record.fragment = forge.util.createBuffer(bytes);
  421. record.length = bytes.length;
  422. rval = true;
  423. } catch(ex) {
  424. // inflate error, fail out
  425. }
  426. return rval;
  427. };
  428. /**
  429. * Reads a TLS variable-length vector from a byte buffer.
  430. *
  431. * Variable-length vectors are defined by specifying a subrange of legal
  432. * lengths, inclusively, using the notation <floor..ceiling>. When these are
  433. * encoded, the actual length precedes the vector's contents in the byte
  434. * stream. The length will be in the form of a number consuming as many bytes
  435. * as required to hold the vector's specified maximum (ceiling) length. A
  436. * variable-length vector with an actual length field of zero is referred to
  437. * as an empty vector.
  438. *
  439. * @param b the byte buffer.
  440. * @param lenBytes the number of bytes required to store the length.
  441. *
  442. * @return the resulting byte buffer.
  443. */
  444. var readVector = function(b, lenBytes) {
  445. var len = 0;
  446. switch(lenBytes) {
  447. case 1:
  448. len = b.getByte();
  449. break;
  450. case 2:
  451. len = b.getInt16();
  452. break;
  453. case 3:
  454. len = b.getInt24();
  455. break;
  456. case 4:
  457. len = b.getInt32();
  458. break;
  459. }
  460. // read vector bytes into a new buffer
  461. return forge.util.createBuffer(b.getBytes(len));
  462. };
  463. /**
  464. * Writes a TLS variable-length vector to a byte buffer.
  465. *
  466. * @param b the byte buffer.
  467. * @param lenBytes the number of bytes required to store the length.
  468. * @param v the byte buffer vector.
  469. */
  470. var writeVector = function(b, lenBytes, v) {
  471. // encode length at the start of the vector, where the number of bytes for
  472. // the length is the maximum number of bytes it would take to encode the
  473. // vector's ceiling
  474. b.putInt(v.length(), lenBytes << 3);
  475. b.putBuffer(v);
  476. };
  477. /**
  478. * The tls implementation.
  479. */
  480. var tls = {};
  481. /**
  482. * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and
  483. * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time
  484. * of this implementation so TLS 1.0 was implemented instead.
  485. */
  486. tls.Versions = {
  487. TLS_1_0: {major: 3, minor: 1},
  488. TLS_1_1: {major: 3, minor: 2},
  489. TLS_1_2: {major: 3, minor: 3}
  490. };
  491. tls.SupportedVersions = [
  492. tls.Versions.TLS_1_1,
  493. tls.Versions.TLS_1_0
  494. ];
  495. tls.Version = tls.SupportedVersions[0];
  496. /**
  497. * Maximum fragment size. True maximum is 16384, but we fragment before that
  498. * to allow for unusual small increases during compression.
  499. */
  500. tls.MaxFragment = 16384 - 1024;
  501. /**
  502. * Whether this entity is considered the "client" or "server".
  503. * enum { server, client } ConnectionEnd;
  504. */
  505. tls.ConnectionEnd = {
  506. server: 0,
  507. client: 1
  508. };
  509. /**
  510. * Pseudo-random function algorithm used to generate keys from the master
  511. * secret.
  512. * enum { tls_prf_sha256 } PRFAlgorithm;
  513. */
  514. tls.PRFAlgorithm = {
  515. tls_prf_sha256: 0
  516. };
  517. /**
  518. * Bulk encryption algorithms.
  519. * enum { null, rc4, des3, aes } BulkCipherAlgorithm;
  520. */
  521. tls.BulkCipherAlgorithm = {
  522. none: null,
  523. rc4: 0,
  524. des3: 1,
  525. aes: 2
  526. };
  527. /**
  528. * Cipher types.
  529. * enum { stream, block, aead } CipherType;
  530. */
  531. tls.CipherType = {
  532. stream: 0,
  533. block: 1,
  534. aead: 2
  535. };
  536. /**
  537. * MAC (Message Authentication Code) algorithms.
  538. * enum { null, hmac_md5, hmac_sha1, hmac_sha256,
  539. * hmac_sha384, hmac_sha512} MACAlgorithm;
  540. */
  541. tls.MACAlgorithm = {
  542. none: null,
  543. hmac_md5: 0,
  544. hmac_sha1: 1,
  545. hmac_sha256: 2,
  546. hmac_sha384: 3,
  547. hmac_sha512: 4
  548. };
  549. /**
  550. * Compression algorithms.
  551. * enum { null(0), deflate(1), (255) } CompressionMethod;
  552. */
  553. tls.CompressionMethod = {
  554. none: 0,
  555. deflate: 1
  556. };
  557. /**
  558. * TLS record content types.
  559. * enum {
  560. * change_cipher_spec(20), alert(21), handshake(22),
  561. * application_data(23), (255)
  562. * } ContentType;
  563. */
  564. tls.ContentType = {
  565. change_cipher_spec: 20,
  566. alert: 21,
  567. handshake: 22,
  568. application_data: 23,
  569. heartbeat: 24
  570. };
  571. /**
  572. * TLS handshake types.
  573. * enum {
  574. * hello_request(0), client_hello(1), server_hello(2),
  575. * certificate(11), server_key_exchange (12),
  576. * certificate_request(13), server_hello_done(14),
  577. * certificate_verify(15), client_key_exchange(16),
  578. * finished(20), (255)
  579. * } HandshakeType;
  580. */
  581. tls.HandshakeType = {
  582. hello_request: 0,
  583. client_hello: 1,
  584. server_hello: 2,
  585. certificate: 11,
  586. server_key_exchange: 12,
  587. certificate_request: 13,
  588. server_hello_done: 14,
  589. certificate_verify: 15,
  590. client_key_exchange: 16,
  591. finished: 20
  592. };
  593. /**
  594. * TLS Alert Protocol.
  595. *
  596. * enum { warning(1), fatal(2), (255) } AlertLevel;
  597. *
  598. * enum {
  599. * close_notify(0),
  600. * unexpected_message(10),
  601. * bad_record_mac(20),
  602. * decryption_failed(21),
  603. * record_overflow(22),
  604. * decompression_failure(30),
  605. * handshake_failure(40),
  606. * bad_certificate(42),
  607. * unsupported_certificate(43),
  608. * certificate_revoked(44),
  609. * certificate_expired(45),
  610. * certificate_unknown(46),
  611. * illegal_parameter(47),
  612. * unknown_ca(48),
  613. * access_denied(49),
  614. * decode_error(50),
  615. * decrypt_error(51),
  616. * export_restriction(60),
  617. * protocol_version(70),
  618. * insufficient_security(71),
  619. * internal_error(80),
  620. * user_canceled(90),
  621. * no_renegotiation(100),
  622. * (255)
  623. * } AlertDescription;
  624. *
  625. * struct {
  626. * AlertLevel level;
  627. * AlertDescription description;
  628. * } Alert;
  629. */
  630. tls.Alert = {};
  631. tls.Alert.Level = {
  632. warning: 1,
  633. fatal: 2
  634. };
  635. tls.Alert.Description = {
  636. close_notify: 0,
  637. unexpected_message: 10,
  638. bad_record_mac: 20,
  639. decryption_failed: 21,
  640. record_overflow: 22,
  641. decompression_failure: 30,
  642. handshake_failure: 40,
  643. bad_certificate: 42,
  644. unsupported_certificate: 43,
  645. certificate_revoked: 44,
  646. certificate_expired: 45,
  647. certificate_unknown: 46,
  648. illegal_parameter: 47,
  649. unknown_ca: 48,
  650. access_denied: 49,
  651. decode_error: 50,
  652. decrypt_error: 51,
  653. export_restriction: 60,
  654. protocol_version: 70,
  655. insufficient_security: 71,
  656. internal_error: 80,
  657. user_canceled: 90,
  658. no_renegotiation: 100
  659. };
  660. /**
  661. * TLS Heartbeat Message types.
  662. * enum {
  663. * heartbeat_request(1),
  664. * heartbeat_response(2),
  665. * (255)
  666. * } HeartbeatMessageType;
  667. */
  668. tls.HeartbeatMessageType = {
  669. heartbeat_request: 1,
  670. heartbeat_response: 2
  671. };
  672. /**
  673. * Supported cipher suites.
  674. */
  675. tls.CipherSuites = {};
  676. /**
  677. * Gets a supported cipher suite from its 2 byte ID.
  678. *
  679. * @param twoBytes two bytes in a string.
  680. *
  681. * @return the matching supported cipher suite or null.
  682. */
  683. tls.getCipherSuite = function(twoBytes) {
  684. var rval = null;
  685. for(var key in tls.CipherSuites) {
  686. var cs = tls.CipherSuites[key];
  687. if(cs.id[0] === twoBytes.charCodeAt(0) &&
  688. cs.id[1] === twoBytes.charCodeAt(1)) {
  689. rval = cs;
  690. break;
  691. }
  692. }
  693. return rval;
  694. };
  695. /**
  696. * Called when an unexpected record is encountered.
  697. *
  698. * @param c the connection.
  699. * @param record the record.
  700. */
  701. tls.handleUnexpected = function(c, record) {
  702. // if connection is client and closed, ignore unexpected messages
  703. var ignore = (!c.open && c.entity === tls.ConnectionEnd.client);
  704. if(!ignore) {
  705. c.error(c, {
  706. message: 'Unexpected message. Received TLS record out of order.',
  707. send: true,
  708. alert: {
  709. level: tls.Alert.Level.fatal,
  710. description: tls.Alert.Description.unexpected_message
  711. }
  712. });
  713. }
  714. };
  715. /**
  716. * Called when a client receives a HelloRequest record.
  717. *
  718. * @param c the connection.
  719. * @param record the record.
  720. * @param length the length of the handshake message.
  721. */
  722. tls.handleHelloRequest = function(c, record, length) {
  723. // ignore renegotiation requests from the server during a handshake, but
  724. // if handshaking, send a warning alert that renegotation is denied
  725. if(!c.handshaking && c.handshakes > 0) {
  726. // send alert warning
  727. tls.queue(c, tls.createAlert(c, {
  728. level: tls.Alert.Level.warning,
  729. description: tls.Alert.Description.no_renegotiation
  730. }));
  731. tls.flush(c);
  732. }
  733. // continue
  734. c.process();
  735. };
  736. /**
  737. * Parses a hello message from a ClientHello or ServerHello record.
  738. *
  739. * @param record the record to parse.
  740. *
  741. * @return the parsed message.
  742. */
  743. tls.parseHelloMessage = function(c, record, length) {
  744. var msg = null;
  745. var client = (c.entity === tls.ConnectionEnd.client);
  746. // minimum of 38 bytes in message
  747. if(length < 38) {
  748. c.error(c, {
  749. message: client ?
  750. 'Invalid ServerHello message. Message too short.' :
  751. 'Invalid ClientHello message. Message too short.',
  752. send: true,
  753. alert: {
  754. level: tls.Alert.Level.fatal,
  755. description: tls.Alert.Description.illegal_parameter
  756. }
  757. });
  758. } else {
  759. // use 'remaining' to calculate # of remaining bytes in the message
  760. var b = record.fragment;
  761. var remaining = b.length();
  762. msg = {
  763. version: {
  764. major: b.getByte(),
  765. minor: b.getByte()
  766. },
  767. random: forge.util.createBuffer(b.getBytes(32)),
  768. session_id: readVector(b, 1),
  769. extensions: []
  770. };
  771. if(client) {
  772. msg.cipher_suite = b.getBytes(2);
  773. msg.compression_method = b.getByte();
  774. } else {
  775. msg.cipher_suites = readVector(b, 2);
  776. msg.compression_methods = readVector(b, 1);
  777. }
  778. // read extensions if there are any bytes left in the message
  779. remaining = length - (remaining - b.length());
  780. if(remaining > 0) {
  781. // parse extensions
  782. var exts = readVector(b, 2);
  783. while(exts.length() > 0) {
  784. msg.extensions.push({
  785. type: [exts.getByte(), exts.getByte()],
  786. data: readVector(exts, 2)
  787. });
  788. }
  789. // TODO: make extension support modular
  790. if(!client) {
  791. for(var i = 0; i < msg.extensions.length; ++i) {
  792. var ext = msg.extensions[i];
  793. // support SNI extension
  794. if(ext.type[0] === 0x00 && ext.type[1] === 0x00) {
  795. // get server name list
  796. var snl = readVector(ext.data, 2);
  797. while(snl.length() > 0) {
  798. // read server name type
  799. var snType = snl.getByte();
  800. // only HostName type (0x00) is known, break out if
  801. // another type is detected
  802. if(snType !== 0x00) {
  803. break;
  804. }
  805. // add host name to server name list
  806. c.session.extensions.server_name.serverNameList.push(
  807. readVector(snl, 2).getBytes());
  808. }
  809. }
  810. }
  811. }
  812. }
  813. // version already set, do not allow version change
  814. if(c.session.version) {
  815. if(msg.version.major !== c.session.version.major ||
  816. msg.version.minor !== c.session.version.minor) {
  817. return c.error(c, {
  818. message: 'TLS version change is disallowed during renegotiation.',
  819. send: true,
  820. alert: {
  821. level: tls.Alert.Level.fatal,
  822. description: tls.Alert.Description.protocol_version
  823. }
  824. });
  825. }
  826. }
  827. // get the chosen (ServerHello) cipher suite
  828. if(client) {
  829. // FIXME: should be checking configured acceptable cipher suites
  830. c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite);
  831. } else {
  832. // get a supported preferred (ClientHello) cipher suite
  833. // choose the first supported cipher suite
  834. var tmp = forge.util.createBuffer(msg.cipher_suites.bytes());
  835. while(tmp.length() > 0) {
  836. // FIXME: should be checking configured acceptable suites
  837. // cipher suites take up 2 bytes
  838. c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2));
  839. if(c.session.cipherSuite !== null) {
  840. break;
  841. }
  842. }
  843. }
  844. // cipher suite not supported
  845. if(c.session.cipherSuite === null) {
  846. return c.error(c, {
  847. message: 'No cipher suites in common.',
  848. send: true,
  849. alert: {
  850. level: tls.Alert.Level.fatal,
  851. description: tls.Alert.Description.handshake_failure
  852. },
  853. cipherSuite: forge.util.bytesToHex(msg.cipher_suite)
  854. });
  855. }
  856. // TODO: handle compression methods
  857. if(client) {
  858. c.session.compressionMethod = msg.compression_method;
  859. } else {
  860. // no compression
  861. c.session.compressionMethod = tls.CompressionMethod.none;
  862. }
  863. }
  864. return msg;
  865. };
  866. /**
  867. * Creates security parameters for the given connection based on the given
  868. * hello message.
  869. *
  870. * @param c the TLS connection.
  871. * @param msg the hello message.
  872. */
  873. tls.createSecurityParameters = function(c, msg) {
  874. /* Note: security params are from TLS 1.2, some values like prf_algorithm
  875. are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is
  876. used. */
  877. // TODO: handle other options from server when more supported
  878. // get client and server randoms
  879. var client = (c.entity === tls.ConnectionEnd.client);
  880. var msgRandom = msg.random.bytes();
  881. var cRandom = client ? c.session.sp.client_random : msgRandom;
  882. var sRandom = client ? msgRandom : tls.createRandom().getBytes();
  883. // create new security parameters
  884. c.session.sp = {
  885. entity: c.entity,
  886. prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256,
  887. bulk_cipher_algorithm: null,
  888. cipher_type: null,
  889. enc_key_length: null,
  890. block_length: null,
  891. fixed_iv_length: null,
  892. record_iv_length: null,
  893. mac_algorithm: null,
  894. mac_length: null,
  895. mac_key_length: null,
  896. compression_algorithm: c.session.compressionMethod,
  897. pre_master_secret: null,
  898. master_secret: null,
  899. client_random: cRandom,
  900. server_random: sRandom
  901. };
  902. };
  903. /**
  904. * Called when a client receives a ServerHello record.
  905. *
  906. * When a ServerHello message will be sent:
  907. * The server will send this message in response to a client hello message
  908. * when it was able to find an acceptable set of algorithms. If it cannot
  909. * find such a match, it will respond with a handshake failure alert.
  910. *
  911. * uint24 length;
  912. * struct {
  913. * ProtocolVersion server_version;
  914. * Random random;
  915. * SessionID session_id;
  916. * CipherSuite cipher_suite;
  917. * CompressionMethod compression_method;
  918. * select(extensions_present) {
  919. * case false:
  920. * struct {};
  921. * case true:
  922. * Extension extensions<0..2^16-1>;
  923. * };
  924. * } ServerHello;
  925. *
  926. * @param c the connection.
  927. * @param record the record.
  928. * @param length the length of the handshake message.
  929. */
  930. tls.handleServerHello = function(c, record, length) {
  931. var msg = tls.parseHelloMessage(c, record, length);
  932. if(c.fail) {
  933. return;
  934. }
  935. // ensure server version is compatible
  936. if(msg.version.minor <= c.version.minor) {
  937. c.version.minor = msg.version.minor;
  938. } else {
  939. return c.error(c, {
  940. message: 'Incompatible TLS version.',
  941. send: true,
  942. alert: {
  943. level: tls.Alert.Level.fatal,
  944. description: tls.Alert.Description.protocol_version
  945. }
  946. });
  947. }
  948. // indicate session version has been set
  949. c.session.version = c.version;
  950. // get the session ID from the message
  951. var sessionId = msg.session_id.bytes();
  952. // if the session ID is not blank and matches the cached one, resume
  953. // the session
  954. if(sessionId.length > 0 && sessionId === c.session.id) {
  955. // resuming session, expect a ChangeCipherSpec next
  956. c.expect = SCC;
  957. c.session.resuming = true;
  958. // get new server random
  959. c.session.sp.server_random = msg.random.bytes();
  960. } else {
  961. // not resuming, expect a server Certificate message next
  962. c.expect = SCE;
  963. c.session.resuming = false;
  964. // create new security parameters
  965. tls.createSecurityParameters(c, msg);
  966. }
  967. // set new session ID
  968. c.session.id = sessionId;
  969. // continue
  970. c.process();
  971. };
  972. /**
  973. * Called when a server receives a ClientHello record.
  974. *
  975. * When a ClientHello message will be sent:
  976. * When a client first connects to a server it is required to send the
  977. * client hello as its first message. The client can also send a client
  978. * hello in response to a hello request or on its own initiative in order
  979. * to renegotiate the security parameters in an existing connection.
  980. *
  981. * @param c the connection.
  982. * @param record the record.
  983. * @param length the length of the handshake message.
  984. */
  985. tls.handleClientHello = function(c, record, length) {
  986. var msg = tls.parseHelloMessage(c, record, length);
  987. if(c.fail) {
  988. return;
  989. }
  990. // get the session ID from the message
  991. var sessionId = msg.session_id.bytes();
  992. // see if the given session ID is in the cache
  993. var session = null;
  994. if(c.sessionCache) {
  995. session = c.sessionCache.getSession(sessionId);
  996. if(session === null) {
  997. // session ID not found
  998. sessionId = '';
  999. } else if(session.version.major !== msg.version.major ||
  1000. session.version.minor > msg.version.minor) {
  1001. // if session version is incompatible with client version, do not resume
  1002. session = null;
  1003. sessionId = '';
  1004. }
  1005. }
  1006. // no session found to resume, generate a new session ID
  1007. if(sessionId.length === 0) {
  1008. sessionId = forge.random.getBytes(32);
  1009. }
  1010. // update session
  1011. c.session.id = sessionId;
  1012. c.session.clientHelloVersion = msg.version;
  1013. c.session.sp = {};
  1014. if(session) {
  1015. // use version and security parameters from resumed session
  1016. c.version = c.session.version = session.version;
  1017. c.session.sp = session.sp;
  1018. } else {
  1019. // use highest compatible minor version
  1020. var version;
  1021. for(var i = 1; i < tls.SupportedVersions.length; ++i) {
  1022. version = tls.SupportedVersions[i];
  1023. if(version.minor <= msg.version.minor) {
  1024. break;
  1025. }
  1026. }
  1027. c.version = {major: version.major, minor: version.minor};
  1028. c.session.version = c.version;
  1029. }
  1030. // if a session is set, resume it
  1031. if(session !== null) {
  1032. // resuming session, expect a ChangeCipherSpec next
  1033. c.expect = CCC;
  1034. c.session.resuming = true;
  1035. // get new client random
  1036. c.session.sp.client_random = msg.random.bytes();
  1037. } else {
  1038. // not resuming, expect a Certificate or ClientKeyExchange
  1039. c.expect = (c.verifyClient !== false) ? CCE : CKE;
  1040. c.session.resuming = false;
  1041. // create new security parameters
  1042. tls.createSecurityParameters(c, msg);
  1043. }
  1044. // connection now open
  1045. c.open = true;
  1046. // queue server hello
  1047. tls.queue(c, tls.createRecord(c, {
  1048. type: tls.ContentType.handshake,
  1049. data: tls.createServerHello(c)
  1050. }));
  1051. if(c.session.resuming) {
  1052. // queue change cipher spec message
  1053. tls.queue(c, tls.createRecord(c, {
  1054. type: tls.ContentType.change_cipher_spec,
  1055. data: tls.createChangeCipherSpec()
  1056. }));
  1057. // create pending state
  1058. c.state.pending = tls.createConnectionState(c);
  1059. // change current write state to pending write state
  1060. c.state.current.write = c.state.pending.write;
  1061. // queue finished
  1062. tls.queue(c, tls.createRecord(c, {
  1063. type: tls.ContentType.handshake,
  1064. data: tls.createFinished(c)
  1065. }));
  1066. } else {
  1067. // queue server certificate
  1068. tls.queue(c, tls.createRecord(c, {
  1069. type: tls.ContentType.handshake,
  1070. data: tls.createCertificate(c)
  1071. }));
  1072. if(!c.fail) {
  1073. // queue server key exchange
  1074. tls.queue(c, tls.createRecord(c, {
  1075. type: tls.ContentType.handshake,
  1076. data: tls.createServerKeyExchange(c)
  1077. }));
  1078. // request client certificate if set
  1079. if(c.verifyClient !== false) {
  1080. // queue certificate request
  1081. tls.queue(c, tls.createRecord(c, {
  1082. type: tls.ContentType.handshake,
  1083. data: tls.createCertificateRequest(c)
  1084. }));
  1085. }
  1086. // queue server hello done
  1087. tls.queue(c, tls.createRecord(c, {
  1088. type: tls.ContentType.handshake,
  1089. data: tls.createServerHelloDone(c)
  1090. }));
  1091. }
  1092. }
  1093. // send records
  1094. tls.flush(c);
  1095. // continue
  1096. c.process();
  1097. };
  1098. /**
  1099. * Called when a client receives a Certificate record.
  1100. *
  1101. * When this message will be sent:
  1102. * The server must send a certificate whenever the agreed-upon key exchange
  1103. * method is not an anonymous one. This message will always immediately
  1104. * follow the server hello message.
  1105. *
  1106. * Meaning of this message:
  1107. * The certificate type must be appropriate for the selected cipher suite's
  1108. * key exchange algorithm, and is generally an X.509v3 certificate. It must
  1109. * contain a key which matches the key exchange method, as follows. Unless
  1110. * otherwise specified, the signing algorithm for the certificate must be
  1111. * the same as the algorithm for the certificate key. Unless otherwise
  1112. * specified, the public key may be of any length.
  1113. *
  1114. * opaque ASN.1Cert<1..2^24-1>;
  1115. * struct {
  1116. * ASN.1Cert certificate_list<1..2^24-1>;
  1117. * } Certificate;
  1118. *
  1119. * @param c the connection.
  1120. * @param record the record.
  1121. * @param length the length of the handshake message.
  1122. */
  1123. tls.handleCertificate = function(c, record, length) {
  1124. // minimum of 3 bytes in message
  1125. if(length < 3) {
  1126. return c.error(c, {
  1127. message: 'Invalid Certificate message. Message too short.',
  1128. send: true,
  1129. alert: {
  1130. level: tls.Alert.Level.fatal,
  1131. description: tls.Alert.Description.illegal_parameter
  1132. }
  1133. });
  1134. }
  1135. var b = record.fragment;
  1136. var msg = {
  1137. certificate_list: readVector(b, 3)
  1138. };
  1139. /* The sender's certificate will be first in the list (chain), each
  1140. subsequent one that follows will certify the previous one, but root
  1141. certificates (self-signed) that specify the certificate authority may
  1142. be omitted under the assumption that clients must already possess it. */
  1143. var cert, asn1;
  1144. var certs = [];
  1145. try {
  1146. while(msg.certificate_list.length() > 0) {
  1147. // each entry in msg.certificate_list is a vector with 3 len bytes
  1148. cert = readVector(msg.certificate_list, 3);
  1149. asn1 = forge.asn1.fromDer(cert);
  1150. cert = forge.pki.certificateFromAsn1(asn1, true);
  1151. certs.push(cert);
  1152. }
  1153. } catch(ex) {
  1154. return c.error(c, {
  1155. message: 'Could not parse certificate list.',
  1156. cause: ex,
  1157. send: true,
  1158. alert: {
  1159. level: tls.Alert.Level.fatal,
  1160. description: tls.Alert.Description.bad_certificate
  1161. }
  1162. });
  1163. }
  1164. // ensure at least 1 certificate was provided if in client-mode
  1165. // or if verifyClient was set to true to require a certificate
  1166. // (as opposed to 'optional')
  1167. var client = (c.entity === tls.ConnectionEnd.client);
  1168. if((client || c.verifyClient === true) && certs.length === 0) {
  1169. // error, no certificate
  1170. c.error(c, {
  1171. message: client ?
  1172. 'No server certificate provided.' :
  1173. 'No client certificate provided.',
  1174. send: true,
  1175. alert: {
  1176. level: tls.Alert.Level.fatal,
  1177. description: tls.Alert.Description.illegal_parameter
  1178. }
  1179. });
  1180. } else if(certs.length === 0) {
  1181. // no certs to verify
  1182. // expect a ServerKeyExchange or ClientKeyExchange message next
  1183. c.expect = client ? SKE : CKE;
  1184. } else {
  1185. // save certificate in session
  1186. if(client) {
  1187. c.session.serverCertificate = certs[0];
  1188. } else {
  1189. c.session.clientCertificate = certs[0];
  1190. }
  1191. if(tls.verifyCertificateChain(c, certs)) {
  1192. // expect a ServerKeyExchange or ClientKeyExchange message next
  1193. c.expect = client ? SKE : CKE;
  1194. }
  1195. }
  1196. // continue
  1197. c.process();
  1198. };
  1199. /**
  1200. * Called when a client receives a ServerKeyExchange record.
  1201. *
  1202. * When this message will be sent:
  1203. * This message will be sent immediately after the server certificate
  1204. * message (or the server hello message, if this is an anonymous
  1205. * negotiation).
  1206. *
  1207. * The server key exchange message is sent by the server only when the
  1208. * server certificate message (if sent) does not contain enough data to
  1209. * allow the client to exchange a premaster secret.
  1210. *
  1211. * Meaning of this message:
  1212. * This message conveys cryptographic information to allow the client to
  1213. * communicate the premaster secret: either an RSA public key to encrypt
  1214. * the premaster secret with, or a Diffie-Hellman public key with which the
  1215. * client can complete a key exchange (with the result being the premaster
  1216. * secret.)
  1217. *
  1218. * enum {
  1219. * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa
  1220. * } KeyExchangeAlgorithm;
  1221. *
  1222. * struct {
  1223. * opaque dh_p<1..2^16-1>;
  1224. * opaque dh_g<1..2^16-1>;
  1225. * opaque dh_Ys<1..2^16-1>;
  1226. * } ServerDHParams;
  1227. *
  1228. * struct {
  1229. * select(KeyExchangeAlgorithm) {
  1230. * case dh_anon:
  1231. * ServerDHParams params;
  1232. * case dhe_dss:
  1233. * case dhe_rsa:
  1234. * ServerDHParams params;
  1235. * digitally-signed struct {
  1236. * opaque client_random[32];
  1237. * opaque server_random[32];
  1238. * ServerDHParams params;
  1239. * } signed_params;
  1240. * case rsa:
  1241. * case dh_dss:
  1242. * case dh_rsa:
  1243. * struct {};
  1244. * };
  1245. * } ServerKeyExchange;
  1246. *
  1247. * @param c the connection.
  1248. * @param record the record.
  1249. * @param length the length of the handshake message.
  1250. */
  1251. tls.handleServerKeyExchange = function(c, record, length) {
  1252. // this implementation only supports RSA, no Diffie-Hellman support
  1253. // so any length > 0 is invalid
  1254. if(length > 0) {
  1255. return c.error(c, {
  1256. message: 'Invalid key parameters. Only RSA is supported.',
  1257. send: true,
  1258. alert: {
  1259. level: tls.Alert.Level.fatal,
  1260. description: tls.Alert.Description.unsupported_certificate
  1261. }
  1262. });
  1263. }
  1264. // expect an optional CertificateRequest message next
  1265. c.expect = SCR;
  1266. // continue
  1267. c.process();
  1268. };
  1269. /**
  1270. * Called when a client receives a ClientKeyExchange record.
  1271. *
  1272. * @param c the connection.
  1273. * @param record the record.
  1274. * @param length the length of the handshake message.
  1275. */
  1276. tls.handleClientKeyExchange = function(c, record, length) {
  1277. // this implementation only supports RSA, no Diffie-Hellman support
  1278. // so any length < 48 is invalid
  1279. if(length < 48) {
  1280. return c.error(c, {
  1281. message: 'Invalid key parameters. Only RSA is supported.',
  1282. send: true,
  1283. alert: {
  1284. level: tls.Alert.Level.fatal,
  1285. description: tls.Alert.Description.unsupported_certificate
  1286. }
  1287. });
  1288. }
  1289. var b = record.fragment;
  1290. var msg = {
  1291. enc_pre_master_secret: readVector(b, 2).getBytes()
  1292. };
  1293. // do rsa decryption
  1294. var privateKey = null;
  1295. if(c.getPrivateKey) {
  1296. try {
  1297. privateKey = c.getPrivateKey(c, c.session.serverCertificate);
  1298. privateKey = forge.pki.privateKeyFromPem(privateKey);
  1299. } catch(ex) {
  1300. c.error(c, {
  1301. message: 'Could not get private key.',
  1302. cause: ex,
  1303. send: true,
  1304. alert: {
  1305. level: tls.Alert.Level.fatal,
  1306. description: tls.Alert.Description.internal_error
  1307. }
  1308. });
  1309. }
  1310. }
  1311. if(privateKey === null) {
  1312. return c.error(c, {
  1313. message: 'No private key set.',
  1314. send: true,
  1315. alert: {
  1316. level: tls.Alert.Level.fatal,
  1317. description: tls.Alert.Description.internal_error
  1318. }
  1319. });
  1320. }
  1321. try {
  1322. // decrypt 48-byte pre-master secret
  1323. var sp = c.session.sp;
  1324. sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);
  1325. // ensure client hello version matches first 2 bytes
  1326. var version = c.session.clientHelloVersion;
  1327. if(version.major !== sp.pre_master_secret.charCodeAt(0) ||
  1328. version.minor !== sp.pre_master_secret.charCodeAt(1)) {
  1329. // error, do not send alert (see BLEI attack below)
  1330. throw new Error('TLS version rollback attack detected.');
  1331. }
  1332. } catch(ex) {
  1333. /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a
  1334. TLS server which is using PKCS#1 encoded RSA, so instead of
  1335. failing here, we generate 48 random bytes and use that as
  1336. the pre-master secret. */
  1337. sp.pre_master_secret = forge.random.getBytes(48);
  1338. }
  1339. // expect a CertificateVerify message if a Certificate was received that
  1340. // does not have fixed Diffie-Hellman params, otherwise expect
  1341. // ChangeCipherSpec
  1342. c.expect = CCC;
  1343. if(c.session.clientCertificate !== null) {
  1344. // only RSA support, so expect CertificateVerify
  1345. // TODO: support Diffie-Hellman
  1346. c.expect = CCV;
  1347. }
  1348. // continue
  1349. c.process();
  1350. };
  1351. /**
  1352. * Called when a client receives a CertificateRequest record.
  1353. *
  1354. * When this message will be sent:
  1355. * A non-anonymous server can optionally request a certificate from the
  1356. * client, if appropriate for the selected cipher suite. This message, if
  1357. * sent, will immediately follow the Server Key Exchange message (if it is
  1358. * sent; otherwise, the Server Certificate message).
  1359. *
  1360. * enum {
  1361. * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
  1362. * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6),
  1363. * fortezza_dms_RESERVED(20), (255)
  1364. * } ClientCertificateType;
  1365. *
  1366. * opaque DistinguishedName<1..2^16-1>;
  1367. *
  1368. * struct {
  1369. * ClientCertificateType certificate_types<1..2^8-1>;
  1370. * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>;
  1371. * DistinguishedName certificate_authorities<0..2^16-1>;
  1372. * } CertificateRequest;
  1373. *
  1374. * @param c the connection.
  1375. * @param record the record.
  1376. * @param length the length of the handshake message.
  1377. */
  1378. tls.handleCertificateRequest = function(c, record, length) {
  1379. // minimum of 3 bytes in message
  1380. if(length < 3) {
  1381. return c.error(c, {
  1382. message: 'Invalid CertificateRequest. Message too short.',
  1383. send: true,
  1384. alert: {
  1385. level: tls.Alert.Level.fatal,
  1386. description: tls.Alert.Description.illegal_parameter
  1387. }
  1388. });
  1389. }
  1390. // TODO: TLS 1.2+ has different format including
  1391. // SignatureAndHashAlgorithm after cert types
  1392. var b = record.fragment;
  1393. var msg = {
  1394. certificate_types: readVector(b, 1),
  1395. certificate_authorities: readVector(b, 2)
  1396. };
  1397. // save certificate request in session
  1398. c.session.certificateRequest = msg;
  1399. // expect a ServerHelloDone message next
  1400. c.expect = SHD;
  1401. // continue
  1402. c.process();
  1403. };
  1404. /**
  1405. * Called when a server receives a CertificateVerify record.
  1406. *
  1407. * @param c the connection.
  1408. * @param record the record.
  1409. * @param length the length of the handshake message.
  1410. */
  1411. tls.handleCertificateVerify = function(c, record, length) {
  1412. if(length < 2) {
  1413. return c.error(c, {
  1414. message: 'Invalid CertificateVerify. Message too short.',
  1415. send: true,
  1416. alert: {
  1417. level: tls.Alert.Level.fatal,
  1418. description: tls.Alert.Description.illegal_parameter
  1419. }
  1420. });
  1421. }
  1422. // rewind to get full bytes for message so it can be manually
  1423. // digested below (special case for CertificateVerify messages because
  1424. // they must be digested *after* handling as opposed to all others)
  1425. var b = record.fragment;
  1426. b.read -= 4;
  1427. var msgBytes = b.bytes();
  1428. b.read += 4;
  1429. var msg = {
  1430. signature: readVector(b, 2).getBytes()
  1431. };
  1432. // TODO: add support for DSA
  1433. // generate data to verify
  1434. var verify = forge.util.createBuffer();
  1435. verify.putBuffer(c.session.md5.digest());
  1436. verify.putBuffer(c.session.sha1.digest());
  1437. verify = verify.getBytes();
  1438. try {
  1439. var cert = c.session.clientCertificate;
  1440. /*b = forge.pki.rsa.decrypt(
  1441. msg.signature, cert.publicKey, true, verify.length);
  1442. if(b !== verify) {*/
  1443. if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) {
  1444. throw new Error('CertificateVerify signature does not match.');
  1445. }
  1446. // digest message now that it has been handled
  1447. c.session.md5.update(msgBytes);
  1448. c.session.sha1.update(msgBytes);
  1449. } catch(ex) {
  1450. return c.error(c, {
  1451. message: 'Bad signature in CertificateVerify.',
  1452. send: true,
  1453. alert: {
  1454. level: tls.Alert.Level.fatal,
  1455. description: tls.Alert.Description.handshake_failure
  1456. }
  1457. });
  1458. }
  1459. // expect ChangeCipherSpec
  1460. c.expect = CCC;
  1461. // continue
  1462. c.process();
  1463. };
  1464. /**
  1465. * Called when a client receives a ServerHelloDone record.
  1466. *
  1467. * When this message will be sent:
  1468. * The server hello done message is sent by the server to indicate the end
  1469. * of the server hello and associated messages. After sending this message
  1470. * the server will wait for a client response.
  1471. *
  1472. * Meaning of this message:
  1473. * This message means that the server is done sending messages to support
  1474. * the key exchange, and the client can proceed with its phase of the key
  1475. * exchange.
  1476. *
  1477. * Upon receipt of the server hello done message the client should verify
  1478. * that the server provided a valid certificate if required and check that
  1479. * the server hello parameters are acceptable.
  1480. *
  1481. * struct {} ServerHelloDone;
  1482. *
  1483. * @param c the connection.
  1484. * @param record the record.
  1485. * @param length the length of the handshake message.
  1486. */
  1487. tls.handleServerHelloDone = function(c, record, length) {
  1488. // len must be 0 bytes
  1489. if(length > 0) {
  1490. return c.error(c, {
  1491. message: 'Invalid ServerHelloDone message. Invalid length.',
  1492. send: true,
  1493. alert: {
  1494. level: tls.Alert.Level.fatal,
  1495. description: tls.Alert.Description.record_overflow
  1496. }
  1497. });
  1498. }
  1499. if(c.serverCertificate === null) {
  1500. // no server certificate was provided
  1501. var error = {
  1502. message: 'No server certificate provided. Not enough security.',
  1503. send: true,
  1504. alert: {
  1505. level: tls.Alert.Level.fatal,
  1506. description: tls.Alert.Description.insufficient_security
  1507. }
  1508. };
  1509. // call application callback
  1510. var depth = 0;
  1511. var ret = c.verify(c, error.alert.description, depth, []);
  1512. if(ret !== true) {
  1513. // check for custom alert info
  1514. if(ret || ret === 0) {
  1515. // set custom message and alert description
  1516. if(typeof ret === 'object' && !forge.util.isArray(ret)) {
  1517. if(ret.message) {
  1518. error.message = ret.message;
  1519. }
  1520. if(ret.alert) {
  1521. error.alert.description = ret.alert;
  1522. }
  1523. } else if(typeof ret === 'number') {
  1524. // set custom alert description
  1525. error.alert.description = ret;
  1526. }
  1527. }
  1528. // send error
  1529. return c.error(c, error);
  1530. }
  1531. }
  1532. // create client certificate message if requested
  1533. if(c.session.certificateRequest !== null) {
  1534. record = tls.createRecord(c, {
  1535. type: tls.ContentType.handshake,
  1536. data: tls.createCertificate(c)
  1537. });
  1538. tls.queue(c, record);
  1539. }
  1540. // create client key exchange message
  1541. record = tls.createRecord(c, {
  1542. type: tls.ContentType.handshake,
  1543. data: tls.createClientKeyExchange(c)
  1544. });
  1545. tls.queue(c, record);
  1546. // expect no messages until the following callback has been called
  1547. c.expect = SER;
  1548. // create callback to handle client signature (for client-certs)
  1549. var callback = function(c, signature) {
  1550. if(c.session.certificateRequest !== null &&
  1551. c.session.clientCertificate !== null) {
  1552. // create certificate verify message
  1553. tls.queue(c, tls.createRecord(c, {
  1554. type: tls.ContentType.handshake,
  1555. data: tls.createCertificateVerify(c, signature)
  1556. }));
  1557. }
  1558. // create change cipher spec message
  1559. tls.queue(c, tls.createRecord(c, {
  1560. type: tls.ContentType.change_cipher_spec,
  1561. data: tls.createChangeCipherSpec()
  1562. }));
  1563. // create pending state
  1564. c.state.pending = tls.createConnectionState(c);
  1565. // change current write state to pending write state
  1566. c.state.current.write = c.state.pending.write;
  1567. // create finished message
  1568. tls.queue(c, tls.createRecord(c, {
  1569. type: tls.ContentType.handshake,
  1570. data: tls.createFinished(c)
  1571. }));
  1572. // expect a server ChangeCipherSpec message next
  1573. c.expect = SCC;
  1574. // send records
  1575. tls.flush(c);
  1576. // continue
  1577. c.process();
  1578. };
  1579. // if there is no certificate request or no client certificate, do
  1580. // callback immediately
  1581. if(c.session.certificateRequest === null ||
  1582. c.session.clientCertificate === null) {
  1583. return callback(c, null);
  1584. }
  1585. // otherwise get the client signature
  1586. tls.getClientSignature(c, callback);
  1587. };
  1588. /**
  1589. * Called when a ChangeCipherSpec record is received.
  1590. *
  1591. * @param c the connection.
  1592. * @param record the record.
  1593. */
  1594. tls.handleChangeCipherSpec = function(c, record) {
  1595. if(record.fragment.getByte() !== 0x01) {
  1596. return c.error(c, {
  1597. message: 'Invalid ChangeCipherSpec message received.',
  1598. send: true,
  1599. alert: {
  1600. level: tls.Alert.Level.fatal,
  1601. description: tls.Alert.Description.illegal_parameter
  1602. }
  1603. });
  1604. }
  1605. // create pending state if:
  1606. // 1. Resuming session in client mode OR
  1607. // 2. NOT resuming session in server mode
  1608. var client = (c.entity === tls.ConnectionEnd.client);
  1609. if((c.session.resuming && client) || (!c.session.resuming && !client)) {
  1610. c.state.pending = tls.createConnectionState(c);
  1611. }
  1612. // change current read state to pending read state
  1613. c.state.current.read = c.state.pending.read;
  1614. // clear pending state if:
  1615. // 1. NOT resuming session in client mode OR
  1616. // 2. resuming a session in server mode
  1617. if((!c.session.resuming && client) || (c.session.resuming && !client)) {
  1618. c.state.pending = null;
  1619. }
  1620. // expect a Finished record next
  1621. c.expect = client ? SFI : CFI;
  1622. // continue
  1623. c.process();
  1624. };
  1625. /**
  1626. * Called when a Finished record is received.
  1627. *
  1628. * When this message will be sent:
  1629. * A finished message is always sent immediately after a change
  1630. * cipher spec message to verify that the key exchange and
  1631. * authentication processes were successful. It is essential that a
  1632. * change cipher spec message be received between the other
  1633. * handshake messages and the Finished message.
  1634. *
  1635. * Meaning of this message:
  1636. * The finished message is the first protected with the just-
  1637. * negotiated algorithms, keys, and secrets. Recipients of finished
  1638. * messages must verify that the contents are correct. Once a side
  1639. * has sent its Finished message and received and validated the
  1640. * Finished message from its peer, it may begin to send and receive
  1641. * application data over the connection.
  1642. *
  1643. * struct {
  1644. * opaque verify_data[verify_data_length];
  1645. * } Finished;
  1646. *
  1647. * verify_data
  1648. * PRF(master_secret, finished_label, Hash(handshake_messages))
  1649. * [0..verify_data_length-1];
  1650. *
  1651. * finished_label
  1652. * For Finished messages sent by the client, the string
  1653. * "client finished". For Finished messages sent by the server, the
  1654. * string "server finished".
  1655. *
  1656. * verify_data_length depends on the cipher suite. If it is not specified
  1657. * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used
  1658. * 12 bytes.
  1659. *
  1660. * @param c the connection.
  1661. * @param record the record.
  1662. * @param length the length of the handshake message.
  1663. */
  1664. tls.handleFinished = function(c, record, length) {
  1665. // rewind to get full bytes for message so it can be manually
  1666. // digested below (special case for Finished messages because they
  1667. // must be digested *after* handling as opposed to all others)
  1668. var b = record.fragment;
  1669. b.read -= 4;
  1670. var msgBytes = b.bytes();
  1671. b.read += 4;
  1672. // message contains only verify_data
  1673. var vd = record.fragment.getBytes();
  1674. // ensure verify data is correct
  1675. b = forge.util.createBuffer();
  1676. b.putBuffer(c.session.md5.digest());
  1677. b.putBuffer(c.session.sha1.digest());
  1678. // set label based on entity type
  1679. var client = (c.entity === tls.ConnectionEnd.client);
  1680. var label = client ? 'server finished' : 'client finished';
  1681. // TODO: determine prf function and verify length for TLS 1.2
  1682. var sp = c.session.sp;
  1683. var vdl = 12;
  1684. var prf = prf_TLS1;
  1685. b = prf(sp.master_secret, label, b.getBytes(), vdl);
  1686. if(b.getBytes() !== vd) {
  1687. return c.error(c, {
  1688. message: 'Invalid verify_data in Finished message.',
  1689. send: true,
  1690. alert: {
  1691. level: tls.Alert.Level.fatal,
  1692. description: tls.Alert.Description.decrypt_error
  1693. }
  1694. });
  1695. }
  1696. // digest finished message now that it has been handled
  1697. c.session.md5.update(msgBytes);
  1698. c.session.sha1.update(msgBytes);
  1699. // resuming session as client or NOT resuming session as server
  1700. if((c.session.resuming && client) || (!c.session.resuming && !client)) {
  1701. // create change cipher spec message
  1702. tls.queue(c, tls.createRecord(c, {
  1703. type: tls.ContentType.change_cipher_spec,
  1704. data: tls.createChangeCipherSpec()
  1705. }));
  1706. // change current write state to pending write state, clear pending
  1707. c.state.current.write = c.state.pending.write;
  1708. c.state.pending = null;
  1709. // create finished message
  1710. tls.queue(c, tls.createRecord(c, {
  1711. type: tls.ContentType.handshake,
  1712. data: tls.createFinished(c)
  1713. }));
  1714. }
  1715. // expect application data next
  1716. c.expect = client ? SAD : CAD;
  1717. // handshake complete
  1718. c.handshaking = false;
  1719. ++c.handshakes;
  1720. // save access to peer certificate
  1721. c.peerCertificate = client ?
  1722. c.session.serverCertificate : c.session.clientCertificate;
  1723. // send records
  1724. tls.flush(c);
  1725. // now connected
  1726. c.isConnected = true;
  1727. c.connected(c);
  1728. // continue
  1729. c.process();
  1730. };
  1731. /**
  1732. * Called when an Alert record is received.
  1733. *
  1734. * @param c the connection.
  1735. * @param record the record.
  1736. */
  1737. tls.handleAlert = function(c, record) {
  1738. // read alert
  1739. var b = record.fragment;
  1740. var alert = {
  1741. level: b.getByte(),
  1742. description: b.getByte()
  1743. };
  1744. // TODO: consider using a table?
  1745. // get appropriate message
  1746. var msg;
  1747. switch(alert.description) {
  1748. case tls.Alert.Description.close_notify:
  1749. msg = 'Connection closed.';
  1750. break;
  1751. case tls.Alert.Description.unexpected_message:
  1752. msg = 'Unexpected message.';
  1753. break;
  1754. case tls.Alert.Description.bad_record_mac:
  1755. msg = 'Bad record MAC.';
  1756. break;
  1757. case tls.Alert.Description.decryption_failed:
  1758. msg = 'Decryption failed.';
  1759. break;
  1760. case tls.Alert.Description.record_overflow:
  1761. msg = 'Record overflow.';
  1762. break;
  1763. case tls.Alert.Description.decompression_failure:
  1764. msg = 'Decompression failed.';
  1765. break;
  1766. case tls.Alert.Description.handshake_failure:
  1767. msg = 'Handshake failure.';
  1768. break;
  1769. case tls.Alert.Description.bad_certificate:
  1770. msg = 'Bad certificate.';
  1771. break;
  1772. case tls.Alert.Description.unsupported_certificate:
  1773. msg = 'Unsupported certificate.';
  1774. break;
  1775. case tls.Alert.Description.certificate_revoked:
  1776. msg = 'Certificate revoked.';
  1777. break;
  1778. case tls.Alert.Description.certificate_expired:
  1779. msg = 'Certificate expired.';
  1780. break;
  1781. case tls.Alert.Description.certificate_unknown:
  1782. msg = 'Certificate unknown.';
  1783. break;
  1784. case tls.Alert.Description.illegal_parameter:
  1785. msg = 'Illegal parameter.';
  1786. break;
  1787. case tls.Alert.Description.unknown_ca:
  1788. msg = 'Unknown certificate authority.';
  1789. break;
  1790. case tls.Alert.Description.access_denied:
  1791. msg = 'Access denied.';
  1792. break;
  1793. case tls.Alert.Description.decode_error:
  1794. msg = 'Decode error.';
  1795. break;
  1796. case tls.Alert.Description.decrypt_error:
  1797. msg = 'Decrypt error.';
  1798. break;
  1799. case tls.Alert.Description.export_restriction:
  1800. msg = 'Export restriction.';
  1801. break;
  1802. case tls.Alert.Description.protocol_version:
  1803. msg = 'Unsupported protocol version.';
  1804. break;
  1805. case tls.Alert.Description.insufficient_security:
  1806. msg = 'Insufficient security.';
  1807. break;
  1808. case tls.Alert.Description.internal_error:
  1809. msg = 'Internal error.';
  1810. break;
  1811. case tls.Alert.Description.user_canceled:
  1812. msg = 'User canceled.';
  1813. break;
  1814. case tls.Alert.Description.no_renegotiation:
  1815. msg = 'Renegotiation not supported.';
  1816. break;
  1817. default:
  1818. msg = 'Unknown error.';
  1819. break;
  1820. }
  1821. // close connection on close_notify, not an error
  1822. if(alert.description === tls.Alert.Description.close_notify) {
  1823. return c.close();
  1824. }
  1825. // call error handler
  1826. c.error(c, {
  1827. message: msg,
  1828. send: false,
  1829. // origin is the opposite end
  1830. origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client',
  1831. alert: alert
  1832. });
  1833. // continue
  1834. c.process();
  1835. };
  1836. /**
  1837. * Called when a Handshake record is received.
  1838. *
  1839. * @param c the connection.
  1840. * @param record the record.
  1841. */
  1842. tls.handleHandshake = function(c, record) {
  1843. // get the handshake type and message length
  1844. var b = record.fragment;
  1845. var type = b.getByte();
  1846. var length = b.getInt24();
  1847. // see if the record fragment doesn't yet contain the full message
  1848. if(length > b.length()) {
  1849. // cache the record, clear its fragment, and reset the buffer read
  1850. // pointer before the type and length were read
  1851. c.fragmented = record;
  1852. record.fragment = forge.util.createBuffer();
  1853. b.read -= 4;
  1854. // continue
  1855. return c.process();
  1856. }
  1857. // full message now available, clear cache, reset read pointer to
  1858. // before type and length
  1859. c.fragmented = null;
  1860. b.read -= 4;
  1861. // save the handshake bytes for digestion after handler is found
  1862. // (include type and length of handshake msg)
  1863. var bytes = b.bytes(length + 4);
  1864. // restore read pointer
  1865. b.read += 4;
  1866. // handle expected message
  1867. if(type in hsTable[c.entity][c.expect]) {
  1868. // initialize server session
  1869. if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) {
  1870. c.handshaking = true;
  1871. c.session = {
  1872. version: null,
  1873. extensions: {
  1874. server_name: {
  1875. serverNameList: []
  1876. }
  1877. },
  1878. cipherSuite: null,
  1879. compressionMethod: null,
  1880. serverCertificate: null,
  1881. clientCertificate: null,
  1882. md5: forge.md.md5.create(),
  1883. sha1: forge.md.sha1.create()
  1884. };
  1885. }
  1886. /* Update handshake messages digest. Finished and CertificateVerify
  1887. messages are not digested here. They can't be digested as part of
  1888. the verify_data that they contain. These messages are manually
  1889. digested in their handlers. HelloRequest messages are simply never
  1890. included in the handshake message digest according to spec. */
  1891. if(type !== tls.HandshakeType.hello_request &&
  1892. type !== tls.HandshakeType.certificate_verify &&
  1893. type !== tls.HandshakeType.finished) {
  1894. c.session.md5.update(bytes);
  1895. c.session.sha1.update(bytes);
  1896. }
  1897. // handle specific handshake type record
  1898. hsTable[c.entity][c.expect][type](c, record, length);
  1899. } else {
  1900. // unexpected record
  1901. tls.handleUnexpected(c, record);
  1902. }
  1903. };
  1904. /**
  1905. * Called when an ApplicationData record is received.
  1906. *
  1907. * @param c the connection.
  1908. * @param record the record.
  1909. */
  1910. tls.handleApplicationData = function(c, record) {
  1911. // buffer data, notify that its ready
  1912. c.data.putBuffer(record.fragment);
  1913. c.dataReady(c);
  1914. // continue
  1915. c.process();
  1916. };
  1917. /**
  1918. * Called when a Heartbeat record is received.
  1919. *
  1920. * @param c the connection.
  1921. * @param record the record.
  1922. */
  1923. tls.handleHeartbeat = function(c, record) {
  1924. // get the heartbeat type and payload
  1925. var b = record.fragment;
  1926. var type = b.getByte();
  1927. var length = b.getInt16();
  1928. var payload = b.getBytes(length);
  1929. if(type === tls.HeartbeatMessageType.heartbeat_request) {
  1930. // discard request during handshake or if length is too large
  1931. if(c.handshaking || length > payload.length) {
  1932. // continue
  1933. return c.process();
  1934. }
  1935. // retransmit payload
  1936. tls.queue(c, tls.createRecord(c, {
  1937. type: tls.ContentType.heartbeat,
  1938. data: tls.createHeartbeat(
  1939. tls.HeartbeatMessageType.heartbeat_response, payload)
  1940. }));
  1941. tls.flush(c);
  1942. } else if(type === tls.HeartbeatMessageType.heartbeat_response) {
  1943. // check payload against expected payload, discard heartbeat if no match
  1944. if(payload !== c.expectedHeartbeatPayload) {
  1945. // continue
  1946. return c.process();
  1947. }
  1948. // notify that a valid heartbeat was received
  1949. if(c.heartbeatReceived) {
  1950. c.heartbeatReceived(c, forge.util.createBuffer(payload));
  1951. }
  1952. }
  1953. // continue
  1954. c.process();
  1955. };
  1956. /**
  1957. * The transistional state tables for receiving TLS records. It maps the
  1958. * current TLS engine state and a received record to a function to handle the
  1959. * record and update the state.
  1960. *
  1961. * For instance, if the current state is SHE, then the TLS engine is expecting
  1962. * a ServerHello record. Once a record is received, the handler function is
  1963. * looked up using the state SHE and the record's content type.
  1964. *
  1965. * The resulting function will either be an error handler or a record handler.
  1966. * The function will take whatever action is appropriate and update the state
  1967. * for the next record.
  1968. *
  1969. * The states are all based on possible server record types. Note that the
  1970. * client will never specifically expect to receive a HelloRequest or an alert
  1971. * from the server so there is no state that reflects this. These messages may
  1972. * occur at any time.
  1973. *
  1974. * There are two tables for mapping states because there is a second tier of
  1975. * types for handshake messages. Once a record with a content type of handshake
  1976. * is received, the handshake record handler will look up the handshake type in
  1977. * the secondary map to get its appropriate handler.
  1978. *
  1979. * Valid message orders are as follows:
  1980. *
  1981. * =======================FULL HANDSHAKE======================
  1982. * Client Server
  1983. *
  1984. * ClientHello -------->
  1985. * ServerHello
  1986. * Certificate*
  1987. * ServerKeyExchange*
  1988. * CertificateRequest*
  1989. * <-------- ServerHelloDone
  1990. * Certificate*
  1991. * ClientKeyExchange
  1992. * CertificateVerify*
  1993. * [ChangeCipherSpec]
  1994. * Finished -------->
  1995. * [ChangeCipherSpec]
  1996. * <-------- Finished
  1997. * Application Data <-------> Application Data
  1998. *
  1999. * =====================SESSION RESUMPTION=====================
  2000. * Client Server
  2001. *
  2002. * ClientHello -------->
  2003. * ServerHello
  2004. * [ChangeCipherSpec]
  2005. * <-------- Finished
  2006. * [ChangeCipherSpec]
  2007. * Finished -------->
  2008. * Application Data <-------> Application Data
  2009. */
  2010. // client expect states (indicate which records are expected to be received)
  2011. var SHE = 0; // rcv server hello
  2012. var SCE = 1; // rcv server certificate
  2013. var SKE = 2; // rcv server key exchange
  2014. var SCR = 3; // rcv certificate request
  2015. var SHD = 4; // rcv server hello done
  2016. var SCC = 5; // rcv change cipher spec
  2017. var SFI = 6; // rcv finished
  2018. var SAD = 7; // rcv application data
  2019. var SER = 8; // not expecting any messages at this point
  2020. // server expect states
  2021. var CHE = 0; // rcv client hello
  2022. var CCE = 1; // rcv client certificate
  2023. var CKE = 2; // rcv client key exchange
  2024. var CCV = 3; // rcv certificate verify
  2025. var CCC = 4; // rcv change cipher spec
  2026. var CFI = 5; // rcv finished
  2027. var CAD = 6; // rcv application data
  2028. var CER = 7; // not expecting any messages at this point
  2029. // map client current expect state and content type to function
  2030. var __ = tls.handleUnexpected;
  2031. var R0 = tls.handleChangeCipherSpec;
  2032. var R1 = tls.handleAlert;
  2033. var R2 = tls.handleHandshake;
  2034. var R3 = tls.handleApplicationData;
  2035. var R4 = tls.handleHeartbeat;
  2036. var ctTable = [];
  2037. ctTable[tls.ConnectionEnd.client] = [
  2038. // CC,AL,HS,AD,HB
  2039. /*SHE*/[__,R1,R2,__,R4],
  2040. /*SCE*/[__,R1,R2,__,R4],
  2041. /*SKE*/[__,R1,R2,__,R4],
  2042. /*SCR*/[__,R1,R2,__,R4],
  2043. /*SHD*/[__,R1,R2,__,R4],
  2044. /*SCC*/[R0,R1,__,__,R4],
  2045. /*SFI*/[__,R1,R2,__,R4],
  2046. /*SAD*/[__,R1,R2,R3,R4],
  2047. /*SER*/[__,R1,R2,__,R4]
  2048. ];
  2049. // map server current expect state and content type to function
  2050. ctTable[tls.ConnectionEnd.server] = [
  2051. // CC,AL,HS,AD
  2052. /*CHE*/[__,R1,R2,__,R4],
  2053. /*CCE*/[__,R1,R2,__,R4],
  2054. /*CKE*/[__,R1,R2,__,R4],
  2055. /*CCV*/[__,R1,R2,__,R4],
  2056. /*CCC*/[R0,R1,__,__,R4],
  2057. /*CFI*/[__,R1,R2,__,R4],
  2058. /*CAD*/[__,R1,R2,R3,R4],
  2059. /*CER*/[__,R1,R2,__,R4]
  2060. ];
  2061. // map client current expect state and handshake type to function
  2062. var H0 = tls.handleHelloRequest;
  2063. var H1 = tls.handleServerHello;
  2064. var H2 = tls.handleCertificate;
  2065. var H3 = tls.handleServerKeyExchange;
  2066. var H4 = tls.handleCertificateRequest;
  2067. var H5 = tls.handleServerHelloDone;
  2068. var H6 = tls.handleFinished;
  2069. var hsTable = [];
  2070. hsTable[tls.ConnectionEnd.client] = [
  2071. // HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI
  2072. /*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  2073. /*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__],
  2074. /*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__],
  2075. /*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__],
  2076. /*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__],
  2077. /*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  2078. /*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],
  2079. /*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  2080. /*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]
  2081. ];
  2082. // map server current expect state and handshake type to function
  2083. // Note: CAD[CH] does not map to FB because renegotation is prohibited
  2084. var H7 = tls.handleClientHello;
  2085. var H8 = tls.handleClientKeyExchange;
  2086. var H9 = tls.handleCertificateVerify;
  2087. hsTable[tls.ConnectionEnd.server] = [
  2088. // 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI
  2089. /*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  2090. /*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__],
  2091. /*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__],
  2092. /*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__],
  2093. /*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  2094. /*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6],
  2095. /*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__],
  2096. /*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__]
  2097. ];
  2098. /**
  2099. * Generates the master_secret and keys using the given security parameters.
  2100. *
  2101. * The security parameters for a TLS connection state are defined as such:
  2102. *
  2103. * struct {
  2104. * ConnectionEnd entity;
  2105. * PRFAlgorithm prf_algorithm;
  2106. * BulkCipherAlgorithm bulk_cipher_algorithm;
  2107. * CipherType cipher_type;
  2108. * uint8 enc_key_length;
  2109. * uint8 block_length;
  2110. * uint8 fixed_iv_length;
  2111. * uint8 record_iv_length;
  2112. * MACAlgorithm mac_algorithm;
  2113. * uint8 mac_length;
  2114. * uint8 mac_key_length;
  2115. * CompressionMethod compression_algorithm;
  2116. * opaque master_secret[48];
  2117. * opaque client_random[32];
  2118. * opaque server_random[32];
  2119. * } SecurityParameters;
  2120. *
  2121. * Note that this definition is from TLS 1.2. In TLS 1.0 some of these
  2122. * parameters are ignored because, for instance, the PRFAlgorithm is a
  2123. * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0.
  2124. *
  2125. * The Record Protocol requires an algorithm to generate keys required by the
  2126. * current connection state.
  2127. *
  2128. * The master secret is expanded into a sequence of secure bytes, which is then
  2129. * split to a client write MAC key, a server write MAC key, a client write
  2130. * encryption key, and a server write encryption key. In TLS 1.0 a client write
  2131. * IV and server write IV are also generated. Each of these is generated from
  2132. * the byte sequence in that order. Unused values are empty. In TLS 1.2, some
  2133. * AEAD ciphers may additionally require a client write IV and a server write
  2134. * IV (see Section 6.2.3.3).
  2135. *
  2136. * When keys, MAC keys, and IVs are generated, the master secret is used as an
  2137. * entropy source.
  2138. *
  2139. * To generate the key material, compute:
  2140. *
  2141. * master_secret = PRF(pre_master_secret, "master secret",
  2142. * ClientHello.random + ServerHello.random)
  2143. *
  2144. * key_block = PRF(SecurityParameters.master_secret,
  2145. * "key expansion",
  2146. * SecurityParameters.server_random +
  2147. * SecurityParameters.client_random);
  2148. *
  2149. * until enough output has been generated. Then, the key_block is
  2150. * partitioned as follows:
  2151. *
  2152. * client_write_MAC_key[SecurityParameters.mac_key_length]
  2153. * server_write_MAC_key[SecurityParameters.mac_key_length]
  2154. * client_write_key[SecurityParameters.enc_key_length]
  2155. * server_write_key[SecurityParameters.enc_key_length]
  2156. * client_write_IV[SecurityParameters.fixed_iv_length]
  2157. * server_write_IV[SecurityParameters.fixed_iv_length]
  2158. *
  2159. * In TLS 1.2, the client_write_IV and server_write_IV are only generated for
  2160. * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This
  2161. * implementation uses TLS 1.0 so IVs are generated.
  2162. *
  2163. * Implementation note: The currently defined cipher suite which requires the
  2164. * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32
  2165. * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also
  2166. * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material.
  2167. *
  2168. * @param c the connection.
  2169. * @param sp the security parameters to use.
  2170. *
  2171. * @return the security keys.
  2172. */
  2173. tls.generateKeys = function(c, sp) {
  2174. // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) &
  2175. // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented
  2176. // at present
  2177. // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with
  2178. // TLS 1.0 but we don't care right now because AES is better and we have
  2179. // an implementation for it
  2180. // TODO: TLS 1.2 implementation
  2181. /*
  2182. // determine the PRF
  2183. var prf;
  2184. switch(sp.prf_algorithm) {
  2185. case tls.PRFAlgorithm.tls_prf_sha256:
  2186. prf = prf_sha256;
  2187. break;
  2188. default:
  2189. // should never happen
  2190. throw new Error('Invalid PRF');
  2191. }
  2192. */
  2193. // TLS 1.0/1.1 implementation
  2194. var prf = prf_TLS1;
  2195. // concatenate server and client random
  2196. var random = sp.client_random + sp.server_random;
  2197. // only create master secret if session is new
  2198. if(!c.session.resuming) {
  2199. // create master secret, clean up pre-master secret
  2200. sp.master_secret = prf(
  2201. sp.pre_master_secret, 'master secret', random, 48).bytes();
  2202. sp.pre_master_secret = null;
  2203. }
  2204. // generate the amount of key material needed
  2205. random = sp.server_random + sp.client_random;
  2206. var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length;
  2207. // include IV for TLS/1.0
  2208. var tls10 = (c.version.major === tls.Versions.TLS_1_0.major &&
  2209. c.version.minor === tls.Versions.TLS_1_0.minor);
  2210. if(tls10) {
  2211. length += 2 * sp.fixed_iv_length;
  2212. }
  2213. var km = prf(sp.master_secret, 'key expansion', random, length);
  2214. // split the key material into the MAC and encryption keys
  2215. var rval = {
  2216. client_write_MAC_key: km.getBytes(sp.mac_key_length),
  2217. server_write_MAC_key: km.getBytes(sp.mac_key_length),
  2218. client_write_key: km.getBytes(sp.enc_key_length),
  2219. server_write_key: km.getBytes(sp.enc_key_length)
  2220. };
  2221. // include TLS 1.0 IVs
  2222. if(tls10) {
  2223. rval.client_write_IV = km.getBytes(sp.fixed_iv_length);
  2224. rval.server_write_IV = km.getBytes(sp.fixed_iv_length);
  2225. }
  2226. return rval;
  2227. };
  2228. /**
  2229. * Creates a new initialized TLS connection state. A connection state has
  2230. * a read mode and a write mode.
  2231. *
  2232. * compression state:
  2233. * The current state of the compression algorithm.
  2234. *
  2235. * cipher state:
  2236. * The current state of the encryption algorithm. This will consist of the
  2237. * scheduled key for that connection. For stream ciphers, this will also
  2238. * contain whatever state information is necessary to allow the stream to
  2239. * continue to encrypt or decrypt data.
  2240. *
  2241. * MAC key:
  2242. * The MAC key for the connection.
  2243. *
  2244. * sequence number:
  2245. * Each connection state contains a sequence number, which is maintained
  2246. * separately for read and write states. The sequence number MUST be set to
  2247. * zero whenever a connection state is made the active state. Sequence
  2248. * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do
  2249. * not wrap. If a TLS implementation would need to wrap a sequence number,
  2250. * it must renegotiate instead. A sequence number is incremented after each
  2251. * record: specifically, the first record transmitted under a particular
  2252. * connection state MUST use sequence number 0.
  2253. *
  2254. * @param c the connection.
  2255. *
  2256. * @return the new initialized TLS connection state.
  2257. */
  2258. tls.createConnectionState = function(c) {
  2259. var client = (c.entity === tls.ConnectionEnd.client);
  2260. var createMode = function() {
  2261. var mode = {
  2262. // two 32-bit numbers, first is most significant
  2263. sequenceNumber: [0, 0],
  2264. macKey: null,
  2265. macLength: 0,
  2266. macFunction: null,
  2267. cipherState: null,
  2268. cipherFunction: function(record) {return true;},
  2269. compressionState: null,
  2270. compressFunction: function(record) {return true;},
  2271. updateSequenceNumber: function() {
  2272. if(mode.sequenceNumber[1] === 0xFFFFFFFF) {
  2273. mode.sequenceNumber[1] = 0;
  2274. ++mode.sequenceNumber[0];
  2275. } else {
  2276. ++mode.sequenceNumber[1];
  2277. }
  2278. }
  2279. };
  2280. return mode;
  2281. };
  2282. var state = {
  2283. read: createMode(),
  2284. write: createMode()
  2285. };
  2286. // update function in read mode will decrypt then decompress a record
  2287. state.read.update = function(c, record) {
  2288. if(!state.read.cipherFunction(record, state.read)) {
  2289. c.error(c, {
  2290. message: 'Could not decrypt record or bad MAC.',
  2291. send: true,
  2292. alert: {
  2293. level: tls.Alert.Level.fatal,
  2294. // doesn't matter if decryption failed or MAC was
  2295. // invalid, return the same error so as not to reveal
  2296. // which one occurred
  2297. description: tls.Alert.Description.bad_record_mac
  2298. }
  2299. });
  2300. } else if(!state.read.compressFunction(c, record, state.read)) {
  2301. c.error(c, {
  2302. message: 'Could not decompress record.',
  2303. send: true,
  2304. alert: {
  2305. level: tls.Alert.Level.fatal,
  2306. description: tls.Alert.Description.decompression_failure
  2307. }
  2308. });
  2309. }
  2310. return !c.fail;
  2311. };
  2312. // update function in write mode will compress then encrypt a record
  2313. state.write.update = function(c, record) {
  2314. if(!state.write.compressFunction(c, record, state.write)) {
  2315. // error, but do not send alert since it would require
  2316. // compression as well
  2317. c.error(c, {
  2318. message: 'Could not compress record.',
  2319. send: false,
  2320. alert: {
  2321. level: tls.Alert.Level.fatal,
  2322. description: tls.Alert.Description.internal_error
  2323. }
  2324. });
  2325. } else if(!state.write.cipherFunction(record, state.write)) {
  2326. // error, but do not send alert since it would require
  2327. // encryption as well
  2328. c.error(c, {
  2329. message: 'Could not encrypt record.',
  2330. send: false,
  2331. alert: {
  2332. level: tls.Alert.Level.fatal,
  2333. description: tls.Alert.Description.internal_error
  2334. }
  2335. });
  2336. }
  2337. return !c.fail;
  2338. };
  2339. // handle security parameters
  2340. if(c.session) {
  2341. var sp = c.session.sp;
  2342. c.session.cipherSuite.initSecurityParameters(sp);
  2343. // generate keys
  2344. sp.keys = tls.generateKeys(c, sp);
  2345. state.read.macKey = client ?
  2346. sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key;
  2347. state.write.macKey = client ?
  2348. sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key;
  2349. // cipher suite setup
  2350. c.session.cipherSuite.initConnectionState(state, c, sp);
  2351. // compression setup
  2352. switch(sp.compression_algorithm) {
  2353. case tls.CompressionMethod.none:
  2354. break;
  2355. case tls.CompressionMethod.deflate:
  2356. state.read.compressFunction = inflate;
  2357. state.write.compressFunction = deflate;
  2358. break;
  2359. default:
  2360. throw new Error('Unsupported compression algorithm.');
  2361. }
  2362. }
  2363. return state;
  2364. };
  2365. /**
  2366. * Creates a Random structure.
  2367. *
  2368. * struct {
  2369. * uint32 gmt_unix_time;
  2370. * opaque random_bytes[28];
  2371. * } Random;
  2372. *
  2373. * gmt_unix_time:
  2374. * The current time and date in standard UNIX 32-bit format (seconds since
  2375. * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according
  2376. * to the sender's internal clock. Clocks are not required to be set
  2377. * correctly by the basic TLS protocol; higher-level or application
  2378. * protocols may define additional requirements. Note that, for historical
  2379. * reasons, the data element is named using GMT, the predecessor of the
  2380. * current worldwide time base, UTC.
  2381. * random_bytes:
  2382. * 28 bytes generated by a secure random number generator.
  2383. *
  2384. * @return the Random structure as a byte array.
  2385. */
  2386. tls.createRandom = function() {
  2387. // get UTC milliseconds
  2388. var d = new Date();
  2389. var utc = +d + d.getTimezoneOffset() * 60000;
  2390. var rval = forge.util.createBuffer();
  2391. rval.putInt32(utc);
  2392. rval.putBytes(forge.random.getBytes(28));
  2393. return rval;
  2394. };
  2395. /**
  2396. * Creates a TLS record with the given type and data.
  2397. *
  2398. * @param c the connection.
  2399. * @param options:
  2400. * type: the record type.
  2401. * data: the plain text data in a byte buffer.
  2402. *
  2403. * @return the created record.
  2404. */
  2405. tls.createRecord = function(c, options) {
  2406. if(!options.data) {
  2407. return null;
  2408. }
  2409. var record = {
  2410. type: options.type,
  2411. version: {
  2412. major: c.version.major,
  2413. minor: c.version.minor
  2414. },
  2415. length: options.data.length(),
  2416. fragment: options.data
  2417. };
  2418. return record;
  2419. };
  2420. /**
  2421. * Creates a TLS alert record.
  2422. *
  2423. * @param c the connection.
  2424. * @param alert:
  2425. * level: the TLS alert level.
  2426. * description: the TLS alert description.
  2427. *
  2428. * @return the created alert record.
  2429. */
  2430. tls.createAlert = function(c, alert) {
  2431. var b = forge.util.createBuffer();
  2432. b.putByte(alert.level);
  2433. b.putByte(alert.description);
  2434. return tls.createRecord(c, {
  2435. type: tls.ContentType.alert,
  2436. data: b
  2437. });
  2438. };
  2439. /* The structure of a TLS handshake message.
  2440. *
  2441. * struct {
  2442. * HandshakeType msg_type; // handshake type
  2443. * uint24 length; // bytes in message
  2444. * select(HandshakeType) {
  2445. * case hello_request: HelloRequest;
  2446. * case client_hello: ClientHello;
  2447. * case server_hello: ServerHello;
  2448. * case certificate: Certificate;
  2449. * case server_key_exchange: ServerKeyExchange;
  2450. * case certificate_request: CertificateRequest;
  2451. * case server_hello_done: ServerHelloDone;
  2452. * case certificate_verify: CertificateVerify;
  2453. * case client_key_exchange: ClientKeyExchange;
  2454. * case finished: Finished;
  2455. * } body;
  2456. * } Handshake;
  2457. */
  2458. /**
  2459. * Creates a ClientHello message.
  2460. *
  2461. * opaque SessionID<0..32>;
  2462. * enum { null(0), deflate(1), (255) } CompressionMethod;
  2463. * uint8 CipherSuite[2];
  2464. *
  2465. * struct {
  2466. * ProtocolVersion client_version;
  2467. * Random random;
  2468. * SessionID session_id;
  2469. * CipherSuite cipher_suites<2..2^16-2>;
  2470. * CompressionMethod compression_methods<1..2^8-1>;
  2471. * select(extensions_present) {
  2472. * case false:
  2473. * struct {};
  2474. * case true:
  2475. * Extension extensions<0..2^16-1>;
  2476. * };
  2477. * } ClientHello;
  2478. *
  2479. * The extension format for extended client hellos and server hellos is:
  2480. *
  2481. * struct {
  2482. * ExtensionType extension_type;
  2483. * opaque extension_data<0..2^16-1>;
  2484. * } Extension;
  2485. *
  2486. * Here:
  2487. *
  2488. * - "extension_type" identifies the particular extension type.
  2489. * - "extension_data" contains information specific to the particular
  2490. * extension type.
  2491. *
  2492. * The extension types defined in this document are:
  2493. *
  2494. * enum {
  2495. * server_name(0), max_fragment_length(1),
  2496. * client_certificate_url(2), trusted_ca_keys(3),
  2497. * truncated_hmac(4), status_request(5), (65535)
  2498. * } ExtensionType;
  2499. *
  2500. * @param c the connection.
  2501. *
  2502. * @return the ClientHello byte buffer.
  2503. */
  2504. tls.createClientHello = function(c) {
  2505. // save hello version
  2506. c.session.clientHelloVersion = {
  2507. major: c.version.major,
  2508. minor: c.version.minor
  2509. };
  2510. // create supported cipher suites
  2511. var cipherSuites = forge.util.createBuffer();
  2512. for(var i = 0; i < c.cipherSuites.length; ++i) {
  2513. var cs = c.cipherSuites[i];
  2514. cipherSuites.putByte(cs.id[0]);
  2515. cipherSuites.putByte(cs.id[1]);
  2516. }
  2517. var cSuites = cipherSuites.length();
  2518. // create supported compression methods, null always supported, but
  2519. // also support deflate if connection has inflate and deflate methods
  2520. var compressionMethods = forge.util.createBuffer();
  2521. compressionMethods.putByte(tls.CompressionMethod.none);
  2522. // FIXME: deflate support disabled until issues with raw deflate data
  2523. // without zlib headers are resolved
  2524. /*
  2525. if(c.inflate !== null && c.deflate !== null) {
  2526. compressionMethods.putByte(tls.CompressionMethod.deflate);
  2527. }
  2528. */
  2529. var cMethods = compressionMethods.length();
  2530. // create TLS SNI (server name indication) extension if virtual host
  2531. // has been specified, see RFC 3546
  2532. var extensions = forge.util.createBuffer();
  2533. if(c.virtualHost) {
  2534. // create extension struct
  2535. var ext = forge.util.createBuffer();
  2536. ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes)
  2537. ext.putByte(0x00);
  2538. /* In order to provide the server name, clients MAY include an
  2539. * extension of type "server_name" in the (extended) client hello.
  2540. * The "extension_data" field of this extension SHALL contain
  2541. * "ServerNameList" where:
  2542. *
  2543. * struct {
  2544. * NameType name_type;
  2545. * select(name_type) {
  2546. * case host_name: HostName;
  2547. * } name;
  2548. * } ServerName;
  2549. *
  2550. * enum {
  2551. * host_name(0), (255)
  2552. * } NameType;
  2553. *
  2554. * opaque HostName<1..2^16-1>;
  2555. *
  2556. * struct {
  2557. * ServerName server_name_list<1..2^16-1>
  2558. * } ServerNameList;
  2559. */
  2560. var serverName = forge.util.createBuffer();
  2561. serverName.putByte(0x00); // type host_name
  2562. writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost));
  2563. // ServerNameList is in extension_data
  2564. var snList = forge.util.createBuffer();
  2565. writeVector(snList, 2, serverName);
  2566. writeVector(ext, 2, snList);
  2567. extensions.putBuffer(ext);
  2568. }
  2569. var extLength = extensions.length();
  2570. if(extLength > 0) {
  2571. // add extension vector length
  2572. extLength += 2;
  2573. }
  2574. // determine length of the handshake message
  2575. // cipher suites and compression methods size will need to be
  2576. // updated if more get added to the list
  2577. var sessionId = c.session.id;
  2578. var length =
  2579. sessionId.length + 1 + // session ID vector
  2580. 2 + // version (major + minor)
  2581. 4 + 28 + // random time and random bytes
  2582. 2 + cSuites + // cipher suites vector
  2583. 1 + cMethods + // compression methods vector
  2584. extLength; // extensions vector
  2585. // build record fragment
  2586. var rval = forge.util.createBuffer();
  2587. rval.putByte(tls.HandshakeType.client_hello);
  2588. rval.putInt24(length); // handshake length
  2589. rval.putByte(c.version.major); // major version
  2590. rval.putByte(c.version.minor); // minor version
  2591. rval.putBytes(c.session.sp.client_random); // random time + bytes
  2592. writeVector(rval, 1, forge.util.createBuffer(sessionId));
  2593. writeVector(rval, 2, cipherSuites);
  2594. writeVector(rval, 1, compressionMethods);
  2595. if(extLength > 0) {
  2596. writeVector(rval, 2, extensions);
  2597. }
  2598. return rval;
  2599. };
  2600. /**
  2601. * Creates a ServerHello message.
  2602. *
  2603. * @param c the connection.
  2604. *
  2605. * @return the ServerHello byte buffer.
  2606. */
  2607. tls.createServerHello = function(c) {
  2608. // determine length of the handshake message
  2609. var sessionId = c.session.id;
  2610. var length =
  2611. sessionId.length + 1 + // session ID vector
  2612. 2 + // version (major + minor)
  2613. 4 + 28 + // random time and random bytes
  2614. 2 + // chosen cipher suite
  2615. 1; // chosen compression method
  2616. // build record fragment
  2617. var rval = forge.util.createBuffer();
  2618. rval.putByte(tls.HandshakeType.server_hello);
  2619. rval.putInt24(length); // handshake length
  2620. rval.putByte(c.version.major); // major version
  2621. rval.putByte(c.version.minor); // minor version
  2622. rval.putBytes(c.session.sp.server_random); // random time + bytes
  2623. writeVector(rval, 1, forge.util.createBuffer(sessionId));
  2624. rval.putByte(c.session.cipherSuite.id[0]);
  2625. rval.putByte(c.session.cipherSuite.id[1]);
  2626. rval.putByte(c.session.compressionMethod);
  2627. return rval;
  2628. };
  2629. /**
  2630. * Creates a Certificate message.
  2631. *
  2632. * When this message will be sent:
  2633. * This is the first message the client can send after receiving a server
  2634. * hello done message and the first message the server can send after
  2635. * sending a ServerHello. This client message is only sent if the server
  2636. * requests a certificate. If no suitable certificate is available, the
  2637. * client should send a certificate message containing no certificates. If
  2638. * client authentication is required by the server for the handshake to
  2639. * continue, it may respond with a fatal handshake failure alert.
  2640. *
  2641. * opaque ASN.1Cert<1..2^24-1>;
  2642. *
  2643. * struct {
  2644. * ASN.1Cert certificate_list<0..2^24-1>;
  2645. * } Certificate;
  2646. *
  2647. * @param c the connection.
  2648. *
  2649. * @return the Certificate byte buffer.
  2650. */
  2651. tls.createCertificate = function(c) {
  2652. // TODO: check certificate request to ensure types are supported
  2653. // get a certificate (a certificate as a PEM string)
  2654. var client = (c.entity === tls.ConnectionEnd.client);
  2655. var cert = null;
  2656. if(c.getCertificate) {
  2657. var hint;
  2658. if(client) {
  2659. hint = c.session.certificateRequest;
  2660. } else {
  2661. hint = c.session.extensions.server_name.serverNameList;
  2662. }
  2663. cert = c.getCertificate(c, hint);
  2664. }
  2665. // buffer to hold certificate list
  2666. var certList = forge.util.createBuffer();
  2667. if(cert !== null) {
  2668. try {
  2669. // normalize cert to a chain of certificates
  2670. if(!forge.util.isArray(cert)) {
  2671. cert = [cert];
  2672. }
  2673. var asn1 = null;
  2674. for(var i = 0; i < cert.length; ++i) {
  2675. var msg = forge.pem.decode(cert[i])[0];
  2676. if(msg.type !== 'CERTIFICATE' &&
  2677. msg.type !== 'X509 CERTIFICATE' &&
  2678. msg.type !== 'TRUSTED CERTIFICATE') {
  2679. var error = new Error('Could not convert certificate from PEM; PEM ' +
  2680. 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' +
  2681. '"TRUSTED CERTIFICATE".');
  2682. error.headerType = msg.type;
  2683. throw error;
  2684. }
  2685. if(msg.procType && msg.procType.type === 'ENCRYPTED') {
  2686. throw new Error('Could not convert certificate from PEM; PEM is encrypted.');
  2687. }
  2688. var der = forge.util.createBuffer(msg.body);
  2689. if(asn1 === null) {
  2690. asn1 = forge.asn1.fromDer(der.bytes(), false);
  2691. }
  2692. // certificate entry is itself a vector with 3 length bytes
  2693. var certBuffer = forge.util.createBuffer();
  2694. writeVector(certBuffer, 3, der);
  2695. // add cert vector to cert list vector
  2696. certList.putBuffer(certBuffer);
  2697. }
  2698. // save certificate
  2699. cert = forge.pki.certificateFromAsn1(asn1);
  2700. if(client) {
  2701. c.session.clientCertificate = cert;
  2702. } else {
  2703. c.session.serverCertificate = cert;
  2704. }
  2705. } catch(ex) {
  2706. return c.error(c, {
  2707. message: 'Could not send certificate list.',
  2708. cause: ex,
  2709. send: true,
  2710. alert: {
  2711. level: tls.Alert.Level.fatal,
  2712. description: tls.Alert.Description.bad_certificate
  2713. }
  2714. });
  2715. }
  2716. }
  2717. // determine length of the handshake message
  2718. var length = 3 + certList.length(); // cert list vector
  2719. // build record fragment
  2720. var rval = forge.util.createBuffer();
  2721. rval.putByte(tls.HandshakeType.certificate);
  2722. rval.putInt24(length);
  2723. writeVector(rval, 3, certList);
  2724. return rval;
  2725. };
  2726. /**
  2727. * Creates a ClientKeyExchange message.
  2728. *
  2729. * When this message will be sent:
  2730. * This message is always sent by the client. It will immediately follow the
  2731. * client certificate message, if it is sent. Otherwise it will be the first
  2732. * message sent by the client after it receives the server hello done
  2733. * message.
  2734. *
  2735. * Meaning of this message:
  2736. * With this message, the premaster secret is set, either though direct
  2737. * transmission of the RSA-encrypted secret, or by the transmission of
  2738. * Diffie-Hellman parameters which will allow each side to agree upon the
  2739. * same premaster secret. When the key exchange method is DH_RSA or DH_DSS,
  2740. * client certification has been requested, and the client was able to
  2741. * respond with a certificate which contained a Diffie-Hellman public key
  2742. * whose parameters (group and generator) matched those specified by the
  2743. * server in its certificate, this message will not contain any data.
  2744. *
  2745. * Meaning of this message:
  2746. * If RSA is being used for key agreement and authentication, the client
  2747. * generates a 48-byte premaster secret, encrypts it using the public key
  2748. * from the server's certificate or the temporary RSA key provided in a
  2749. * server key exchange message, and sends the result in an encrypted
  2750. * premaster secret message. This structure is a variant of the client
  2751. * key exchange message, not a message in itself.
  2752. *
  2753. * struct {
  2754. * select(KeyExchangeAlgorithm) {
  2755. * case rsa: EncryptedPreMasterSecret;
  2756. * case diffie_hellman: ClientDiffieHellmanPublic;
  2757. * } exchange_keys;
  2758. * } ClientKeyExchange;
  2759. *
  2760. * struct {
  2761. * ProtocolVersion client_version;
  2762. * opaque random[46];
  2763. * } PreMasterSecret;
  2764. *
  2765. * struct {
  2766. * public-key-encrypted PreMasterSecret pre_master_secret;
  2767. * } EncryptedPreMasterSecret;
  2768. *
  2769. * A public-key-encrypted element is encoded as a vector <0..2^16-1>.
  2770. *
  2771. * @param c the connection.
  2772. *
  2773. * @return the ClientKeyExchange byte buffer.
  2774. */
  2775. tls.createClientKeyExchange = function(c) {
  2776. // create buffer to encrypt
  2777. var b = forge.util.createBuffer();
  2778. // add highest client-supported protocol to help server avoid version
  2779. // rollback attacks
  2780. b.putByte(c.session.clientHelloVersion.major);
  2781. b.putByte(c.session.clientHelloVersion.minor);
  2782. // generate and add 46 random bytes
  2783. b.putBytes(forge.random.getBytes(46));
  2784. // save pre-master secret
  2785. var sp = c.session.sp;
  2786. sp.pre_master_secret = b.getBytes();
  2787. // RSA-encrypt the pre-master secret
  2788. var key = c.session.serverCertificate.publicKey;
  2789. b = key.encrypt(sp.pre_master_secret);
  2790. /* Note: The encrypted pre-master secret will be stored in a
  2791. public-key-encrypted opaque vector that has the length prefixed using
  2792. 2 bytes, so include those 2 bytes in the handshake message length. This
  2793. is done as a minor optimization instead of calling writeVector(). */
  2794. // determine length of the handshake message
  2795. var length = b.length + 2;
  2796. // build record fragment
  2797. var rval = forge.util.createBuffer();
  2798. rval.putByte(tls.HandshakeType.client_key_exchange);
  2799. rval.putInt24(length);
  2800. // add vector length bytes
  2801. rval.putInt16(b.length);
  2802. rval.putBytes(b);
  2803. return rval;
  2804. };
  2805. /**
  2806. * Creates a ServerKeyExchange message.
  2807. *
  2808. * @param c the connection.
  2809. *
  2810. * @return the ServerKeyExchange byte buffer.
  2811. */
  2812. tls.createServerKeyExchange = function(c) {
  2813. // this implementation only supports RSA, no Diffie-Hellman support,
  2814. // so this record is empty
  2815. // determine length of the handshake message
  2816. var length = 0;
  2817. // build record fragment
  2818. var rval = forge.util.createBuffer();
  2819. if(length > 0) {
  2820. rval.putByte(tls.HandshakeType.server_key_exchange);
  2821. rval.putInt24(length);
  2822. }
  2823. return rval;
  2824. };
  2825. /**
  2826. * Gets the signed data used to verify a client-side certificate. See
  2827. * tls.createCertificateVerify() for details.
  2828. *
  2829. * @param c the connection.
  2830. * @param callback the callback to call once the signed data is ready.
  2831. */
  2832. tls.getClientSignature = function(c, callback) {
  2833. // generate data to RSA encrypt
  2834. var b = forge.util.createBuffer();
  2835. b.putBuffer(c.session.md5.digest());
  2836. b.putBuffer(c.session.sha1.digest());
  2837. b = b.getBytes();
  2838. // create default signing function as necessary
  2839. c.getSignature = c.getSignature || function(c, b, callback) {
  2840. // do rsa encryption, call callback
  2841. var privateKey = null;
  2842. if(c.getPrivateKey) {
  2843. try {
  2844. privateKey = c.getPrivateKey(c, c.session.clientCertificate);
  2845. privateKey = forge.pki.privateKeyFromPem(privateKey);
  2846. } catch(ex) {
  2847. c.error(c, {
  2848. message: 'Could not get private key.',
  2849. cause: ex,
  2850. send: true,
  2851. alert: {
  2852. level: tls.Alert.Level.fatal,
  2853. description: tls.Alert.Description.internal_error
  2854. }
  2855. });
  2856. }
  2857. }
  2858. if(privateKey === null) {
  2859. c.error(c, {
  2860. message: 'No private key set.',
  2861. send: true,
  2862. alert: {
  2863. level: tls.Alert.Level.fatal,
  2864. description: tls.Alert.Description.internal_error
  2865. }
  2866. });
  2867. } else {
  2868. b = privateKey.sign(b, null);
  2869. }
  2870. callback(c, b);
  2871. };
  2872. // get client signature
  2873. c.getSignature(c, b, callback);
  2874. };
  2875. /**
  2876. * Creates a CertificateVerify message.
  2877. *
  2878. * Meaning of this message:
  2879. * This structure conveys the client's Diffie-Hellman public value
  2880. * (Yc) if it was not already included in the client's certificate.
  2881. * The encoding used for Yc is determined by the enumerated
  2882. * PublicValueEncoding. This structure is a variant of the client
  2883. * key exchange message, not a message in itself.
  2884. *
  2885. * When this message will be sent:
  2886. * This message is used to provide explicit verification of a client
  2887. * certificate. This message is only sent following a client
  2888. * certificate that has signing capability (i.e. all certificates
  2889. * except those containing fixed Diffie-Hellman parameters). When
  2890. * sent, it will immediately follow the client key exchange message.
  2891. *
  2892. * struct {
  2893. * Signature signature;
  2894. * } CertificateVerify;
  2895. *
  2896. * CertificateVerify.signature.md5_hash
  2897. * MD5(handshake_messages);
  2898. *
  2899. * Certificate.signature.sha_hash
  2900. * SHA(handshake_messages);
  2901. *
  2902. * Here handshake_messages refers to all handshake messages sent or
  2903. * received starting at client hello up to but not including this
  2904. * message, including the type and length fields of the handshake
  2905. * messages.
  2906. *
  2907. * select(SignatureAlgorithm) {
  2908. * case anonymous: struct { };
  2909. * case rsa:
  2910. * digitally-signed struct {
  2911. * opaque md5_hash[16];
  2912. * opaque sha_hash[20];
  2913. * };
  2914. * case dsa:
  2915. * digitally-signed struct {
  2916. * opaque sha_hash[20];
  2917. * };
  2918. * } Signature;
  2919. *
  2920. * In digital signing, one-way hash functions are used as input for a
  2921. * signing algorithm. A digitally-signed element is encoded as an opaque
  2922. * vector <0..2^16-1>, where the length is specified by the signing
  2923. * algorithm and key.
  2924. *
  2925. * In RSA signing, a 36-byte structure of two hashes (one SHA and one
  2926. * MD5) is signed (encrypted with the private key). It is encoded with
  2927. * PKCS #1 block type 0 or type 1 as described in [PKCS1].
  2928. *
  2929. * In DSS, the 20 bytes of the SHA hash are run directly through the
  2930. * Digital Signing Algorithm with no additional hashing.
  2931. *
  2932. * @param c the connection.
  2933. * @param signature the signature to include in the message.
  2934. *
  2935. * @return the CertificateVerify byte buffer.
  2936. */
  2937. tls.createCertificateVerify = function(c, signature) {
  2938. /* Note: The signature will be stored in a "digitally-signed" opaque
  2939. vector that has the length prefixed using 2 bytes, so include those
  2940. 2 bytes in the handshake message length. This is done as a minor
  2941. optimization instead of calling writeVector(). */
  2942. // determine length of the handshake message
  2943. var length = signature.length + 2;
  2944. // build record fragment
  2945. var rval = forge.util.createBuffer();
  2946. rval.putByte(tls.HandshakeType.certificate_verify);
  2947. rval.putInt24(length);
  2948. // add vector length bytes
  2949. rval.putInt16(signature.length);
  2950. rval.putBytes(signature);
  2951. return rval;
  2952. };
  2953. /**
  2954. * Creates a CertificateRequest message.
  2955. *
  2956. * @param c the connection.
  2957. *
  2958. * @return the CertificateRequest byte buffer.
  2959. */
  2960. tls.createCertificateRequest = function(c) {
  2961. // TODO: support other certificate types
  2962. var certTypes = forge.util.createBuffer();
  2963. // common RSA certificate type
  2964. certTypes.putByte(0x01);
  2965. // add distinguished names from CA store
  2966. var cAs = forge.util.createBuffer();
  2967. for(var key in c.caStore.certs) {
  2968. var cert = c.caStore.certs[key];
  2969. var dn = forge.pki.distinguishedNameToAsn1(cert.subject);
  2970. var byteBuffer = forge.asn1.toDer(dn);
  2971. cAs.putInt16(byteBuffer.length());
  2972. cAs.putBuffer(byteBuffer);
  2973. }
  2974. // TODO: TLS 1.2+ has a different format
  2975. // determine length of the handshake message
  2976. var length =
  2977. 1 + certTypes.length() +
  2978. 2 + cAs.length();
  2979. // build record fragment
  2980. var rval = forge.util.createBuffer();
  2981. rval.putByte(tls.HandshakeType.certificate_request);
  2982. rval.putInt24(length);
  2983. writeVector(rval, 1, certTypes);
  2984. writeVector(rval, 2, cAs);
  2985. return rval;
  2986. };
  2987. /**
  2988. * Creates a ServerHelloDone message.
  2989. *
  2990. * @param c the connection.
  2991. *
  2992. * @return the ServerHelloDone byte buffer.
  2993. */
  2994. tls.createServerHelloDone = function(c) {
  2995. // build record fragment
  2996. var rval = forge.util.createBuffer();
  2997. rval.putByte(tls.HandshakeType.server_hello_done);
  2998. rval.putInt24(0);
  2999. return rval;
  3000. };
  3001. /**
  3002. * Creates a ChangeCipherSpec message.
  3003. *
  3004. * The change cipher spec protocol exists to signal transitions in
  3005. * ciphering strategies. The protocol consists of a single message,
  3006. * which is encrypted and compressed under the current (not the pending)
  3007. * connection state. The message consists of a single byte of value 1.
  3008. *
  3009. * struct {
  3010. * enum { change_cipher_spec(1), (255) } type;
  3011. * } ChangeCipherSpec;
  3012. *
  3013. * @return the ChangeCipherSpec byte buffer.
  3014. */
  3015. tls.createChangeCipherSpec = function() {
  3016. var rval = forge.util.createBuffer();
  3017. rval.putByte(0x01);
  3018. return rval;
  3019. };
  3020. /**
  3021. * Creates a Finished message.
  3022. *
  3023. * struct {
  3024. * opaque verify_data[12];
  3025. * } Finished;
  3026. *
  3027. * verify_data
  3028. * PRF(master_secret, finished_label, MD5(handshake_messages) +
  3029. * SHA-1(handshake_messages)) [0..11];
  3030. *
  3031. * finished_label
  3032. * For Finished messages sent by the client, the string "client
  3033. * finished". For Finished messages sent by the server, the
  3034. * string "server finished".
  3035. *
  3036. * handshake_messages
  3037. * All of the data from all handshake messages up to but not
  3038. * including this message. This is only data visible at the
  3039. * handshake layer and does not include record layer headers.
  3040. * This is the concatenation of all the Handshake structures as
  3041. * defined in 7.4 exchanged thus far.
  3042. *
  3043. * @param c the connection.
  3044. *
  3045. * @return the Finished byte buffer.
  3046. */
  3047. tls.createFinished = function(c) {
  3048. // generate verify_data
  3049. var b = forge.util.createBuffer();
  3050. b.putBuffer(c.session.md5.digest());
  3051. b.putBuffer(c.session.sha1.digest());
  3052. // TODO: determine prf function and verify length for TLS 1.2
  3053. var client = (c.entity === tls.ConnectionEnd.client);
  3054. var sp = c.session.sp;
  3055. var vdl = 12;
  3056. var prf = prf_TLS1;
  3057. var label = client ? 'client finished' : 'server finished';
  3058. b = prf(sp.master_secret, label, b.getBytes(), vdl);
  3059. // build record fragment
  3060. var rval = forge.util.createBuffer();
  3061. rval.putByte(tls.HandshakeType.finished);
  3062. rval.putInt24(b.length());
  3063. rval.putBuffer(b);
  3064. return rval;
  3065. };
  3066. /**
  3067. * Creates a HeartbeatMessage (See RFC 6520).
  3068. *
  3069. * struct {
  3070. * HeartbeatMessageType type;
  3071. * uint16 payload_length;
  3072. * opaque payload[HeartbeatMessage.payload_length];
  3073. * opaque padding[padding_length];
  3074. * } HeartbeatMessage;
  3075. *
  3076. * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or
  3077. * max_fragment_length when negotiated as defined in [RFC6066].
  3078. *
  3079. * type: The message type, either heartbeat_request or heartbeat_response.
  3080. *
  3081. * payload_length: The length of the payload.
  3082. *
  3083. * payload: The payload consists of arbitrary content.
  3084. *
  3085. * padding: The padding is random content that MUST be ignored by the
  3086. * receiver. The length of a HeartbeatMessage is TLSPlaintext.length
  3087. * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the
  3088. * length of the type field is 1 byte, and the length of the
  3089. * payload_length is 2. Therefore, the padding_length is
  3090. * TLSPlaintext.length - payload_length - 3 for TLS and
  3091. * DTLSPlaintext.length - payload_length - 3 for DTLS. The
  3092. * padding_length MUST be at least 16.
  3093. *
  3094. * The sender of a HeartbeatMessage MUST use a random padding of at
  3095. * least 16 bytes. The padding of a received HeartbeatMessage message
  3096. * MUST be ignored.
  3097. *
  3098. * If the payload_length of a received HeartbeatMessage is too large,
  3099. * the received HeartbeatMessage MUST be discarded silently.
  3100. *
  3101. * @param c the connection.
  3102. * @param type the tls.HeartbeatMessageType.
  3103. * @param payload the heartbeat data to send as the payload.
  3104. * @param [payloadLength] the payload length to use, defaults to the
  3105. * actual payload length.
  3106. *
  3107. * @return the HeartbeatRequest byte buffer.
  3108. */
  3109. tls.createHeartbeat = function(type, payload, payloadLength) {
  3110. if(typeof payloadLength === 'undefined') {
  3111. payloadLength = payload.length;
  3112. }
  3113. // build record fragment
  3114. var rval = forge.util.createBuffer();
  3115. rval.putByte(type); // heartbeat message type
  3116. rval.putInt16(payloadLength); // payload length
  3117. rval.putBytes(payload); // payload
  3118. // padding
  3119. var plaintextLength = rval.length();
  3120. var paddingLength = Math.max(16, plaintextLength - payloadLength - 3);
  3121. rval.putBytes(forge.random.getBytes(paddingLength));
  3122. return rval;
  3123. };
  3124. /**
  3125. * Fragments, compresses, encrypts, and queues a record for delivery.
  3126. *
  3127. * @param c the connection.
  3128. * @param record the record to queue.
  3129. */
  3130. tls.queue = function(c, record) {
  3131. // error during record creation
  3132. if(!record) {
  3133. return;
  3134. }
  3135. if(record.fragment.length() === 0) {
  3136. if(record.type === tls.ContentType.handshake ||
  3137. record.type === tls.ContentType.alert ||
  3138. record.type === tls.ContentType.change_cipher_spec) {
  3139. // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent.
  3140. return;
  3141. }
  3142. }
  3143. // if the record is a handshake record, update handshake hashes
  3144. if(record.type === tls.ContentType.handshake) {
  3145. var bytes = record.fragment.bytes();
  3146. c.session.md5.update(bytes);
  3147. c.session.sha1.update(bytes);
  3148. bytes = null;
  3149. }
  3150. // handle record fragmentation
  3151. var records;
  3152. if(record.fragment.length() <= tls.MaxFragment) {
  3153. records = [record];
  3154. } else {
  3155. // fragment data as long as it is too long
  3156. records = [];
  3157. var data = record.fragment.bytes();
  3158. while(data.length > tls.MaxFragment) {
  3159. records.push(tls.createRecord(c, {
  3160. type: record.type,
  3161. data: forge.util.createBuffer(data.slice(0, tls.MaxFragment))
  3162. }));
  3163. data = data.slice(tls.MaxFragment);
  3164. }
  3165. // add last record
  3166. if(data.length > 0) {
  3167. records.push(tls.createRecord(c, {
  3168. type: record.type,
  3169. data: forge.util.createBuffer(data)
  3170. }));
  3171. }
  3172. }
  3173. // compress and encrypt all fragmented records
  3174. for(var i = 0; i < records.length && !c.fail; ++i) {
  3175. // update the record using current write state
  3176. var rec = records[i];
  3177. var s = c.state.current.write;
  3178. if(s.update(c, rec)) {
  3179. // store record
  3180. c.records.push(rec);
  3181. }
  3182. }
  3183. };
  3184. /**
  3185. * Flushes all queued records to the output buffer and calls the
  3186. * tlsDataReady() handler on the given connection.
  3187. *
  3188. * @param c the connection.
  3189. *
  3190. * @return true on success, false on failure.
  3191. */
  3192. tls.flush = function(c) {
  3193. for(var i = 0; i < c.records.length; ++i) {
  3194. var record = c.records[i];
  3195. // add record header and fragment
  3196. c.tlsData.putByte(record.type);
  3197. c.tlsData.putByte(record.version.major);
  3198. c.tlsData.putByte(record.version.minor);
  3199. c.tlsData.putInt16(record.fragment.length());
  3200. c.tlsData.putBuffer(c.records[i].fragment);
  3201. }
  3202. c.records = [];
  3203. return c.tlsDataReady(c);
  3204. };
  3205. /**
  3206. * Maps a pki.certificateError to a tls.Alert.Description.
  3207. *
  3208. * @param error the error to map.
  3209. *
  3210. * @return the alert description.
  3211. */
  3212. var _certErrorToAlertDesc = function(error) {
  3213. switch(error) {
  3214. case true:
  3215. return true;
  3216. case forge.pki.certificateError.bad_certificate:
  3217. return tls.Alert.Description.bad_certificate;
  3218. case forge.pki.certificateError.unsupported_certificate:
  3219. return tls.Alert.Description.unsupported_certificate;
  3220. case forge.pki.certificateError.certificate_revoked:
  3221. return tls.Alert.Description.certificate_revoked;
  3222. case forge.pki.certificateError.certificate_expired:
  3223. return tls.Alert.Description.certificate_expired;
  3224. case forge.pki.certificateError.certificate_unknown:
  3225. return tls.Alert.Description.certificate_unknown;
  3226. case forge.pki.certificateError.unknown_ca:
  3227. return tls.Alert.Description.unknown_ca;
  3228. default:
  3229. return tls.Alert.Description.bad_certificate;
  3230. }
  3231. };
  3232. /**
  3233. * Maps a tls.Alert.Description to a pki.certificateError.
  3234. *
  3235. * @param desc the alert description.
  3236. *
  3237. * @return the certificate error.
  3238. */
  3239. var _alertDescToCertError = function(desc) {
  3240. switch(desc) {
  3241. case true:
  3242. return true;
  3243. case tls.Alert.Description.bad_certificate:
  3244. return forge.pki.certificateError.bad_certificate;
  3245. case tls.Alert.Description.unsupported_certificate:
  3246. return forge.pki.certificateError.unsupported_certificate;
  3247. case tls.Alert.Description.certificate_revoked:
  3248. return forge.pki.certificateError.certificate_revoked;
  3249. case tls.Alert.Description.certificate_expired:
  3250. return forge.pki.certificateError.certificate_expired;
  3251. case tls.Alert.Description.certificate_unknown:
  3252. return forge.pki.certificateError.certificate_unknown;
  3253. case tls.Alert.Description.unknown_ca:
  3254. return forge.pki.certificateError.unknown_ca;
  3255. default:
  3256. return forge.pki.certificateError.bad_certificate;
  3257. }
  3258. };
  3259. /**
  3260. * Verifies a certificate chain against the given connection's
  3261. * Certificate Authority store.
  3262. *
  3263. * @param c the TLS connection.
  3264. * @param chain the certificate chain to verify, with the root or highest
  3265. * authority at the end.
  3266. *
  3267. * @return true if successful, false if not.
  3268. */
  3269. tls.verifyCertificateChain = function(c, chain) {
  3270. try {
  3271. // Make a copy of c.verifyOptions so that we can modify options.verify
  3272. // without modifying c.verifyOptions.
  3273. var options = {};
  3274. for (var key in c.verifyOptions) {
  3275. options[key] = c.verifyOptions[key];
  3276. }
  3277. options.verify = function(vfd, depth, chain) {
  3278. // convert pki.certificateError to tls alert description
  3279. var desc = _certErrorToAlertDesc(vfd);
  3280. // call application callback
  3281. var ret = c.verify(c, vfd, depth, chain);
  3282. if(ret !== true) {
  3283. if(typeof ret === 'object' && !forge.util.isArray(ret)) {
  3284. // throw custom error
  3285. var error = new Error('The application rejected the certificate.');
  3286. error.send = true;
  3287. error.alert = {
  3288. level: tls.Alert.Level.fatal,
  3289. description: tls.Alert.Description.bad_certificate
  3290. };
  3291. if(ret.message) {
  3292. error.message = ret.message;
  3293. }
  3294. if(ret.alert) {
  3295. error.alert.description = ret.alert;
  3296. }
  3297. throw error;
  3298. }
  3299. // convert tls alert description to pki.certificateError
  3300. if(ret !== vfd) {
  3301. ret = _alertDescToCertError(ret);
  3302. }
  3303. }
  3304. return ret;
  3305. };
  3306. // verify chain
  3307. forge.pki.verifyCertificateChain(c.caStore, chain, options);
  3308. } catch(ex) {
  3309. // build tls error if not already customized
  3310. var err = ex;
  3311. if(typeof err !== 'object' || forge.util.isArray(err)) {
  3312. err = {
  3313. send: true,
  3314. alert: {
  3315. level: tls.Alert.Level.fatal,
  3316. description: _certErrorToAlertDesc(ex)
  3317. }
  3318. };
  3319. }
  3320. if(!('send' in err)) {
  3321. err.send = true;
  3322. }
  3323. if(!('alert' in err)) {
  3324. err.alert = {
  3325. level: tls.Alert.Level.fatal,
  3326. description: _certErrorToAlertDesc(err.error)
  3327. };
  3328. }
  3329. // send error
  3330. c.error(c, err);
  3331. }
  3332. return !c.fail;
  3333. };
  3334. /**
  3335. * Creates a new TLS session cache.
  3336. *
  3337. * @param cache optional map of session ID to cached session.
  3338. * @param capacity the maximum size for the cache (default: 100).
  3339. *
  3340. * @return the new TLS session cache.
  3341. */
  3342. tls.createSessionCache = function(cache, capacity) {
  3343. var rval = null;
  3344. // assume input is already a session cache object
  3345. if(cache && cache.getSession && cache.setSession && cache.order) {
  3346. rval = cache;
  3347. } else {
  3348. // create cache
  3349. rval = {};
  3350. rval.cache = cache || {};
  3351. rval.capacity = Math.max(capacity || 100, 1);
  3352. rval.order = [];
  3353. // store order for sessions, delete session overflow
  3354. for(var key in cache) {
  3355. if(rval.order.length <= capacity) {
  3356. rval.order.push(key);
  3357. } else {
  3358. delete cache[key];
  3359. }
  3360. }
  3361. // get a session from a session ID (or get any session)
  3362. rval.getSession = function(sessionId) {
  3363. var session = null;
  3364. var key = null;
  3365. // if session ID provided, use it
  3366. if(sessionId) {
  3367. key = forge.util.bytesToHex(sessionId);
  3368. } else if(rval.order.length > 0) {
  3369. // get first session from cache
  3370. key = rval.order[0];
  3371. }
  3372. if(key !== null && key in rval.cache) {
  3373. // get cached session and remove from cache
  3374. session = rval.cache[key];
  3375. delete rval.cache[key];
  3376. for(var i in rval.order) {
  3377. if(rval.order[i] === key) {
  3378. rval.order.splice(i, 1);
  3379. break;
  3380. }
  3381. }
  3382. }
  3383. return session;
  3384. };
  3385. // set a session in the cache
  3386. rval.setSession = function(sessionId, session) {
  3387. // remove session from cache if at capacity
  3388. if(rval.order.length === rval.capacity) {
  3389. var key = rval.order.shift();
  3390. delete rval.cache[key];
  3391. }
  3392. // add session to cache
  3393. var key = forge.util.bytesToHex(sessionId);
  3394. rval.order.push(key);
  3395. rval.cache[key] = session;
  3396. };
  3397. }
  3398. return rval;
  3399. };
  3400. /**
  3401. * Creates a new TLS connection.
  3402. *
  3403. * See public createConnection() docs for more details.
  3404. *
  3405. * @param options the options for this connection.
  3406. *
  3407. * @return the new TLS connection.
  3408. */
  3409. tls.createConnection = function(options) {
  3410. var caStore = null;
  3411. if(options.caStore) {
  3412. // if CA store is an array, convert it to a CA store object
  3413. if(forge.util.isArray(options.caStore)) {
  3414. caStore = forge.pki.createCaStore(options.caStore);
  3415. } else {
  3416. caStore = options.caStore;
  3417. }
  3418. } else {
  3419. // create empty CA store
  3420. caStore = forge.pki.createCaStore();
  3421. }
  3422. // setup default cipher suites
  3423. var cipherSuites = options.cipherSuites || null;
  3424. if(cipherSuites === null) {
  3425. cipherSuites = [];
  3426. for(var key in tls.CipherSuites) {
  3427. cipherSuites.push(tls.CipherSuites[key]);
  3428. }
  3429. }
  3430. // set default entity
  3431. var entity = (options.server || false) ?
  3432. tls.ConnectionEnd.server : tls.ConnectionEnd.client;
  3433. // create session cache if requested
  3434. var sessionCache = options.sessionCache ?
  3435. tls.createSessionCache(options.sessionCache) : null;
  3436. // create TLS connection
  3437. var c = {
  3438. version: {major: tls.Version.major, minor: tls.Version.minor},
  3439. entity: entity,
  3440. sessionId: options.sessionId,
  3441. caStore: caStore,
  3442. sessionCache: sessionCache,
  3443. cipherSuites: cipherSuites,
  3444. connected: options.connected,
  3445. virtualHost: options.virtualHost || null,
  3446. verifyClient: options.verifyClient || false,
  3447. verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},
  3448. verifyOptions: options.verifyOptions || {},
  3449. getCertificate: options.getCertificate || null,
  3450. getPrivateKey: options.getPrivateKey || null,
  3451. getSignature: options.getSignature || null,
  3452. input: forge.util.createBuffer(),
  3453. tlsData: forge.util.createBuffer(),
  3454. data: forge.util.createBuffer(),
  3455. tlsDataReady: options.tlsDataReady,
  3456. dataReady: options.dataReady,
  3457. heartbeatReceived: options.heartbeatReceived,
  3458. closed: options.closed,
  3459. error: function(c, ex) {
  3460. // set origin if not set
  3461. ex.origin = ex.origin ||
  3462. ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');
  3463. // send TLS alert
  3464. if(ex.send) {
  3465. tls.queue(c, tls.createAlert(c, ex.alert));
  3466. tls.flush(c);
  3467. }
  3468. // error is fatal by default
  3469. var fatal = (ex.fatal !== false);
  3470. if(fatal) {
  3471. // set fail flag
  3472. c.fail = true;
  3473. }
  3474. // call error handler first
  3475. options.error(c, ex);
  3476. if(fatal) {
  3477. // fatal error, close connection, do not clear fail
  3478. c.close(false);
  3479. }
  3480. },
  3481. deflate: options.deflate || null,
  3482. inflate: options.inflate || null
  3483. };
  3484. /**
  3485. * Resets a closed TLS connection for reuse. Called in c.close().
  3486. *
  3487. * @param clearFail true to clear the fail flag (default: true).
  3488. */
  3489. c.reset = function(clearFail) {
  3490. c.version = {major: tls.Version.major, minor: tls.Version.minor};
  3491. c.record = null;
  3492. c.session = null;
  3493. c.peerCertificate = null;
  3494. c.state = {
  3495. pending: null,
  3496. current: null
  3497. };
  3498. c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;
  3499. c.fragmented = null;
  3500. c.records = [];
  3501. c.open = false;
  3502. c.handshakes = 0;
  3503. c.handshaking = false;
  3504. c.isConnected = false;
  3505. c.fail = !(clearFail || typeof(clearFail) === 'undefined');
  3506. c.input.clear();
  3507. c.tlsData.clear();
  3508. c.data.clear();
  3509. c.state.current = tls.createConnectionState(c);
  3510. };
  3511. // do initial reset of connection
  3512. c.reset();
  3513. /**
  3514. * Updates the current TLS engine state based on the given record.
  3515. *
  3516. * @param c the TLS connection.
  3517. * @param record the TLS record to act on.
  3518. */
  3519. var _update = function(c, record) {
  3520. // get record handler (align type in table by subtracting lowest)
  3521. var aligned = record.type - tls.ContentType.change_cipher_spec;
  3522. var handlers = ctTable[c.entity][c.expect];
  3523. if(aligned in handlers) {
  3524. handlers[aligned](c, record);
  3525. } else {
  3526. // unexpected record
  3527. tls.handleUnexpected(c, record);
  3528. }
  3529. };
  3530. /**
  3531. * Reads the record header and initializes the next record on the given
  3532. * connection.
  3533. *
  3534. * @param c the TLS connection with the next record.
  3535. *
  3536. * @return 0 if the input data could be processed, otherwise the
  3537. * number of bytes required for data to be processed.
  3538. */
  3539. var _readRecordHeader = function(c) {
  3540. var rval = 0;
  3541. // get input buffer and its length
  3542. var b = c.input;
  3543. var len = b.length();
  3544. // need at least 5 bytes to initialize a record
  3545. if(len < 5) {
  3546. rval = 5 - len;
  3547. } else {
  3548. // enough bytes for header
  3549. // initialize record
  3550. c.record = {
  3551. type: b.getByte(),
  3552. version: {
  3553. major: b.getByte(),
  3554. minor: b.getByte()
  3555. },
  3556. length: b.getInt16(),
  3557. fragment: forge.util.createBuffer(),
  3558. ready: false
  3559. };
  3560. // check record version
  3561. var compatibleVersion = (c.record.version.major === c.version.major);
  3562. if(compatibleVersion && c.session && c.session.version) {
  3563. // session version already set, require same minor version
  3564. compatibleVersion = (c.record.version.minor === c.version.minor);
  3565. }
  3566. if(!compatibleVersion) {
  3567. c.error(c, {
  3568. message: 'Incompatible TLS version.',
  3569. send: true,
  3570. alert: {
  3571. level: tls.Alert.Level.fatal,
  3572. description: tls.Alert.Description.protocol_version
  3573. }
  3574. });
  3575. }
  3576. }
  3577. return rval;
  3578. };
  3579. /**
  3580. * Reads the next record's contents and appends its message to any
  3581. * previously fragmented message.
  3582. *
  3583. * @param c the TLS connection with the next record.
  3584. *
  3585. * @return 0 if the input data could be processed, otherwise the
  3586. * number of bytes required for data to be processed.
  3587. */
  3588. var _readRecord = function(c) {
  3589. var rval = 0;
  3590. // ensure there is enough input data to get the entire record
  3591. var b = c.input;
  3592. var len = b.length();
  3593. if(len < c.record.length) {
  3594. // not enough data yet, return how much is required
  3595. rval = c.record.length - len;
  3596. } else {
  3597. // there is enough data to parse the pending record
  3598. // fill record fragment and compact input buffer
  3599. c.record.fragment.putBytes(b.getBytes(c.record.length));
  3600. b.compact();
  3601. // update record using current read state
  3602. var s = c.state.current.read;
  3603. if(s.update(c, c.record)) {
  3604. // see if there is a previously fragmented message that the
  3605. // new record's message fragment should be appended to
  3606. if(c.fragmented !== null) {
  3607. // if the record type matches a previously fragmented
  3608. // record, append the record fragment to it
  3609. if(c.fragmented.type === c.record.type) {
  3610. // concatenate record fragments
  3611. c.fragmented.fragment.putBuffer(c.record.fragment);
  3612. c.record = c.fragmented;
  3613. } else {
  3614. // error, invalid fragmented record
  3615. c.error(c, {
  3616. message: 'Invalid fragmented record.',
  3617. send: true,
  3618. alert: {
  3619. level: tls.Alert.Level.fatal,
  3620. description:
  3621. tls.Alert.Description.unexpected_message
  3622. }
  3623. });
  3624. }
  3625. }
  3626. // record is now ready
  3627. c.record.ready = true;
  3628. }
  3629. }
  3630. return rval;
  3631. };
  3632. /**
  3633. * Performs a handshake using the TLS Handshake Protocol, as a client.
  3634. *
  3635. * This method should only be called if the connection is in client mode.
  3636. *
  3637. * @param sessionId the session ID to use, null to start a new one.
  3638. */
  3639. c.handshake = function(sessionId) {
  3640. // error to call this in non-client mode
  3641. if(c.entity !== tls.ConnectionEnd.client) {
  3642. // not fatal error
  3643. c.error(c, {
  3644. message: 'Cannot initiate handshake as a server.',
  3645. fatal: false
  3646. });
  3647. } else if(c.handshaking) {
  3648. // handshake is already in progress, fail but not fatal error
  3649. c.error(c, {
  3650. message: 'Handshake already in progress.',
  3651. fatal: false
  3652. });
  3653. } else {
  3654. // clear fail flag on reuse
  3655. if(c.fail && !c.open && c.handshakes === 0) {
  3656. c.fail = false;
  3657. }
  3658. // now handshaking
  3659. c.handshaking = true;
  3660. // default to blank (new session)
  3661. sessionId = sessionId || '';
  3662. // if a session ID was specified, try to find it in the cache
  3663. var session = null;
  3664. if(sessionId.length > 0) {
  3665. if(c.sessionCache) {
  3666. session = c.sessionCache.getSession(sessionId);
  3667. }
  3668. // matching session not found in cache, clear session ID
  3669. if(session === null) {
  3670. sessionId = '';
  3671. }
  3672. }
  3673. // no session given, grab a session from the cache, if available
  3674. if(sessionId.length === 0 && c.sessionCache) {
  3675. session = c.sessionCache.getSession();
  3676. if(session !== null) {
  3677. sessionId = session.id;
  3678. }
  3679. }
  3680. // set up session
  3681. c.session = {
  3682. id: sessionId,
  3683. version: null,
  3684. cipherSuite: null,
  3685. compressionMethod: null,
  3686. serverCertificate: null,
  3687. certificateRequest: null,
  3688. clientCertificate: null,
  3689. sp: {},
  3690. md5: forge.md.md5.create(),
  3691. sha1: forge.md.sha1.create()
  3692. };
  3693. // use existing session information
  3694. if(session) {
  3695. // only update version on connection, session version not yet set
  3696. c.version = session.version;
  3697. c.session.sp = session.sp;
  3698. }
  3699. // generate new client random
  3700. c.session.sp.client_random = tls.createRandom().getBytes();
  3701. // connection now open
  3702. c.open = true;
  3703. // send hello
  3704. tls.queue(c, tls.createRecord(c, {
  3705. type: tls.ContentType.handshake,
  3706. data: tls.createClientHello(c)
  3707. }));
  3708. tls.flush(c);
  3709. }
  3710. };
  3711. /**
  3712. * Called when TLS protocol data has been received from somewhere and should
  3713. * be processed by the TLS engine.
  3714. *
  3715. * @param data the TLS protocol data, as a string, to process.
  3716. *
  3717. * @return 0 if the data could be processed, otherwise the number of bytes
  3718. * required for data to be processed.
  3719. */
  3720. c.process = function(data) {
  3721. var rval = 0;
  3722. // buffer input data
  3723. if(data) {
  3724. c.input.putBytes(data);
  3725. }
  3726. // process next record if no failure, process will be called after
  3727. // each record is handled (since handling can be asynchronous)
  3728. if(!c.fail) {
  3729. // reset record if ready and now empty
  3730. if(c.record !== null &&
  3731. c.record.ready && c.record.fragment.isEmpty()) {
  3732. c.record = null;
  3733. }
  3734. // if there is no pending record, try to read record header
  3735. if(c.record === null) {
  3736. rval = _readRecordHeader(c);
  3737. }
  3738. // read the next record (if record not yet ready)
  3739. if(!c.fail && c.record !== null && !c.record.ready) {
  3740. rval = _readRecord(c);
  3741. }
  3742. // record ready to be handled, update engine state
  3743. if(!c.fail && c.record !== null && c.record.ready) {
  3744. _update(c, c.record);
  3745. }
  3746. }
  3747. return rval;
  3748. };
  3749. /**
  3750. * Requests that application data be packaged into a TLS record. The
  3751. * tlsDataReady handler will be called when the TLS record(s) have been
  3752. * prepared.
  3753. *
  3754. * @param data the application data, as a raw 'binary' encoded string, to
  3755. * be sent; to send utf-16/utf-8 string data, use the return value
  3756. * of util.encodeUtf8(str).
  3757. *
  3758. * @return true on success, false on failure.
  3759. */
  3760. c.prepare = function(data) {
  3761. tls.queue(c, tls.createRecord(c, {
  3762. type: tls.ContentType.application_data,
  3763. data: forge.util.createBuffer(data)
  3764. }));
  3765. return tls.flush(c);
  3766. };
  3767. /**
  3768. * Requests that a heartbeat request be packaged into a TLS record for
  3769. * transmission. The tlsDataReady handler will be called when TLS record(s)
  3770. * have been prepared.
  3771. *
  3772. * When a heartbeat response has been received, the heartbeatReceived
  3773. * handler will be called with the matching payload. This handler can
  3774. * be used to clear a retransmission timer, etc.
  3775. *
  3776. * @param payload the heartbeat data to send as the payload in the message.
  3777. * @param [payloadLength] the payload length to use, defaults to the
  3778. * actual payload length.
  3779. *
  3780. * @return true on success, false on failure.
  3781. */
  3782. c.prepareHeartbeatRequest = function(payload, payloadLength) {
  3783. if(payload instanceof forge.util.ByteBuffer) {
  3784. payload = payload.bytes();
  3785. }
  3786. if(typeof payloadLength === 'undefined') {
  3787. payloadLength = payload.length;
  3788. }
  3789. c.expectedHeartbeatPayload = payload;
  3790. tls.queue(c, tls.createRecord(c, {
  3791. type: tls.ContentType.heartbeat,
  3792. data: tls.createHeartbeat(
  3793. tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)
  3794. }));
  3795. return tls.flush(c);
  3796. };
  3797. /**
  3798. * Closes the connection (sends a close_notify alert).
  3799. *
  3800. * @param clearFail true to clear the fail flag (default: true).
  3801. */
  3802. c.close = function(clearFail) {
  3803. // save session if connection didn't fail
  3804. if(!c.fail && c.sessionCache && c.session) {
  3805. // only need to preserve session ID, version, and security params
  3806. var session = {
  3807. id: c.session.id,
  3808. version: c.session.version,
  3809. sp: c.session.sp
  3810. };
  3811. session.sp.keys = null;
  3812. c.sessionCache.setSession(session.id, session);
  3813. }
  3814. if(c.open) {
  3815. // connection no longer open, clear input
  3816. c.open = false;
  3817. c.input.clear();
  3818. // if connected or handshaking, send an alert
  3819. if(c.isConnected || c.handshaking) {
  3820. c.isConnected = c.handshaking = false;
  3821. // send close_notify alert
  3822. tls.queue(c, tls.createAlert(c, {
  3823. level: tls.Alert.Level.warning,
  3824. description: tls.Alert.Description.close_notify
  3825. }));
  3826. tls.flush(c);
  3827. }
  3828. // call handler
  3829. c.closed(c);
  3830. }
  3831. // reset TLS connection, do not clear fail flag
  3832. c.reset(clearFail);
  3833. };
  3834. return c;
  3835. };
  3836. /* TLS API */
  3837. module.exports = forge.tls = forge.tls || {};
  3838. // expose non-functions
  3839. for(var key in tls) {
  3840. if(typeof tls[key] !== 'function') {
  3841. forge.tls[key] = tls[key];
  3842. }
  3843. }
  3844. // expose prf_tls1 for testing
  3845. forge.tls.prf_tls1 = prf_TLS1;
  3846. // expose sha1 hmac method
  3847. forge.tls.hmac_sha1 = hmac_sha1;
  3848. // expose session cache creation
  3849. forge.tls.createSessionCache = tls.createSessionCache;
  3850. /**
  3851. * Creates a new TLS connection. This does not make any assumptions about the
  3852. * transport layer that TLS is working on top of, ie: it does not assume there
  3853. * is a TCP/IP connection or establish one. A TLS connection is totally
  3854. * abstracted away from the layer is runs on top of, it merely establishes a
  3855. * secure channel between a client" and a "server".
  3856. *
  3857. * A TLS connection contains 4 connection states: pending read and write, and
  3858. * current read and write.
  3859. *
  3860. * At initialization, the current read and write states will be null. Only once
  3861. * the security parameters have been set and the keys have been generated can
  3862. * the pending states be converted into current states. Current states will be
  3863. * updated for each record processed.
  3864. *
  3865. * A custom certificate verify callback may be provided to check information
  3866. * like the common name on the server's certificate. It will be called for
  3867. * every certificate in the chain. It has the following signature:
  3868. *
  3869. * variable func(c, certs, index, preVerify)
  3870. * Where:
  3871. * c The TLS connection
  3872. * verified Set to true if certificate was verified, otherwise the alert
  3873. * tls.Alert.Description for why the certificate failed.
  3874. * depth The current index in the chain, where 0 is the server's cert.
  3875. * certs The certificate chain, *NOTE* if the server was anonymous then
  3876. * the chain will be empty.
  3877. *
  3878. * The function returns true on success and on failure either the appropriate
  3879. * tls.Alert.Description or an object with 'alert' set to the appropriate
  3880. * tls.Alert.Description and 'message' set to a custom error message. If true
  3881. * is not returned then the connection will abort using, in order of
  3882. * availability, first the returned alert description, second the preVerify
  3883. * alert description, and lastly the default 'bad_certificate'.
  3884. *
  3885. * There are three callbacks that can be used to make use of client-side
  3886. * certificates where each takes the TLS connection as the first parameter:
  3887. *
  3888. * getCertificate(conn, hint)
  3889. * The second parameter is a hint as to which certificate should be
  3890. * returned. If the connection entity is a client, then the hint will be
  3891. * the CertificateRequest message from the server that is part of the
  3892. * TLS protocol. If the connection entity is a server, then it will be
  3893. * the servername list provided via an SNI extension the ClientHello, if
  3894. * one was provided (empty array if not). The hint can be examined to
  3895. * determine which certificate to use (advanced). Most implementations
  3896. * will just return a certificate. The return value must be a
  3897. * PEM-formatted certificate or an array of PEM-formatted certificates
  3898. * that constitute a certificate chain, with the first in the array/chain
  3899. * being the client's certificate.
  3900. * getPrivateKey(conn, certificate)
  3901. * The second parameter is an forge.pki X.509 certificate object that
  3902. * is associated with the requested private key. The return value must
  3903. * be a PEM-formatted private key.
  3904. * getSignature(conn, bytes, callback)
  3905. * This callback can be used instead of getPrivateKey if the private key
  3906. * is not directly accessible in javascript or should not be. For
  3907. * instance, a secure external web service could provide the signature
  3908. * in exchange for appropriate credentials. The second parameter is a
  3909. * string of bytes to be signed that are part of the TLS protocol. These
  3910. * bytes are used to verify that the private key for the previously
  3911. * provided client-side certificate is accessible to the client. The
  3912. * callback is a function that takes 2 parameters, the TLS connection
  3913. * and the RSA encrypted (signed) bytes as a string. This callback must
  3914. * be called once the signature is ready.
  3915. *
  3916. * @param options the options for this connection:
  3917. * server: true if the connection is server-side, false for client.
  3918. * sessionId: a session ID to reuse, null for a new connection.
  3919. * caStore: an array of certificates to trust.
  3920. * sessionCache: a session cache to use.
  3921. * cipherSuites: an optional array of cipher suites to use,
  3922. * see tls.CipherSuites.
  3923. * connected: function(conn) called when the first handshake completes.
  3924. * virtualHost: the virtual server name to use in a TLS SNI extension.
  3925. * verifyClient: true to require a client certificate in server mode,
  3926. * 'optional' to request one, false not to (default: false).
  3927. * verify: a handler used to custom verify certificates in the chain.
  3928. * verifyOptions: an object with options for the certificate chain validation.
  3929. * See documentation of pki.verifyCertificateChain for possible options.
  3930. * verifyOptions.verify is ignored. If you wish to specify a verify handler
  3931. * use the verify key.
  3932. * getCertificate: an optional callback used to get a certificate or
  3933. * a chain of certificates (as an array).
  3934. * getPrivateKey: an optional callback used to get a private key.
  3935. * getSignature: an optional callback used to get a signature.
  3936. * tlsDataReady: function(conn) called when TLS protocol data has been
  3937. * prepared and is ready to be used (typically sent over a socket
  3938. * connection to its destination), read from conn.tlsData buffer.
  3939. * dataReady: function(conn) called when application data has
  3940. * been parsed from a TLS record and should be consumed by the
  3941. * application, read from conn.data buffer.
  3942. * closed: function(conn) called when the connection has been closed.
  3943. * error: function(conn, error) called when there was an error.
  3944. * deflate: function(inBytes) if provided, will deflate TLS records using
  3945. * the deflate algorithm if the server supports it.
  3946. * inflate: function(inBytes) if provided, will inflate TLS records using
  3947. * the deflate algorithm if the server supports it.
  3948. *
  3949. * @return the new TLS connection.
  3950. */
  3951. forge.tls.createConnection = tls.createConnection;