tls.js 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269
  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. // verify chain
  3272. forge.pki.verifyCertificateChain(c.caStore, chain,
  3273. function verify(vfd, depth, chain) {
  3274. // convert pki.certificateError to tls alert description
  3275. var desc = _certErrorToAlertDesc(vfd);
  3276. // call application callback
  3277. var ret = c.verify(c, vfd, depth, chain);
  3278. if(ret !== true) {
  3279. if(typeof ret === 'object' && !forge.util.isArray(ret)) {
  3280. // throw custom error
  3281. var error = new Error('The application rejected the certificate.');
  3282. error.send = true;
  3283. error.alert = {
  3284. level: tls.Alert.Level.fatal,
  3285. description: tls.Alert.Description.bad_certificate
  3286. };
  3287. if(ret.message) {
  3288. error.message = ret.message;
  3289. }
  3290. if(ret.alert) {
  3291. error.alert.description = ret.alert;
  3292. }
  3293. throw error;
  3294. }
  3295. // convert tls alert description to pki.certificateError
  3296. if(ret !== vfd) {
  3297. ret = _alertDescToCertError(ret);
  3298. }
  3299. }
  3300. return ret;
  3301. });
  3302. } catch(ex) {
  3303. // build tls error if not already customized
  3304. var err = ex;
  3305. if(typeof err !== 'object' || forge.util.isArray(err)) {
  3306. err = {
  3307. send: true,
  3308. alert: {
  3309. level: tls.Alert.Level.fatal,
  3310. description: _certErrorToAlertDesc(ex)
  3311. }
  3312. };
  3313. }
  3314. if(!('send' in err)) {
  3315. err.send = true;
  3316. }
  3317. if(!('alert' in err)) {
  3318. err.alert = {
  3319. level: tls.Alert.Level.fatal,
  3320. description: _certErrorToAlertDesc(err.error)
  3321. };
  3322. }
  3323. // send error
  3324. c.error(c, err);
  3325. }
  3326. return !c.fail;
  3327. };
  3328. /**
  3329. * Creates a new TLS session cache.
  3330. *
  3331. * @param cache optional map of session ID to cached session.
  3332. * @param capacity the maximum size for the cache (default: 100).
  3333. *
  3334. * @return the new TLS session cache.
  3335. */
  3336. tls.createSessionCache = function(cache, capacity) {
  3337. var rval = null;
  3338. // assume input is already a session cache object
  3339. if(cache && cache.getSession && cache.setSession && cache.order) {
  3340. rval = cache;
  3341. } else {
  3342. // create cache
  3343. rval = {};
  3344. rval.cache = cache || {};
  3345. rval.capacity = Math.max(capacity || 100, 1);
  3346. rval.order = [];
  3347. // store order for sessions, delete session overflow
  3348. for(var key in cache) {
  3349. if(rval.order.length <= capacity) {
  3350. rval.order.push(key);
  3351. } else {
  3352. delete cache[key];
  3353. }
  3354. }
  3355. // get a session from a session ID (or get any session)
  3356. rval.getSession = function(sessionId) {
  3357. var session = null;
  3358. var key = null;
  3359. // if session ID provided, use it
  3360. if(sessionId) {
  3361. key = forge.util.bytesToHex(sessionId);
  3362. } else if(rval.order.length > 0) {
  3363. // get first session from cache
  3364. key = rval.order[0];
  3365. }
  3366. if(key !== null && key in rval.cache) {
  3367. // get cached session and remove from cache
  3368. session = rval.cache[key];
  3369. delete rval.cache[key];
  3370. for(var i in rval.order) {
  3371. if(rval.order[i] === key) {
  3372. rval.order.splice(i, 1);
  3373. break;
  3374. }
  3375. }
  3376. }
  3377. return session;
  3378. };
  3379. // set a session in the cache
  3380. rval.setSession = function(sessionId, session) {
  3381. // remove session from cache if at capacity
  3382. if(rval.order.length === rval.capacity) {
  3383. var key = rval.order.shift();
  3384. delete rval.cache[key];
  3385. }
  3386. // add session to cache
  3387. var key = forge.util.bytesToHex(sessionId);
  3388. rval.order.push(key);
  3389. rval.cache[key] = session;
  3390. };
  3391. }
  3392. return rval;
  3393. };
  3394. /**
  3395. * Creates a new TLS connection.
  3396. *
  3397. * See public createConnection() docs for more details.
  3398. *
  3399. * @param options the options for this connection.
  3400. *
  3401. * @return the new TLS connection.
  3402. */
  3403. tls.createConnection = function(options) {
  3404. var caStore = null;
  3405. if(options.caStore) {
  3406. // if CA store is an array, convert it to a CA store object
  3407. if(forge.util.isArray(options.caStore)) {
  3408. caStore = forge.pki.createCaStore(options.caStore);
  3409. } else {
  3410. caStore = options.caStore;
  3411. }
  3412. } else {
  3413. // create empty CA store
  3414. caStore = forge.pki.createCaStore();
  3415. }
  3416. // setup default cipher suites
  3417. var cipherSuites = options.cipherSuites || null;
  3418. if(cipherSuites === null) {
  3419. cipherSuites = [];
  3420. for(var key in tls.CipherSuites) {
  3421. cipherSuites.push(tls.CipherSuites[key]);
  3422. }
  3423. }
  3424. // set default entity
  3425. var entity = (options.server || false) ?
  3426. tls.ConnectionEnd.server : tls.ConnectionEnd.client;
  3427. // create session cache if requested
  3428. var sessionCache = options.sessionCache ?
  3429. tls.createSessionCache(options.sessionCache) : null;
  3430. // create TLS connection
  3431. var c = {
  3432. version: {major: tls.Version.major, minor: tls.Version.minor},
  3433. entity: entity,
  3434. sessionId: options.sessionId,
  3435. caStore: caStore,
  3436. sessionCache: sessionCache,
  3437. cipherSuites: cipherSuites,
  3438. connected: options.connected,
  3439. virtualHost: options.virtualHost || null,
  3440. verifyClient: options.verifyClient || false,
  3441. verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;},
  3442. getCertificate: options.getCertificate || null,
  3443. getPrivateKey: options.getPrivateKey || null,
  3444. getSignature: options.getSignature || null,
  3445. input: forge.util.createBuffer(),
  3446. tlsData: forge.util.createBuffer(),
  3447. data: forge.util.createBuffer(),
  3448. tlsDataReady: options.tlsDataReady,
  3449. dataReady: options.dataReady,
  3450. heartbeatReceived: options.heartbeatReceived,
  3451. closed: options.closed,
  3452. error: function(c, ex) {
  3453. // set origin if not set
  3454. ex.origin = ex.origin ||
  3455. ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server');
  3456. // send TLS alert
  3457. if(ex.send) {
  3458. tls.queue(c, tls.createAlert(c, ex.alert));
  3459. tls.flush(c);
  3460. }
  3461. // error is fatal by default
  3462. var fatal = (ex.fatal !== false);
  3463. if(fatal) {
  3464. // set fail flag
  3465. c.fail = true;
  3466. }
  3467. // call error handler first
  3468. options.error(c, ex);
  3469. if(fatal) {
  3470. // fatal error, close connection, do not clear fail
  3471. c.close(false);
  3472. }
  3473. },
  3474. deflate: options.deflate || null,
  3475. inflate: options.inflate || null
  3476. };
  3477. /**
  3478. * Resets a closed TLS connection for reuse. Called in c.close().
  3479. *
  3480. * @param clearFail true to clear the fail flag (default: true).
  3481. */
  3482. c.reset = function(clearFail) {
  3483. c.version = {major: tls.Version.major, minor: tls.Version.minor};
  3484. c.record = null;
  3485. c.session = null;
  3486. c.peerCertificate = null;
  3487. c.state = {
  3488. pending: null,
  3489. current: null
  3490. };
  3491. c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE;
  3492. c.fragmented = null;
  3493. c.records = [];
  3494. c.open = false;
  3495. c.handshakes = 0;
  3496. c.handshaking = false;
  3497. c.isConnected = false;
  3498. c.fail = !(clearFail || typeof(clearFail) === 'undefined');
  3499. c.input.clear();
  3500. c.tlsData.clear();
  3501. c.data.clear();
  3502. c.state.current = tls.createConnectionState(c);
  3503. };
  3504. // do initial reset of connection
  3505. c.reset();
  3506. /**
  3507. * Updates the current TLS engine state based on the given record.
  3508. *
  3509. * @param c the TLS connection.
  3510. * @param record the TLS record to act on.
  3511. */
  3512. var _update = function(c, record) {
  3513. // get record handler (align type in table by subtracting lowest)
  3514. var aligned = record.type - tls.ContentType.change_cipher_spec;
  3515. var handlers = ctTable[c.entity][c.expect];
  3516. if(aligned in handlers) {
  3517. handlers[aligned](c, record);
  3518. } else {
  3519. // unexpected record
  3520. tls.handleUnexpected(c, record);
  3521. }
  3522. };
  3523. /**
  3524. * Reads the record header and initializes the next record on the given
  3525. * connection.
  3526. *
  3527. * @param c the TLS connection with the next record.
  3528. *
  3529. * @return 0 if the input data could be processed, otherwise the
  3530. * number of bytes required for data to be processed.
  3531. */
  3532. var _readRecordHeader = function(c) {
  3533. var rval = 0;
  3534. // get input buffer and its length
  3535. var b = c.input;
  3536. var len = b.length();
  3537. // need at least 5 bytes to initialize a record
  3538. if(len < 5) {
  3539. rval = 5 - len;
  3540. } else {
  3541. // enough bytes for header
  3542. // initialize record
  3543. c.record = {
  3544. type: b.getByte(),
  3545. version: {
  3546. major: b.getByte(),
  3547. minor: b.getByte()
  3548. },
  3549. length: b.getInt16(),
  3550. fragment: forge.util.createBuffer(),
  3551. ready: false
  3552. };
  3553. // check record version
  3554. var compatibleVersion = (c.record.version.major === c.version.major);
  3555. if(compatibleVersion && c.session && c.session.version) {
  3556. // session version already set, require same minor version
  3557. compatibleVersion = (c.record.version.minor === c.version.minor);
  3558. }
  3559. if(!compatibleVersion) {
  3560. c.error(c, {
  3561. message: 'Incompatible TLS version.',
  3562. send: true,
  3563. alert: {
  3564. level: tls.Alert.Level.fatal,
  3565. description: tls.Alert.Description.protocol_version
  3566. }
  3567. });
  3568. }
  3569. }
  3570. return rval;
  3571. };
  3572. /**
  3573. * Reads the next record's contents and appends its message to any
  3574. * previously fragmented message.
  3575. *
  3576. * @param c the TLS connection with the next record.
  3577. *
  3578. * @return 0 if the input data could be processed, otherwise the
  3579. * number of bytes required for data to be processed.
  3580. */
  3581. var _readRecord = function(c) {
  3582. var rval = 0;
  3583. // ensure there is enough input data to get the entire record
  3584. var b = c.input;
  3585. var len = b.length();
  3586. if(len < c.record.length) {
  3587. // not enough data yet, return how much is required
  3588. rval = c.record.length - len;
  3589. } else {
  3590. // there is enough data to parse the pending record
  3591. // fill record fragment and compact input buffer
  3592. c.record.fragment.putBytes(b.getBytes(c.record.length));
  3593. b.compact();
  3594. // update record using current read state
  3595. var s = c.state.current.read;
  3596. if(s.update(c, c.record)) {
  3597. // see if there is a previously fragmented message that the
  3598. // new record's message fragment should be appended to
  3599. if(c.fragmented !== null) {
  3600. // if the record type matches a previously fragmented
  3601. // record, append the record fragment to it
  3602. if(c.fragmented.type === c.record.type) {
  3603. // concatenate record fragments
  3604. c.fragmented.fragment.putBuffer(c.record.fragment);
  3605. c.record = c.fragmented;
  3606. } else {
  3607. // error, invalid fragmented record
  3608. c.error(c, {
  3609. message: 'Invalid fragmented record.',
  3610. send: true,
  3611. alert: {
  3612. level: tls.Alert.Level.fatal,
  3613. description:
  3614. tls.Alert.Description.unexpected_message
  3615. }
  3616. });
  3617. }
  3618. }
  3619. // record is now ready
  3620. c.record.ready = true;
  3621. }
  3622. }
  3623. return rval;
  3624. };
  3625. /**
  3626. * Performs a handshake using the TLS Handshake Protocol, as a client.
  3627. *
  3628. * This method should only be called if the connection is in client mode.
  3629. *
  3630. * @param sessionId the session ID to use, null to start a new one.
  3631. */
  3632. c.handshake = function(sessionId) {
  3633. // error to call this in non-client mode
  3634. if(c.entity !== tls.ConnectionEnd.client) {
  3635. // not fatal error
  3636. c.error(c, {
  3637. message: 'Cannot initiate handshake as a server.',
  3638. fatal: false
  3639. });
  3640. } else if(c.handshaking) {
  3641. // handshake is already in progress, fail but not fatal error
  3642. c.error(c, {
  3643. message: 'Handshake already in progress.',
  3644. fatal: false
  3645. });
  3646. } else {
  3647. // clear fail flag on reuse
  3648. if(c.fail && !c.open && c.handshakes === 0) {
  3649. c.fail = false;
  3650. }
  3651. // now handshaking
  3652. c.handshaking = true;
  3653. // default to blank (new session)
  3654. sessionId = sessionId || '';
  3655. // if a session ID was specified, try to find it in the cache
  3656. var session = null;
  3657. if(sessionId.length > 0) {
  3658. if(c.sessionCache) {
  3659. session = c.sessionCache.getSession(sessionId);
  3660. }
  3661. // matching session not found in cache, clear session ID
  3662. if(session === null) {
  3663. sessionId = '';
  3664. }
  3665. }
  3666. // no session given, grab a session from the cache, if available
  3667. if(sessionId.length === 0 && c.sessionCache) {
  3668. session = c.sessionCache.getSession();
  3669. if(session !== null) {
  3670. sessionId = session.id;
  3671. }
  3672. }
  3673. // set up session
  3674. c.session = {
  3675. id: sessionId,
  3676. version: null,
  3677. cipherSuite: null,
  3678. compressionMethod: null,
  3679. serverCertificate: null,
  3680. certificateRequest: null,
  3681. clientCertificate: null,
  3682. sp: {},
  3683. md5: forge.md.md5.create(),
  3684. sha1: forge.md.sha1.create()
  3685. };
  3686. // use existing session information
  3687. if(session) {
  3688. // only update version on connection, session version not yet set
  3689. c.version = session.version;
  3690. c.session.sp = session.sp;
  3691. }
  3692. // generate new client random
  3693. c.session.sp.client_random = tls.createRandom().getBytes();
  3694. // connection now open
  3695. c.open = true;
  3696. // send hello
  3697. tls.queue(c, tls.createRecord(c, {
  3698. type: tls.ContentType.handshake,
  3699. data: tls.createClientHello(c)
  3700. }));
  3701. tls.flush(c);
  3702. }
  3703. };
  3704. /**
  3705. * Called when TLS protocol data has been received from somewhere and should
  3706. * be processed by the TLS engine.
  3707. *
  3708. * @param data the TLS protocol data, as a string, to process.
  3709. *
  3710. * @return 0 if the data could be processed, otherwise the number of bytes
  3711. * required for data to be processed.
  3712. */
  3713. c.process = function(data) {
  3714. var rval = 0;
  3715. // buffer input data
  3716. if(data) {
  3717. c.input.putBytes(data);
  3718. }
  3719. // process next record if no failure, process will be called after
  3720. // each record is handled (since handling can be asynchronous)
  3721. if(!c.fail) {
  3722. // reset record if ready and now empty
  3723. if(c.record !== null &&
  3724. c.record.ready && c.record.fragment.isEmpty()) {
  3725. c.record = null;
  3726. }
  3727. // if there is no pending record, try to read record header
  3728. if(c.record === null) {
  3729. rval = _readRecordHeader(c);
  3730. }
  3731. // read the next record (if record not yet ready)
  3732. if(!c.fail && c.record !== null && !c.record.ready) {
  3733. rval = _readRecord(c);
  3734. }
  3735. // record ready to be handled, update engine state
  3736. if(!c.fail && c.record !== null && c.record.ready) {
  3737. _update(c, c.record);
  3738. }
  3739. }
  3740. return rval;
  3741. };
  3742. /**
  3743. * Requests that application data be packaged into a TLS record. The
  3744. * tlsDataReady handler will be called when the TLS record(s) have been
  3745. * prepared.
  3746. *
  3747. * @param data the application data, as a raw 'binary' encoded string, to
  3748. * be sent; to send utf-16/utf-8 string data, use the return value
  3749. * of util.encodeUtf8(str).
  3750. *
  3751. * @return true on success, false on failure.
  3752. */
  3753. c.prepare = function(data) {
  3754. tls.queue(c, tls.createRecord(c, {
  3755. type: tls.ContentType.application_data,
  3756. data: forge.util.createBuffer(data)
  3757. }));
  3758. return tls.flush(c);
  3759. };
  3760. /**
  3761. * Requests that a heartbeat request be packaged into a TLS record for
  3762. * transmission. The tlsDataReady handler will be called when TLS record(s)
  3763. * have been prepared.
  3764. *
  3765. * When a heartbeat response has been received, the heartbeatReceived
  3766. * handler will be called with the matching payload. This handler can
  3767. * be used to clear a retransmission timer, etc.
  3768. *
  3769. * @param payload the heartbeat data to send as the payload in the message.
  3770. * @param [payloadLength] the payload length to use, defaults to the
  3771. * actual payload length.
  3772. *
  3773. * @return true on success, false on failure.
  3774. */
  3775. c.prepareHeartbeatRequest = function(payload, payloadLength) {
  3776. if(payload instanceof forge.util.ByteBuffer) {
  3777. payload = payload.bytes();
  3778. }
  3779. if(typeof payloadLength === 'undefined') {
  3780. payloadLength = payload.length;
  3781. }
  3782. c.expectedHeartbeatPayload = payload;
  3783. tls.queue(c, tls.createRecord(c, {
  3784. type: tls.ContentType.heartbeat,
  3785. data: tls.createHeartbeat(
  3786. tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength)
  3787. }));
  3788. return tls.flush(c);
  3789. };
  3790. /**
  3791. * Closes the connection (sends a close_notify alert).
  3792. *
  3793. * @param clearFail true to clear the fail flag (default: true).
  3794. */
  3795. c.close = function(clearFail) {
  3796. // save session if connection didn't fail
  3797. if(!c.fail && c.sessionCache && c.session) {
  3798. // only need to preserve session ID, version, and security params
  3799. var session = {
  3800. id: c.session.id,
  3801. version: c.session.version,
  3802. sp: c.session.sp
  3803. };
  3804. session.sp.keys = null;
  3805. c.sessionCache.setSession(session.id, session);
  3806. }
  3807. if(c.open) {
  3808. // connection no longer open, clear input
  3809. c.open = false;
  3810. c.input.clear();
  3811. // if connected or handshaking, send an alert
  3812. if(c.isConnected || c.handshaking) {
  3813. c.isConnected = c.handshaking = false;
  3814. // send close_notify alert
  3815. tls.queue(c, tls.createAlert(c, {
  3816. level: tls.Alert.Level.warning,
  3817. description: tls.Alert.Description.close_notify
  3818. }));
  3819. tls.flush(c);
  3820. }
  3821. // call handler
  3822. c.closed(c);
  3823. }
  3824. // reset TLS connection, do not clear fail flag
  3825. c.reset(clearFail);
  3826. };
  3827. return c;
  3828. };
  3829. /* TLS API */
  3830. module.exports = forge.tls = forge.tls || {};
  3831. // expose non-functions
  3832. for(var key in tls) {
  3833. if(typeof tls[key] !== 'function') {
  3834. forge.tls[key] = tls[key];
  3835. }
  3836. }
  3837. // expose prf_tls1 for testing
  3838. forge.tls.prf_tls1 = prf_TLS1;
  3839. // expose sha1 hmac method
  3840. forge.tls.hmac_sha1 = hmac_sha1;
  3841. // expose session cache creation
  3842. forge.tls.createSessionCache = tls.createSessionCache;
  3843. /**
  3844. * Creates a new TLS connection. This does not make any assumptions about the
  3845. * transport layer that TLS is working on top of, ie: it does not assume there
  3846. * is a TCP/IP connection or establish one. A TLS connection is totally
  3847. * abstracted away from the layer is runs on top of, it merely establishes a
  3848. * secure channel between a client" and a "server".
  3849. *
  3850. * A TLS connection contains 4 connection states: pending read and write, and
  3851. * current read and write.
  3852. *
  3853. * At initialization, the current read and write states will be null. Only once
  3854. * the security parameters have been set and the keys have been generated can
  3855. * the pending states be converted into current states. Current states will be
  3856. * updated for each record processed.
  3857. *
  3858. * A custom certificate verify callback may be provided to check information
  3859. * like the common name on the server's certificate. It will be called for
  3860. * every certificate in the chain. It has the following signature:
  3861. *
  3862. * variable func(c, certs, index, preVerify)
  3863. * Where:
  3864. * c The TLS connection
  3865. * verified Set to true if certificate was verified, otherwise the alert
  3866. * tls.Alert.Description for why the certificate failed.
  3867. * depth The current index in the chain, where 0 is the server's cert.
  3868. * certs The certificate chain, *NOTE* if the server was anonymous then
  3869. * the chain will be empty.
  3870. *
  3871. * The function returns true on success and on failure either the appropriate
  3872. * tls.Alert.Description or an object with 'alert' set to the appropriate
  3873. * tls.Alert.Description and 'message' set to a custom error message. If true
  3874. * is not returned then the connection will abort using, in order of
  3875. * availability, first the returned alert description, second the preVerify
  3876. * alert description, and lastly the default 'bad_certificate'.
  3877. *
  3878. * There are three callbacks that can be used to make use of client-side
  3879. * certificates where each takes the TLS connection as the first parameter:
  3880. *
  3881. * getCertificate(conn, hint)
  3882. * The second parameter is a hint as to which certificate should be
  3883. * returned. If the connection entity is a client, then the hint will be
  3884. * the CertificateRequest message from the server that is part of the
  3885. * TLS protocol. If the connection entity is a server, then it will be
  3886. * the servername list provided via an SNI extension the ClientHello, if
  3887. * one was provided (empty array if not). The hint can be examined to
  3888. * determine which certificate to use (advanced). Most implementations
  3889. * will just return a certificate. The return value must be a
  3890. * PEM-formatted certificate or an array of PEM-formatted certificates
  3891. * that constitute a certificate chain, with the first in the array/chain
  3892. * being the client's certificate.
  3893. * getPrivateKey(conn, certificate)
  3894. * The second parameter is an forge.pki X.509 certificate object that
  3895. * is associated with the requested private key. The return value must
  3896. * be a PEM-formatted private key.
  3897. * getSignature(conn, bytes, callback)
  3898. * This callback can be used instead of getPrivateKey if the private key
  3899. * is not directly accessible in javascript or should not be. For
  3900. * instance, a secure external web service could provide the signature
  3901. * in exchange for appropriate credentials. The second parameter is a
  3902. * string of bytes to be signed that are part of the TLS protocol. These
  3903. * bytes are used to verify that the private key for the previously
  3904. * provided client-side certificate is accessible to the client. The
  3905. * callback is a function that takes 2 parameters, the TLS connection
  3906. * and the RSA encrypted (signed) bytes as a string. This callback must
  3907. * be called once the signature is ready.
  3908. *
  3909. * @param options the options for this connection:
  3910. * server: true if the connection is server-side, false for client.
  3911. * sessionId: a session ID to reuse, null for a new connection.
  3912. * caStore: an array of certificates to trust.
  3913. * sessionCache: a session cache to use.
  3914. * cipherSuites: an optional array of cipher suites to use,
  3915. * see tls.CipherSuites.
  3916. * connected: function(conn) called when the first handshake completes.
  3917. * virtualHost: the virtual server name to use in a TLS SNI extension.
  3918. * verifyClient: true to require a client certificate in server mode,
  3919. * 'optional' to request one, false not to (default: false).
  3920. * verify: a handler used to custom verify certificates in the chain.
  3921. * getCertificate: an optional callback used to get a certificate or
  3922. * a chain of certificates (as an array).
  3923. * getPrivateKey: an optional callback used to get a private key.
  3924. * getSignature: an optional callback used to get a signature.
  3925. * tlsDataReady: function(conn) called when TLS protocol data has been
  3926. * prepared and is ready to be used (typically sent over a socket
  3927. * connection to its destination), read from conn.tlsData buffer.
  3928. * dataReady: function(conn) called when application data has
  3929. * been parsed from a TLS record and should be consumed by the
  3930. * application, read from conn.data buffer.
  3931. * closed: function(conn) called when the connection has been closed.
  3932. * error: function(conn, error) called when there was an error.
  3933. * deflate: function(inBytes) if provided, will deflate TLS records using
  3934. * the deflate algorithm if the server supports it.
  3935. * inflate: function(inBytes) if provided, will inflate TLS records using
  3936. * the deflate algorithm if the server supports it.
  3937. *
  3938. * @return the new TLS connection.
  3939. */
  3940. forge.tls.createConnection = tls.createConnection;