You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tls.c 89KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132
  1. /*
  2. * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  17. * 02110-1301, USA.
  18. */
  19. FILE_LICENCE ( GPL2_OR_LATER );
  20. /**
  21. * @file
  22. *
  23. * Transport Layer Security Protocol
  24. */
  25. #include <stdint.h>
  26. #include <stdlib.h>
  27. #include <stdarg.h>
  28. #include <string.h>
  29. #include <time.h>
  30. #include <errno.h>
  31. #include <byteswap.h>
  32. #include <ipxe/pending.h>
  33. #include <ipxe/hmac.h>
  34. #include <ipxe/md5.h>
  35. #include <ipxe/sha1.h>
  36. #include <ipxe/sha256.h>
  37. #include <ipxe/aes.h>
  38. #include <ipxe/rsa.h>
  39. #include <ipxe/iobuf.h>
  40. #include <ipxe/xfer.h>
  41. #include <ipxe/open.h>
  42. #include <ipxe/x509.h>
  43. #include <ipxe/privkey.h>
  44. #include <ipxe/certstore.h>
  45. #include <ipxe/rbg.h>
  46. #include <ipxe/validator.h>
  47. #include <ipxe/job.h>
  48. #include <ipxe/tls.h>
  49. /* Disambiguate the various error causes */
  50. #define EINVAL_CHANGE_CIPHER __einfo_error ( EINFO_EINVAL_CHANGE_CIPHER )
  51. #define EINFO_EINVAL_CHANGE_CIPHER \
  52. __einfo_uniqify ( EINFO_EINVAL, 0x01, \
  53. "Invalid Change Cipher record" )
  54. #define EINVAL_ALERT __einfo_error ( EINFO_EINVAL_ALERT )
  55. #define EINFO_EINVAL_ALERT \
  56. __einfo_uniqify ( EINFO_EINVAL, 0x02, \
  57. "Invalid Alert record" )
  58. #define EINVAL_HELLO __einfo_error ( EINFO_EINVAL_HELLO )
  59. #define EINFO_EINVAL_HELLO \
  60. __einfo_uniqify ( EINFO_EINVAL, 0x03, \
  61. "Invalid Server Hello record" )
  62. #define EINVAL_CERTIFICATE __einfo_error ( EINFO_EINVAL_CERTIFICATE )
  63. #define EINFO_EINVAL_CERTIFICATE \
  64. __einfo_uniqify ( EINFO_EINVAL, 0x04, \
  65. "Invalid Certificate" )
  66. #define EINVAL_CERTIFICATES __einfo_error ( EINFO_EINVAL_CERTIFICATES )
  67. #define EINFO_EINVAL_CERTIFICATES \
  68. __einfo_uniqify ( EINFO_EINVAL, 0x05, \
  69. "Invalid Server Certificate record" )
  70. #define EINVAL_HELLO_DONE __einfo_error ( EINFO_EINVAL_HELLO_DONE )
  71. #define EINFO_EINVAL_HELLO_DONE \
  72. __einfo_uniqify ( EINFO_EINVAL, 0x06, \
  73. "Invalid Server Hello Done record" )
  74. #define EINVAL_FINISHED __einfo_error ( EINFO_EINVAL_FINISHED )
  75. #define EINFO_EINVAL_FINISHED \
  76. __einfo_uniqify ( EINFO_EINVAL, 0x07, \
  77. "Invalid Server Finished record" )
  78. #define EINVAL_HANDSHAKE __einfo_error ( EINFO_EINVAL_HANDSHAKE )
  79. #define EINFO_EINVAL_HANDSHAKE \
  80. __einfo_uniqify ( EINFO_EINVAL, 0x08, \
  81. "Invalid Handshake record" )
  82. #define EINVAL_STREAM __einfo_error ( EINFO_EINVAL_STREAM )
  83. #define EINFO_EINVAL_STREAM \
  84. __einfo_uniqify ( EINFO_EINVAL, 0x09, \
  85. "Invalid stream-ciphered record" )
  86. #define EINVAL_BLOCK __einfo_error ( EINFO_EINVAL_BLOCK )
  87. #define EINFO_EINVAL_BLOCK \
  88. __einfo_uniqify ( EINFO_EINVAL, 0x0a, \
  89. "Invalid block-ciphered record" )
  90. #define EINVAL_PADDING __einfo_error ( EINFO_EINVAL_PADDING )
  91. #define EINFO_EINVAL_PADDING \
  92. __einfo_uniqify ( EINFO_EINVAL, 0x0b, \
  93. "Invalid block padding" )
  94. #define EINVAL_RX_STATE __einfo_error ( EINFO_EINVAL_RX_STATE )
  95. #define EINFO_EINVAL_RX_STATE \
  96. __einfo_uniqify ( EINFO_EINVAL, 0x0c, \
  97. "Invalid receive state" )
  98. #define EINVAL_MAC __einfo_error ( EINFO_EINVAL_MAC )
  99. #define EINFO_EINVAL_MAC \
  100. __einfo_uniqify ( EINFO_EINVAL, 0x0d, \
  101. "Invalid MAC" )
  102. #define EINVAL_TICKET __einfo_error ( EINFO_EINVAL_TICKET )
  103. #define EINFO_EINVAL_TICKET \
  104. __einfo_uniqify ( EINFO_EINVAL, 0x0e, \
  105. "Invalid New Session Ticket record")
  106. #define EIO_ALERT __einfo_error ( EINFO_EIO_ALERT )
  107. #define EINFO_EIO_ALERT \
  108. __einfo_uniqify ( EINFO_EIO, 0x01, \
  109. "Unknown alert level" )
  110. #define ENOMEM_CONTEXT __einfo_error ( EINFO_ENOMEM_CONTEXT )
  111. #define EINFO_ENOMEM_CONTEXT \
  112. __einfo_uniqify ( EINFO_ENOMEM, 0x01, \
  113. "Not enough space for crypto context" )
  114. #define ENOMEM_CERTIFICATE __einfo_error ( EINFO_ENOMEM_CERTIFICATE )
  115. #define EINFO_ENOMEM_CERTIFICATE \
  116. __einfo_uniqify ( EINFO_ENOMEM, 0x02, \
  117. "Not enough space for certificate" )
  118. #define ENOMEM_CHAIN __einfo_error ( EINFO_ENOMEM_CHAIN )
  119. #define EINFO_ENOMEM_CHAIN \
  120. __einfo_uniqify ( EINFO_ENOMEM, 0x03, \
  121. "Not enough space for certificate chain" )
  122. #define ENOMEM_TX_PLAINTEXT __einfo_error ( EINFO_ENOMEM_TX_PLAINTEXT )
  123. #define EINFO_ENOMEM_TX_PLAINTEXT \
  124. __einfo_uniqify ( EINFO_ENOMEM, 0x04, \
  125. "Not enough space for transmitted plaintext" )
  126. #define ENOMEM_TX_CIPHERTEXT __einfo_error ( EINFO_ENOMEM_TX_CIPHERTEXT )
  127. #define EINFO_ENOMEM_TX_CIPHERTEXT \
  128. __einfo_uniqify ( EINFO_ENOMEM, 0x05, \
  129. "Not enough space for transmitted ciphertext" )
  130. #define ENOMEM_RX_DATA __einfo_error ( EINFO_ENOMEM_RX_DATA )
  131. #define EINFO_ENOMEM_RX_DATA \
  132. __einfo_uniqify ( EINFO_ENOMEM, 0x07, \
  133. "Not enough space for received data" )
  134. #define ENOMEM_RX_CONCAT __einfo_error ( EINFO_ENOMEM_RX_CONCAT )
  135. #define EINFO_ENOMEM_RX_CONCAT \
  136. __einfo_uniqify ( EINFO_ENOMEM, 0x08, \
  137. "Not enough space to concatenate received data" )
  138. #define ENOTSUP_CIPHER __einfo_error ( EINFO_ENOTSUP_CIPHER )
  139. #define EINFO_ENOTSUP_CIPHER \
  140. __einfo_uniqify ( EINFO_ENOTSUP, 0x01, \
  141. "Unsupported cipher" )
  142. #define ENOTSUP_NULL __einfo_error ( EINFO_ENOTSUP_NULL )
  143. #define EINFO_ENOTSUP_NULL \
  144. __einfo_uniqify ( EINFO_ENOTSUP, 0x02, \
  145. "Refusing to use null cipher" )
  146. #define ENOTSUP_SIG_HASH __einfo_error ( EINFO_ENOTSUP_SIG_HASH )
  147. #define EINFO_ENOTSUP_SIG_HASH \
  148. __einfo_uniqify ( EINFO_ENOTSUP, 0x03, \
  149. "Unsupported signature and hash algorithm" )
  150. #define ENOTSUP_VERSION __einfo_error ( EINFO_ENOTSUP_VERSION )
  151. #define EINFO_ENOTSUP_VERSION \
  152. __einfo_uniqify ( EINFO_ENOTSUP, 0x04, \
  153. "Unsupported protocol version" )
  154. #define EPERM_ALERT __einfo_error ( EINFO_EPERM_ALERT )
  155. #define EINFO_EPERM_ALERT \
  156. __einfo_uniqify ( EINFO_EPERM, 0x01, \
  157. "Received fatal alert" )
  158. #define EPERM_VERIFY __einfo_error ( EINFO_EPERM_VERIFY )
  159. #define EINFO_EPERM_VERIFY \
  160. __einfo_uniqify ( EINFO_EPERM, 0x02, \
  161. "Handshake verification failed" )
  162. #define EPERM_CLIENT_CERT __einfo_error ( EINFO_EPERM_CLIENT_CERT )
  163. #define EINFO_EPERM_CLIENT_CERT \
  164. __einfo_uniqify ( EINFO_EPERM, 0x03, \
  165. "No suitable client certificate available" )
  166. #define EPERM_RENEG_INSECURE __einfo_error ( EINFO_EPERM_RENEG_INSECURE )
  167. #define EINFO_EPERM_RENEG_INSECURE \
  168. __einfo_uniqify ( EINFO_EPERM, 0x04, \
  169. "Secure renegotiation not supported" )
  170. #define EPERM_RENEG_VERIFY __einfo_error ( EINFO_EPERM_RENEG_VERIFY )
  171. #define EINFO_EPERM_RENEG_VERIFY \
  172. __einfo_uniqify ( EINFO_EPERM, 0x05, \
  173. "Secure renegotiation verification failed" )
  174. #define EPROTO_VERSION __einfo_error ( EINFO_EPROTO_VERSION )
  175. #define EINFO_EPROTO_VERSION \
  176. __einfo_uniqify ( EINFO_EPROTO, 0x01, \
  177. "Illegal protocol version upgrade" )
  178. /** List of TLS session */
  179. static LIST_HEAD ( tls_sessions );
  180. static void tls_tx_resume_all ( struct tls_session *session );
  181. static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
  182. const void *data, size_t len );
  183. static void tls_clear_cipher ( struct tls_connection *tls,
  184. struct tls_cipherspec *cipherspec );
  185. /******************************************************************************
  186. *
  187. * Utility functions
  188. *
  189. ******************************************************************************
  190. */
  191. /** A TLS 24-bit integer
  192. *
  193. * TLS uses 24-bit integers in several places, which are awkward to
  194. * parse in C.
  195. */
  196. typedef struct {
  197. /** High byte */
  198. uint8_t high;
  199. /** Low word */
  200. uint16_t low;
  201. } __attribute__ (( packed )) tls24_t;
  202. /**
  203. * Extract 24-bit field value
  204. *
  205. * @v field24 24-bit field
  206. * @ret value Field value
  207. *
  208. */
  209. static inline __attribute__ (( always_inline )) unsigned long
  210. tls_uint24 ( const tls24_t *field24 ) {
  211. return ( ( field24->high << 16 ) | be16_to_cpu ( field24->low ) );
  212. }
  213. /**
  214. * Set 24-bit field value
  215. *
  216. * @v field24 24-bit field
  217. * @v value Field value
  218. */
  219. static void tls_set_uint24 ( tls24_t *field24, unsigned long value ) {
  220. field24->high = ( value >> 16 );
  221. field24->low = cpu_to_be16 ( value );
  222. }
  223. /**
  224. * Determine if TLS connection is ready for application data
  225. *
  226. * @v tls TLS connection
  227. * @ret is_ready TLS connection is ready
  228. */
  229. static int tls_ready ( struct tls_connection *tls ) {
  230. return ( ( ! is_pending ( &tls->client_negotiation ) ) &&
  231. ( ! is_pending ( &tls->server_negotiation ) ) );
  232. }
  233. /******************************************************************************
  234. *
  235. * Hybrid MD5+SHA1 hash as used by TLSv1.1 and earlier
  236. *
  237. ******************************************************************************
  238. */
  239. /**
  240. * Initialise MD5+SHA1 algorithm
  241. *
  242. * @v ctx MD5+SHA1 context
  243. */
  244. static void md5_sha1_init ( void *ctx ) {
  245. struct md5_sha1_context *context = ctx;
  246. digest_init ( &md5_algorithm, context->md5 );
  247. digest_init ( &sha1_algorithm, context->sha1 );
  248. }
  249. /**
  250. * Accumulate data with MD5+SHA1 algorithm
  251. *
  252. * @v ctx MD5+SHA1 context
  253. * @v data Data
  254. * @v len Length of data
  255. */
  256. static void md5_sha1_update ( void *ctx, const void *data, size_t len ) {
  257. struct md5_sha1_context *context = ctx;
  258. digest_update ( &md5_algorithm, context->md5, data, len );
  259. digest_update ( &sha1_algorithm, context->sha1, data, len );
  260. }
  261. /**
  262. * Generate MD5+SHA1 digest
  263. *
  264. * @v ctx MD5+SHA1 context
  265. * @v out Output buffer
  266. */
  267. static void md5_sha1_final ( void *ctx, void *out ) {
  268. struct md5_sha1_context *context = ctx;
  269. struct md5_sha1_digest *digest = out;
  270. digest_final ( &md5_algorithm, context->md5, digest->md5 );
  271. digest_final ( &sha1_algorithm, context->sha1, digest->sha1 );
  272. }
  273. /** Hybrid MD5+SHA1 digest algorithm */
  274. static struct digest_algorithm md5_sha1_algorithm = {
  275. .name = "md5+sha1",
  276. .ctxsize = sizeof ( struct md5_sha1_context ),
  277. .blocksize = 0, /* Not applicable */
  278. .digestsize = sizeof ( struct md5_sha1_digest ),
  279. .init = md5_sha1_init,
  280. .update = md5_sha1_update,
  281. .final = md5_sha1_final,
  282. };
  283. /** RSA digestInfo prefix for MD5+SHA1 algorithm */
  284. struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix = {
  285. .digest = &md5_sha1_algorithm,
  286. .data = NULL, /* MD5+SHA1 signatures have no digestInfo */
  287. .len = 0,
  288. };
  289. /******************************************************************************
  290. *
  291. * Cleanup functions
  292. *
  293. ******************************************************************************
  294. */
  295. /**
  296. * Free TLS session
  297. *
  298. * @v refcnt Reference counter
  299. */
  300. static void free_tls_session ( struct refcnt *refcnt ) {
  301. struct tls_session *session =
  302. container_of ( refcnt, struct tls_session, refcnt );
  303. /* Sanity check */
  304. assert ( list_empty ( &session->conn ) );
  305. /* Remove from list of sessions */
  306. list_del ( &session->list );
  307. /* Free session ticket */
  308. free ( session->ticket );
  309. /* Free session */
  310. free ( session );
  311. }
  312. /**
  313. * Free TLS connection
  314. *
  315. * @v refcnt Reference counter
  316. */
  317. static void free_tls ( struct refcnt *refcnt ) {
  318. struct tls_connection *tls =
  319. container_of ( refcnt, struct tls_connection, refcnt );
  320. struct tls_session *session = tls->session;
  321. struct io_buffer *iobuf;
  322. struct io_buffer *tmp;
  323. /* Free dynamically-allocated resources */
  324. free ( tls->new_session_ticket );
  325. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  326. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  327. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  328. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  329. list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
  330. list_del ( &iobuf->list );
  331. free_iob ( iobuf );
  332. }
  333. x509_put ( tls->cert );
  334. x509_chain_put ( tls->chain );
  335. /* Drop reference to session */
  336. assert ( list_empty ( &tls->list ) );
  337. ref_put ( &session->refcnt );
  338. /* Free TLS structure itself */
  339. free ( tls );
  340. }
  341. /**
  342. * Finish with TLS connection
  343. *
  344. * @v tls TLS connection
  345. * @v rc Status code
  346. */
  347. static void tls_close ( struct tls_connection *tls, int rc ) {
  348. /* Remove pending operations, if applicable */
  349. pending_put ( &tls->client_negotiation );
  350. pending_put ( &tls->server_negotiation );
  351. pending_put ( &tls->validation );
  352. /* Remove process */
  353. process_del ( &tls->process );
  354. /* Close all interfaces */
  355. intf_shutdown ( &tls->cipherstream, rc );
  356. intf_shutdown ( &tls->plainstream, rc );
  357. intf_shutdown ( &tls->validator, rc );
  358. /* Remove from session */
  359. list_del ( &tls->list );
  360. INIT_LIST_HEAD ( &tls->list );
  361. /* Resume all other connections, in case we were the lead connection */
  362. tls_tx_resume_all ( tls->session );
  363. }
  364. /******************************************************************************
  365. *
  366. * Random number generation
  367. *
  368. ******************************************************************************
  369. */
  370. /**
  371. * Generate random data
  372. *
  373. * @v tls TLS connection
  374. * @v data Buffer to fill
  375. * @v len Length of buffer
  376. * @ret rc Return status code
  377. */
  378. static int tls_generate_random ( struct tls_connection *tls,
  379. void *data, size_t len ) {
  380. int rc;
  381. /* Generate random bits with no additional input and without
  382. * prediction resistance
  383. */
  384. if ( ( rc = rbg_generate ( NULL, 0, 0, data, len ) ) != 0 ) {
  385. DBGC ( tls, "TLS %p could not generate random data: %s\n",
  386. tls, strerror ( rc ) );
  387. return rc;
  388. }
  389. return 0;
  390. }
  391. /**
  392. * Update HMAC with a list of ( data, len ) pairs
  393. *
  394. * @v digest Hash function to use
  395. * @v digest_ctx Digest context
  396. * @v args ( data, len ) pairs of data, terminated by NULL
  397. */
  398. static void tls_hmac_update_va ( struct digest_algorithm *digest,
  399. void *digest_ctx, va_list args ) {
  400. void *data;
  401. size_t len;
  402. while ( ( data = va_arg ( args, void * ) ) ) {
  403. len = va_arg ( args, size_t );
  404. hmac_update ( digest, digest_ctx, data, len );
  405. }
  406. }
  407. /**
  408. * Generate secure pseudo-random data using a single hash function
  409. *
  410. * @v tls TLS connection
  411. * @v digest Hash function to use
  412. * @v secret Secret
  413. * @v secret_len Length of secret
  414. * @v out Output buffer
  415. * @v out_len Length of output buffer
  416. * @v seeds ( data, len ) pairs of seed data, terminated by NULL
  417. */
  418. static void tls_p_hash_va ( struct tls_connection *tls,
  419. struct digest_algorithm *digest,
  420. void *secret, size_t secret_len,
  421. void *out, size_t out_len,
  422. va_list seeds ) {
  423. uint8_t secret_copy[secret_len];
  424. uint8_t digest_ctx[digest->ctxsize];
  425. uint8_t digest_ctx_partial[digest->ctxsize];
  426. uint8_t a[digest->digestsize];
  427. uint8_t out_tmp[digest->digestsize];
  428. size_t frag_len = digest->digestsize;
  429. va_list tmp;
  430. /* Copy the secret, in case HMAC modifies it */
  431. memcpy ( secret_copy, secret, secret_len );
  432. secret = secret_copy;
  433. DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
  434. DBGC2_HD ( tls, secret, secret_len );
  435. /* Calculate A(1) */
  436. hmac_init ( digest, digest_ctx, secret, &secret_len );
  437. va_copy ( tmp, seeds );
  438. tls_hmac_update_va ( digest, digest_ctx, tmp );
  439. va_end ( tmp );
  440. hmac_final ( digest, digest_ctx, secret, &secret_len, a );
  441. DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
  442. DBGC2_HD ( tls, &a, sizeof ( a ) );
  443. /* Generate as much data as required */
  444. while ( out_len ) {
  445. /* Calculate output portion */
  446. hmac_init ( digest, digest_ctx, secret, &secret_len );
  447. hmac_update ( digest, digest_ctx, a, sizeof ( a ) );
  448. memcpy ( digest_ctx_partial, digest_ctx, digest->ctxsize );
  449. va_copy ( tmp, seeds );
  450. tls_hmac_update_va ( digest, digest_ctx, tmp );
  451. va_end ( tmp );
  452. hmac_final ( digest, digest_ctx,
  453. secret, &secret_len, out_tmp );
  454. /* Copy output */
  455. if ( frag_len > out_len )
  456. frag_len = out_len;
  457. memcpy ( out, out_tmp, frag_len );
  458. DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
  459. DBGC2_HD ( tls, out, frag_len );
  460. /* Calculate A(i) */
  461. hmac_final ( digest, digest_ctx_partial,
  462. secret, &secret_len, a );
  463. DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
  464. DBGC2_HD ( tls, &a, sizeof ( a ) );
  465. out += frag_len;
  466. out_len -= frag_len;
  467. }
  468. }
  469. /**
  470. * Generate secure pseudo-random data
  471. *
  472. * @v tls TLS connection
  473. * @v secret Secret
  474. * @v secret_len Length of secret
  475. * @v out Output buffer
  476. * @v out_len Length of output buffer
  477. * @v ... ( data, len ) pairs of seed data, terminated by NULL
  478. */
  479. static void tls_prf ( struct tls_connection *tls, void *secret,
  480. size_t secret_len, void *out, size_t out_len, ... ) {
  481. va_list seeds;
  482. va_list tmp;
  483. size_t subsecret_len;
  484. void *md5_secret;
  485. void *sha1_secret;
  486. uint8_t buf[out_len];
  487. unsigned int i;
  488. va_start ( seeds, out_len );
  489. if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
  490. /* Use P_SHA256 for TLSv1.2 and later */
  491. tls_p_hash_va ( tls, &sha256_algorithm, secret, secret_len,
  492. out, out_len, seeds );
  493. } else {
  494. /* Use combination of P_MD5 and P_SHA-1 for TLSv1.1
  495. * and earlier
  496. */
  497. /* Split secret into two, with an overlap of up to one byte */
  498. subsecret_len = ( ( secret_len + 1 ) / 2 );
  499. md5_secret = secret;
  500. sha1_secret = ( secret + secret_len - subsecret_len );
  501. /* Calculate MD5 portion */
  502. va_copy ( tmp, seeds );
  503. tls_p_hash_va ( tls, &md5_algorithm, md5_secret,
  504. subsecret_len, out, out_len, seeds );
  505. va_end ( tmp );
  506. /* Calculate SHA1 portion */
  507. va_copy ( tmp, seeds );
  508. tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret,
  509. subsecret_len, buf, out_len, seeds );
  510. va_end ( tmp );
  511. /* XOR the two portions together into the final output buffer */
  512. for ( i = 0 ; i < out_len ; i++ )
  513. *( ( uint8_t * ) out + i ) ^= buf[i];
  514. }
  515. va_end ( seeds );
  516. }
  517. /**
  518. * Generate secure pseudo-random data
  519. *
  520. * @v secret Secret
  521. * @v secret_len Length of secret
  522. * @v out Output buffer
  523. * @v out_len Length of output buffer
  524. * @v label String literal label
  525. * @v ... ( data, len ) pairs of seed data
  526. */
  527. #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
  528. tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
  529. label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
  530. /******************************************************************************
  531. *
  532. * Secret management
  533. *
  534. ******************************************************************************
  535. */
  536. /**
  537. * Generate master secret
  538. *
  539. * @v tls TLS connection
  540. *
  541. * The pre-master secret and the client and server random values must
  542. * already be known.
  543. */
  544. static void tls_generate_master_secret ( struct tls_connection *tls ) {
  545. DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
  546. DBGC_HD ( tls, &tls->pre_master_secret,
  547. sizeof ( tls->pre_master_secret ) );
  548. DBGC ( tls, "TLS %p client random bytes:\n", tls );
  549. DBGC_HD ( tls, &tls->client_random, sizeof ( tls->client_random ) );
  550. DBGC ( tls, "TLS %p server random bytes:\n", tls );
  551. DBGC_HD ( tls, &tls->server_random, sizeof ( tls->server_random ) );
  552. tls_prf_label ( tls, &tls->pre_master_secret,
  553. sizeof ( tls->pre_master_secret ),
  554. &tls->master_secret, sizeof ( tls->master_secret ),
  555. "master secret",
  556. &tls->client_random, sizeof ( tls->client_random ),
  557. &tls->server_random, sizeof ( tls->server_random ) );
  558. DBGC ( tls, "TLS %p generated master secret:\n", tls );
  559. DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
  560. }
  561. /**
  562. * Generate key material
  563. *
  564. * @v tls TLS connection
  565. *
  566. * The master secret must already be known.
  567. */
  568. static int tls_generate_keys ( struct tls_connection *tls ) {
  569. struct tls_cipherspec *tx_cipherspec = &tls->tx_cipherspec_pending;
  570. struct tls_cipherspec *rx_cipherspec = &tls->rx_cipherspec_pending;
  571. size_t hash_size = tx_cipherspec->suite->digest->digestsize;
  572. size_t key_size = tx_cipherspec->suite->key_len;
  573. size_t iv_size = tx_cipherspec->suite->cipher->blocksize;
  574. size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
  575. uint8_t key_block[total];
  576. uint8_t *key;
  577. int rc;
  578. /* Generate key block */
  579. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  580. key_block, sizeof ( key_block ), "key expansion",
  581. &tls->server_random, sizeof ( tls->server_random ),
  582. &tls->client_random, sizeof ( tls->client_random ) );
  583. /* Split key block into portions */
  584. key = key_block;
  585. /* TX MAC secret */
  586. memcpy ( tx_cipherspec->mac_secret, key, hash_size );
  587. DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
  588. DBGC_HD ( tls, key, hash_size );
  589. key += hash_size;
  590. /* RX MAC secret */
  591. memcpy ( rx_cipherspec->mac_secret, key, hash_size );
  592. DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
  593. DBGC_HD ( tls, key, hash_size );
  594. key += hash_size;
  595. /* TX key */
  596. if ( ( rc = cipher_setkey ( tx_cipherspec->suite->cipher,
  597. tx_cipherspec->cipher_ctx,
  598. key, key_size ) ) != 0 ) {
  599. DBGC ( tls, "TLS %p could not set TX key: %s\n",
  600. tls, strerror ( rc ) );
  601. return rc;
  602. }
  603. DBGC ( tls, "TLS %p TX key:\n", tls );
  604. DBGC_HD ( tls, key, key_size );
  605. key += key_size;
  606. /* RX key */
  607. if ( ( rc = cipher_setkey ( rx_cipherspec->suite->cipher,
  608. rx_cipherspec->cipher_ctx,
  609. key, key_size ) ) != 0 ) {
  610. DBGC ( tls, "TLS %p could not set TX key: %s\n",
  611. tls, strerror ( rc ) );
  612. return rc;
  613. }
  614. DBGC ( tls, "TLS %p RX key:\n", tls );
  615. DBGC_HD ( tls, key, key_size );
  616. key += key_size;
  617. /* TX initialisation vector */
  618. cipher_setiv ( tx_cipherspec->suite->cipher,
  619. tx_cipherspec->cipher_ctx, key );
  620. DBGC ( tls, "TLS %p TX IV:\n", tls );
  621. DBGC_HD ( tls, key, iv_size );
  622. key += iv_size;
  623. /* RX initialisation vector */
  624. cipher_setiv ( rx_cipherspec->suite->cipher,
  625. rx_cipherspec->cipher_ctx, key );
  626. DBGC ( tls, "TLS %p RX IV:\n", tls );
  627. DBGC_HD ( tls, key, iv_size );
  628. key += iv_size;
  629. assert ( ( key_block + total ) == key );
  630. return 0;
  631. }
  632. /******************************************************************************
  633. *
  634. * Cipher suite management
  635. *
  636. ******************************************************************************
  637. */
  638. /** Null cipher suite */
  639. struct tls_cipher_suite tls_cipher_suite_null = {
  640. .pubkey = &pubkey_null,
  641. .cipher = &cipher_null,
  642. .digest = &digest_null,
  643. };
  644. /** Number of supported cipher suites */
  645. #define TLS_NUM_CIPHER_SUITES table_num_entries ( TLS_CIPHER_SUITES )
  646. /**
  647. * Identify cipher suite
  648. *
  649. * @v cipher_suite Cipher suite specification
  650. * @ret suite Cipher suite, or NULL
  651. */
  652. static struct tls_cipher_suite *
  653. tls_find_cipher_suite ( unsigned int cipher_suite ) {
  654. struct tls_cipher_suite *suite;
  655. /* Identify cipher suite */
  656. for_each_table_entry ( suite, TLS_CIPHER_SUITES ) {
  657. if ( suite->code == cipher_suite )
  658. return suite;
  659. }
  660. return NULL;
  661. }
  662. /**
  663. * Clear cipher suite
  664. *
  665. * @v cipherspec TLS cipher specification
  666. */
  667. static void tls_clear_cipher ( struct tls_connection *tls __unused,
  668. struct tls_cipherspec *cipherspec ) {
  669. if ( cipherspec->suite ) {
  670. pubkey_final ( cipherspec->suite->pubkey,
  671. cipherspec->pubkey_ctx );
  672. }
  673. free ( cipherspec->dynamic );
  674. memset ( cipherspec, 0, sizeof ( *cipherspec ) );
  675. cipherspec->suite = &tls_cipher_suite_null;
  676. }
  677. /**
  678. * Set cipher suite
  679. *
  680. * @v tls TLS connection
  681. * @v cipherspec TLS cipher specification
  682. * @v suite Cipher suite
  683. * @ret rc Return status code
  684. */
  685. static int tls_set_cipher ( struct tls_connection *tls,
  686. struct tls_cipherspec *cipherspec,
  687. struct tls_cipher_suite *suite ) {
  688. struct pubkey_algorithm *pubkey = suite->pubkey;
  689. struct cipher_algorithm *cipher = suite->cipher;
  690. struct digest_algorithm *digest = suite->digest;
  691. size_t total;
  692. void *dynamic;
  693. /* Clear out old cipher contents, if any */
  694. tls_clear_cipher ( tls, cipherspec );
  695. /* Allocate dynamic storage */
  696. total = ( pubkey->ctxsize + 2 * cipher->ctxsize + digest->digestsize );
  697. dynamic = zalloc ( total );
  698. if ( ! dynamic ) {
  699. DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
  700. "context\n", tls, total );
  701. return -ENOMEM_CONTEXT;
  702. }
  703. /* Assign storage */
  704. cipherspec->dynamic = dynamic;
  705. cipherspec->pubkey_ctx = dynamic; dynamic += pubkey->ctxsize;
  706. cipherspec->cipher_ctx = dynamic; dynamic += cipher->ctxsize;
  707. cipherspec->cipher_next_ctx = dynamic; dynamic += cipher->ctxsize;
  708. cipherspec->mac_secret = dynamic; dynamic += digest->digestsize;
  709. assert ( ( cipherspec->dynamic + total ) == dynamic );
  710. /* Store parameters */
  711. cipherspec->suite = suite;
  712. return 0;
  713. }
  714. /**
  715. * Select next cipher suite
  716. *
  717. * @v tls TLS connection
  718. * @v cipher_suite Cipher suite specification
  719. * @ret rc Return status code
  720. */
  721. static int tls_select_cipher ( struct tls_connection *tls,
  722. unsigned int cipher_suite ) {
  723. struct tls_cipher_suite *suite;
  724. int rc;
  725. /* Identify cipher suite */
  726. suite = tls_find_cipher_suite ( cipher_suite );
  727. if ( ! suite ) {
  728. DBGC ( tls, "TLS %p does not support cipher %04x\n",
  729. tls, ntohs ( cipher_suite ) );
  730. return -ENOTSUP_CIPHER;
  731. }
  732. /* Set ciphers */
  733. if ( ( rc = tls_set_cipher ( tls, &tls->tx_cipherspec_pending,
  734. suite ) ) != 0 )
  735. return rc;
  736. if ( ( rc = tls_set_cipher ( tls, &tls->rx_cipherspec_pending,
  737. suite ) ) != 0 )
  738. return rc;
  739. DBGC ( tls, "TLS %p selected %s-%s-%d-%s\n", tls, suite->pubkey->name,
  740. suite->cipher->name, ( suite->key_len * 8 ),
  741. suite->digest->name );
  742. return 0;
  743. }
  744. /**
  745. * Activate next cipher suite
  746. *
  747. * @v tls TLS connection
  748. * @v pending Pending cipher specification
  749. * @v active Active cipher specification to replace
  750. * @ret rc Return status code
  751. */
  752. static int tls_change_cipher ( struct tls_connection *tls,
  753. struct tls_cipherspec *pending,
  754. struct tls_cipherspec *active ) {
  755. /* Sanity check */
  756. if ( pending->suite == &tls_cipher_suite_null ) {
  757. DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
  758. return -ENOTSUP_NULL;
  759. }
  760. tls_clear_cipher ( tls, active );
  761. memswap ( active, pending, sizeof ( *active ) );
  762. return 0;
  763. }
  764. /******************************************************************************
  765. *
  766. * Signature and hash algorithms
  767. *
  768. ******************************************************************************
  769. */
  770. /** Number of supported signature and hash algorithms */
  771. #define TLS_NUM_SIG_HASH_ALGORITHMS \
  772. table_num_entries ( TLS_SIG_HASH_ALGORITHMS )
  773. /**
  774. * Find TLS signature and hash algorithm
  775. *
  776. * @v pubkey Public-key algorithm
  777. * @v digest Digest algorithm
  778. * @ret sig_hash Signature and hash algorithm, or NULL
  779. */
  780. static struct tls_signature_hash_algorithm *
  781. tls_signature_hash_algorithm ( struct pubkey_algorithm *pubkey,
  782. struct digest_algorithm *digest ) {
  783. struct tls_signature_hash_algorithm *sig_hash;
  784. /* Identify signature and hash algorithm */
  785. for_each_table_entry ( sig_hash, TLS_SIG_HASH_ALGORITHMS ) {
  786. if ( ( sig_hash->pubkey == pubkey ) &&
  787. ( sig_hash->digest == digest ) ) {
  788. return sig_hash;
  789. }
  790. }
  791. return NULL;
  792. }
  793. /******************************************************************************
  794. *
  795. * Handshake verification
  796. *
  797. ******************************************************************************
  798. */
  799. /**
  800. * Add handshake record to verification hash
  801. *
  802. * @v tls TLS connection
  803. * @v data Handshake record
  804. * @v len Length of handshake record
  805. */
  806. static void tls_add_handshake ( struct tls_connection *tls,
  807. const void *data, size_t len ) {
  808. digest_update ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx,
  809. data, len );
  810. digest_update ( &sha256_algorithm, tls->handshake_sha256_ctx,
  811. data, len );
  812. }
  813. /**
  814. * Calculate handshake verification hash
  815. *
  816. * @v tls TLS connection
  817. * @v out Output buffer
  818. *
  819. * Calculates the MD5+SHA1 or SHA256 digest over all handshake
  820. * messages seen so far.
  821. */
  822. static void tls_verify_handshake ( struct tls_connection *tls, void *out ) {
  823. struct digest_algorithm *digest = tls->handshake_digest;
  824. uint8_t ctx[ digest->ctxsize ];
  825. memcpy ( ctx, tls->handshake_ctx, sizeof ( ctx ) );
  826. digest_final ( digest, ctx, out );
  827. }
  828. /******************************************************************************
  829. *
  830. * Record handling
  831. *
  832. ******************************************************************************
  833. */
  834. /**
  835. * Restart negotiation
  836. *
  837. * @v tls TLS connection
  838. */
  839. static void tls_restart ( struct tls_connection *tls ) {
  840. /* Sanity check */
  841. assert ( ! tls->tx_pending );
  842. assert ( ! is_pending ( &tls->client_negotiation ) );
  843. assert ( ! is_pending ( &tls->server_negotiation ) );
  844. assert ( ! is_pending ( &tls->validation ) );
  845. /* (Re)initialise handshake context */
  846. digest_init ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx );
  847. digest_init ( &sha256_algorithm, tls->handshake_sha256_ctx );
  848. tls->handshake_digest = &sha256_algorithm;
  849. tls->handshake_ctx = tls->handshake_sha256_ctx;
  850. /* (Re)start negotiation */
  851. tls->tx_pending = TLS_TX_CLIENT_HELLO;
  852. pending_get ( &tls->client_negotiation );
  853. pending_get ( &tls->server_negotiation );
  854. }
  855. /**
  856. * Resume TX state machine
  857. *
  858. * @v tls TLS connection
  859. */
  860. static void tls_tx_resume ( struct tls_connection *tls ) {
  861. process_add ( &tls->process );
  862. }
  863. /**
  864. * Resume TX state machine for all connections within a session
  865. *
  866. * @v session TLS session
  867. */
  868. static void tls_tx_resume_all ( struct tls_session *session ) {
  869. struct tls_connection *tls;
  870. list_for_each_entry ( tls, &session->conn, list )
  871. tls_tx_resume ( tls );
  872. }
  873. /**
  874. * Transmit Handshake record
  875. *
  876. * @v tls TLS connection
  877. * @v data Plaintext record
  878. * @v len Length of plaintext record
  879. * @ret rc Return status code
  880. */
  881. static int tls_send_handshake ( struct tls_connection *tls,
  882. void *data, size_t len ) {
  883. /* Add to handshake digest */
  884. tls_add_handshake ( tls, data, len );
  885. /* Send record */
  886. return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
  887. }
  888. /**
  889. * Transmit Client Hello record
  890. *
  891. * @v tls TLS connection
  892. * @ret rc Return status code
  893. */
  894. static int tls_send_client_hello ( struct tls_connection *tls ) {
  895. struct tls_session *session = tls->session;
  896. size_t name_len = strlen ( session->name );
  897. struct {
  898. uint32_t type_length;
  899. uint16_t version;
  900. uint8_t random[32];
  901. uint8_t session_id_len;
  902. uint8_t session_id[tls->session_id_len];
  903. uint16_t cipher_suite_len;
  904. uint16_t cipher_suites[TLS_NUM_CIPHER_SUITES];
  905. uint8_t compression_methods_len;
  906. uint8_t compression_methods[1];
  907. uint16_t extensions_len;
  908. struct {
  909. uint16_t server_name_type;
  910. uint16_t server_name_len;
  911. struct {
  912. uint16_t len;
  913. struct {
  914. uint8_t type;
  915. uint16_t len;
  916. uint8_t name[name_len];
  917. } __attribute__ (( packed )) list[1];
  918. } __attribute__ (( packed )) server_name;
  919. uint16_t max_fragment_length_type;
  920. uint16_t max_fragment_length_len;
  921. struct {
  922. uint8_t max;
  923. } __attribute__ (( packed )) max_fragment_length;
  924. uint16_t signature_algorithms_type;
  925. uint16_t signature_algorithms_len;
  926. struct {
  927. uint16_t len;
  928. struct tls_signature_hash_id
  929. code[TLS_NUM_SIG_HASH_ALGORITHMS];
  930. } __attribute__ (( packed )) signature_algorithms;
  931. uint16_t renegotiation_info_type;
  932. uint16_t renegotiation_info_len;
  933. struct {
  934. uint8_t len;
  935. uint8_t data[ tls->secure_renegotiation ?
  936. sizeof ( tls->verify.client ) :0];
  937. } __attribute__ (( packed )) renegotiation_info;
  938. uint16_t session_ticket_type;
  939. uint16_t session_ticket_len;
  940. struct {
  941. uint8_t data[session->ticket_len];
  942. } __attribute__ (( packed )) session_ticket;
  943. } __attribute__ (( packed )) extensions;
  944. } __attribute__ (( packed )) hello;
  945. struct tls_cipher_suite *suite;
  946. struct tls_signature_hash_algorithm *sighash;
  947. unsigned int i;
  948. /* Construct record */
  949. memset ( &hello, 0, sizeof ( hello ) );
  950. hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
  951. htonl ( sizeof ( hello ) -
  952. sizeof ( hello.type_length ) ) );
  953. hello.version = htons ( tls->version );
  954. memcpy ( &hello.random, &tls->client_random, sizeof ( hello.random ) );
  955. hello.session_id_len = tls->session_id_len;
  956. memcpy ( hello.session_id, tls->session_id,
  957. sizeof ( hello.session_id ) );
  958. hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
  959. i = 0 ; for_each_table_entry ( suite, TLS_CIPHER_SUITES )
  960. hello.cipher_suites[i++] = suite->code;
  961. hello.compression_methods_len = sizeof ( hello.compression_methods );
  962. hello.extensions_len = htons ( sizeof ( hello.extensions ) );
  963. hello.extensions.server_name_type = htons ( TLS_SERVER_NAME );
  964. hello.extensions.server_name_len
  965. = htons ( sizeof ( hello.extensions.server_name ) );
  966. hello.extensions.server_name.len
  967. = htons ( sizeof ( hello.extensions.server_name.list ) );
  968. hello.extensions.server_name.list[0].type = TLS_SERVER_NAME_HOST_NAME;
  969. hello.extensions.server_name.list[0].len
  970. = htons ( sizeof ( hello.extensions.server_name.list[0].name ));
  971. memcpy ( hello.extensions.server_name.list[0].name, session->name,
  972. sizeof ( hello.extensions.server_name.list[0].name ) );
  973. hello.extensions.max_fragment_length_type
  974. = htons ( TLS_MAX_FRAGMENT_LENGTH );
  975. hello.extensions.max_fragment_length_len
  976. = htons ( sizeof ( hello.extensions.max_fragment_length ) );
  977. hello.extensions.max_fragment_length.max
  978. = TLS_MAX_FRAGMENT_LENGTH_4096;
  979. hello.extensions.signature_algorithms_type
  980. = htons ( TLS_SIGNATURE_ALGORITHMS );
  981. hello.extensions.signature_algorithms_len
  982. = htons ( sizeof ( hello.extensions.signature_algorithms ) );
  983. hello.extensions.signature_algorithms.len
  984. = htons ( sizeof ( hello.extensions.signature_algorithms.code));
  985. i = 0 ; for_each_table_entry ( sighash, TLS_SIG_HASH_ALGORITHMS )
  986. hello.extensions.signature_algorithms.code[i++] = sighash->code;
  987. hello.extensions.renegotiation_info_type
  988. = htons ( TLS_RENEGOTIATION_INFO );
  989. hello.extensions.renegotiation_info_len
  990. = htons ( sizeof ( hello.extensions.renegotiation_info ) );
  991. hello.extensions.renegotiation_info.len
  992. = sizeof ( hello.extensions.renegotiation_info.data );
  993. memcpy ( hello.extensions.renegotiation_info.data, tls->verify.client,
  994. sizeof ( hello.extensions.renegotiation_info.data ) );
  995. hello.extensions.session_ticket_type = htons ( TLS_SESSION_TICKET );
  996. hello.extensions.session_ticket_len
  997. = htons ( sizeof ( hello.extensions.session_ticket ) );
  998. memcpy ( hello.extensions.session_ticket.data, session->ticket,
  999. sizeof ( hello.extensions.session_ticket.data ) );
  1000. return tls_send_handshake ( tls, &hello, sizeof ( hello ) );
  1001. }
  1002. /**
  1003. * Transmit Certificate record
  1004. *
  1005. * @v tls TLS connection
  1006. * @ret rc Return status code
  1007. */
  1008. static int tls_send_certificate ( struct tls_connection *tls ) {
  1009. struct {
  1010. uint32_t type_length;
  1011. tls24_t length;
  1012. struct {
  1013. tls24_t length;
  1014. uint8_t data[ tls->cert->raw.len ];
  1015. } __attribute__ (( packed )) certificates[1];
  1016. } __attribute__ (( packed )) *certificate;
  1017. int rc;
  1018. /* Allocate storage for Certificate record (which may be too
  1019. * large for the stack).
  1020. */
  1021. certificate = zalloc ( sizeof ( *certificate ) );
  1022. if ( ! certificate )
  1023. return -ENOMEM_CERTIFICATE;
  1024. /* Populate record */
  1025. certificate->type_length =
  1026. ( cpu_to_le32 ( TLS_CERTIFICATE ) |
  1027. htonl ( sizeof ( *certificate ) -
  1028. sizeof ( certificate->type_length ) ) );
  1029. tls_set_uint24 ( &certificate->length,
  1030. sizeof ( certificate->certificates ) );
  1031. tls_set_uint24 ( &certificate->certificates[0].length,
  1032. sizeof ( certificate->certificates[0].data ) );
  1033. memcpy ( certificate->certificates[0].data,
  1034. tls->cert->raw.data,
  1035. sizeof ( certificate->certificates[0].data ) );
  1036. /* Transmit record */
  1037. rc = tls_send_handshake ( tls, certificate, sizeof ( *certificate ) );
  1038. /* Free record */
  1039. free ( certificate );
  1040. return rc;
  1041. }
  1042. /**
  1043. * Transmit Client Key Exchange record
  1044. *
  1045. * @v tls TLS connection
  1046. * @ret rc Return status code
  1047. */
  1048. static int tls_send_client_key_exchange ( struct tls_connection *tls ) {
  1049. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
  1050. struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
  1051. size_t max_len = pubkey_max_len ( pubkey, cipherspec->pubkey_ctx );
  1052. struct {
  1053. uint32_t type_length;
  1054. uint16_t encrypted_pre_master_secret_len;
  1055. uint8_t encrypted_pre_master_secret[max_len];
  1056. } __attribute__ (( packed )) key_xchg;
  1057. size_t unused;
  1058. int len;
  1059. int rc;
  1060. /* Encrypt pre-master secret using server's public key */
  1061. memset ( &key_xchg, 0, sizeof ( key_xchg ) );
  1062. len = pubkey_encrypt ( pubkey, cipherspec->pubkey_ctx,
  1063. &tls->pre_master_secret,
  1064. sizeof ( tls->pre_master_secret ),
  1065. key_xchg.encrypted_pre_master_secret );
  1066. if ( len < 0 ) {
  1067. rc = len;
  1068. DBGC ( tls, "TLS %p could not encrypt pre-master secret: %s\n",
  1069. tls, strerror ( rc ) );
  1070. return rc;
  1071. }
  1072. unused = ( max_len - len );
  1073. key_xchg.type_length =
  1074. ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE ) |
  1075. htonl ( sizeof ( key_xchg ) -
  1076. sizeof ( key_xchg.type_length ) - unused ) );
  1077. key_xchg.encrypted_pre_master_secret_len =
  1078. htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) -
  1079. unused );
  1080. return tls_send_handshake ( tls, &key_xchg,
  1081. ( sizeof ( key_xchg ) - unused ) );
  1082. }
  1083. /**
  1084. * Transmit Certificate Verify record
  1085. *
  1086. * @v tls TLS connection
  1087. * @ret rc Return status code
  1088. */
  1089. static int tls_send_certificate_verify ( struct tls_connection *tls ) {
  1090. struct digest_algorithm *digest = tls->handshake_digest;
  1091. struct x509_certificate *cert = tls->cert;
  1092. struct pubkey_algorithm *pubkey = cert->signature_algorithm->pubkey;
  1093. uint8_t digest_out[ digest->digestsize ];
  1094. uint8_t ctx[ pubkey->ctxsize ];
  1095. struct tls_signature_hash_algorithm *sig_hash = NULL;
  1096. int rc;
  1097. /* Generate digest to be signed */
  1098. tls_verify_handshake ( tls, digest_out );
  1099. /* Initialise public-key algorithm */
  1100. if ( ( rc = pubkey_init ( pubkey, ctx, private_key.data,
  1101. private_key.len ) ) != 0 ) {
  1102. DBGC ( tls, "TLS %p could not initialise %s client private "
  1103. "key: %s\n", tls, pubkey->name, strerror ( rc ) );
  1104. goto err_pubkey_init;
  1105. }
  1106. /* TLSv1.2 and later use explicit algorithm identifiers */
  1107. if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
  1108. sig_hash = tls_signature_hash_algorithm ( pubkey, digest );
  1109. if ( ! sig_hash ) {
  1110. DBGC ( tls, "TLS %p could not identify (%s,%s) "
  1111. "signature and hash algorithm\n", tls,
  1112. pubkey->name, digest->name );
  1113. rc = -ENOTSUP_SIG_HASH;
  1114. goto err_sig_hash;
  1115. }
  1116. }
  1117. /* Generate and transmit record */
  1118. {
  1119. size_t max_len = pubkey_max_len ( pubkey, ctx );
  1120. int use_sig_hash = ( ( sig_hash == NULL ) ? 0 : 1 );
  1121. struct {
  1122. uint32_t type_length;
  1123. struct tls_signature_hash_id sig_hash[use_sig_hash];
  1124. uint16_t signature_len;
  1125. uint8_t signature[max_len];
  1126. } __attribute__ (( packed )) certificate_verify;
  1127. size_t unused;
  1128. int len;
  1129. /* Sign digest */
  1130. len = pubkey_sign ( pubkey, ctx, digest, digest_out,
  1131. certificate_verify.signature );
  1132. if ( len < 0 ) {
  1133. rc = len;
  1134. DBGC ( tls, "TLS %p could not sign %s digest using %s "
  1135. "client private key: %s\n", tls, digest->name,
  1136. pubkey->name, strerror ( rc ) );
  1137. goto err_pubkey_sign;
  1138. }
  1139. unused = ( max_len - len );
  1140. /* Construct Certificate Verify record */
  1141. certificate_verify.type_length =
  1142. ( cpu_to_le32 ( TLS_CERTIFICATE_VERIFY ) |
  1143. htonl ( sizeof ( certificate_verify ) -
  1144. sizeof ( certificate_verify.type_length ) -
  1145. unused ) );
  1146. if ( use_sig_hash ) {
  1147. memcpy ( &certificate_verify.sig_hash[0],
  1148. &sig_hash->code,
  1149. sizeof ( certificate_verify.sig_hash[0] ) );
  1150. }
  1151. certificate_verify.signature_len =
  1152. htons ( sizeof ( certificate_verify.signature ) -
  1153. unused );
  1154. /* Transmit record */
  1155. rc = tls_send_handshake ( tls, &certificate_verify,
  1156. ( sizeof ( certificate_verify ) - unused ) );
  1157. }
  1158. err_pubkey_sign:
  1159. err_sig_hash:
  1160. pubkey_final ( pubkey, ctx );
  1161. err_pubkey_init:
  1162. return rc;
  1163. }
  1164. /**
  1165. * Transmit Change Cipher record
  1166. *
  1167. * @v tls TLS connection
  1168. * @ret rc Return status code
  1169. */
  1170. static int tls_send_change_cipher ( struct tls_connection *tls ) {
  1171. static const uint8_t change_cipher[1] = { 1 };
  1172. return tls_send_plaintext ( tls, TLS_TYPE_CHANGE_CIPHER,
  1173. change_cipher, sizeof ( change_cipher ) );
  1174. }
  1175. /**
  1176. * Transmit Finished record
  1177. *
  1178. * @v tls TLS connection
  1179. * @ret rc Return status code
  1180. */
  1181. static int tls_send_finished ( struct tls_connection *tls ) {
  1182. struct digest_algorithm *digest = tls->handshake_digest;
  1183. struct {
  1184. uint32_t type_length;
  1185. uint8_t verify_data[ sizeof ( tls->verify.client ) ];
  1186. } __attribute__ (( packed )) finished;
  1187. uint8_t digest_out[ digest->digestsize ];
  1188. int rc;
  1189. /* Construct client verification data */
  1190. tls_verify_handshake ( tls, digest_out );
  1191. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  1192. tls->verify.client, sizeof ( tls->verify.client ),
  1193. "client finished", digest_out, sizeof ( digest_out ) );
  1194. /* Construct record */
  1195. memset ( &finished, 0, sizeof ( finished ) );
  1196. finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
  1197. htonl ( sizeof ( finished ) -
  1198. sizeof ( finished.type_length ) ) );
  1199. memcpy ( finished.verify_data, tls->verify.client,
  1200. sizeof ( finished.verify_data ) );
  1201. /* Transmit record */
  1202. if ( ( rc = tls_send_handshake ( tls, &finished,
  1203. sizeof ( finished ) ) ) != 0 )
  1204. return rc;
  1205. /* Mark client as finished */
  1206. pending_put ( &tls->client_negotiation );
  1207. return 0;
  1208. }
  1209. /**
  1210. * Receive new Change Cipher record
  1211. *
  1212. * @v tls TLS connection
  1213. * @v data Plaintext record
  1214. * @v len Length of plaintext record
  1215. * @ret rc Return status code
  1216. */
  1217. static int tls_new_change_cipher ( struct tls_connection *tls,
  1218. const void *data, size_t len ) {
  1219. int rc;
  1220. if ( ( len != 1 ) || ( *( ( uint8_t * ) data ) != 1 ) ) {
  1221. DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
  1222. DBGC_HD ( tls, data, len );
  1223. return -EINVAL_CHANGE_CIPHER;
  1224. }
  1225. if ( ( rc = tls_change_cipher ( tls, &tls->rx_cipherspec_pending,
  1226. &tls->rx_cipherspec ) ) != 0 ) {
  1227. DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
  1228. tls, strerror ( rc ) );
  1229. return rc;
  1230. }
  1231. tls->rx_seq = ~( ( uint64_t ) 0 );
  1232. return 0;
  1233. }
  1234. /**
  1235. * Receive new Alert record
  1236. *
  1237. * @v tls TLS connection
  1238. * @v data Plaintext record
  1239. * @v len Length of plaintext record
  1240. * @ret rc Return status code
  1241. */
  1242. static int tls_new_alert ( struct tls_connection *tls, const void *data,
  1243. size_t len ) {
  1244. const struct {
  1245. uint8_t level;
  1246. uint8_t description;
  1247. char next[0];
  1248. } __attribute__ (( packed )) *alert = data;
  1249. /* Sanity check */
  1250. if ( sizeof ( *alert ) != len ) {
  1251. DBGC ( tls, "TLS %p received overlength Alert\n", tls );
  1252. DBGC_HD ( tls, data, len );
  1253. return -EINVAL_ALERT;
  1254. }
  1255. switch ( alert->level ) {
  1256. case TLS_ALERT_WARNING:
  1257. DBGC ( tls, "TLS %p received warning alert %d\n",
  1258. tls, alert->description );
  1259. return 0;
  1260. case TLS_ALERT_FATAL:
  1261. DBGC ( tls, "TLS %p received fatal alert %d\n",
  1262. tls, alert->description );
  1263. return -EPERM_ALERT;
  1264. default:
  1265. DBGC ( tls, "TLS %p received unknown alert level %d"
  1266. "(alert %d)\n", tls, alert->level, alert->description );
  1267. return -EIO_ALERT;
  1268. }
  1269. }
  1270. /**
  1271. * Receive new Hello Request handshake record
  1272. *
  1273. * @v tls TLS connection
  1274. * @v data Plaintext handshake record
  1275. * @v len Length of plaintext handshake record
  1276. * @ret rc Return status code
  1277. */
  1278. static int tls_new_hello_request ( struct tls_connection *tls,
  1279. const void *data __unused,
  1280. size_t len __unused ) {
  1281. /* Ignore if a handshake is in progress */
  1282. if ( ! tls_ready ( tls ) ) {
  1283. DBGC ( tls, "TLS %p ignoring Hello Request\n", tls );
  1284. return 0;
  1285. }
  1286. /* Fail unless server supports secure renegotiation */
  1287. if ( ! tls->secure_renegotiation ) {
  1288. DBGC ( tls, "TLS %p refusing to renegotiate insecurely\n",
  1289. tls );
  1290. return -EPERM_RENEG_INSECURE;
  1291. }
  1292. /* Restart negotiation */
  1293. tls_restart ( tls );
  1294. return 0;
  1295. }
  1296. /**
  1297. * Receive new Server Hello handshake record
  1298. *
  1299. * @v tls TLS connection
  1300. * @v data Plaintext handshake record
  1301. * @v len Length of plaintext handshake record
  1302. * @ret rc Return status code
  1303. */
  1304. static int tls_new_server_hello ( struct tls_connection *tls,
  1305. const void *data, size_t len ) {
  1306. const struct {
  1307. uint16_t version;
  1308. uint8_t random[32];
  1309. uint8_t session_id_len;
  1310. uint8_t session_id[0];
  1311. } __attribute__ (( packed )) *hello_a = data;
  1312. const uint8_t *session_id;
  1313. const struct {
  1314. uint16_t cipher_suite;
  1315. uint8_t compression_method;
  1316. char next[0];
  1317. } __attribute__ (( packed )) *hello_b;
  1318. const struct {
  1319. uint16_t len;
  1320. uint8_t data[0];
  1321. } __attribute__ (( packed )) *exts;
  1322. const struct {
  1323. uint16_t type;
  1324. uint16_t len;
  1325. uint8_t data[0];
  1326. } __attribute__ (( packed )) *ext;
  1327. const struct {
  1328. uint8_t len;
  1329. uint8_t data[0];
  1330. } __attribute__ (( packed )) *reneg = NULL;
  1331. uint16_t version;
  1332. size_t exts_len;
  1333. size_t ext_len;
  1334. size_t remaining;
  1335. int rc;
  1336. /* Parse header */
  1337. if ( ( sizeof ( *hello_a ) > len ) ||
  1338. ( hello_a->session_id_len > ( len - sizeof ( *hello_a ) ) ) ||
  1339. ( sizeof ( *hello_b ) > ( len - sizeof ( *hello_a ) -
  1340. hello_a->session_id_len ) ) ) {
  1341. DBGC ( tls, "TLS %p received underlength Server Hello\n", tls );
  1342. DBGC_HD ( tls, data, len );
  1343. return -EINVAL_HELLO;
  1344. }
  1345. session_id = hello_a->session_id;
  1346. hello_b = ( ( void * ) ( session_id + hello_a->session_id_len ) );
  1347. /* Parse extensions, if present */
  1348. remaining = ( len - sizeof ( *hello_a ) - hello_a->session_id_len -
  1349. sizeof ( *hello_b ) );
  1350. if ( remaining ) {
  1351. /* Parse extensions length */
  1352. exts = ( ( void * ) hello_b->next );
  1353. if ( ( sizeof ( *exts ) > remaining ) ||
  1354. ( ( exts_len = ntohs ( exts->len ) ) >
  1355. ( remaining - sizeof ( *exts ) ) ) ) {
  1356. DBGC ( tls, "TLS %p received underlength extensions\n",
  1357. tls );
  1358. DBGC_HD ( tls, data, len );
  1359. return -EINVAL_HELLO;
  1360. }
  1361. /* Parse extensions */
  1362. for ( ext = ( ( void * ) exts->data ), remaining = exts_len ;
  1363. remaining ;
  1364. ext = ( ( ( void * ) ext ) + sizeof ( *ext ) + ext_len ),
  1365. remaining -= ( sizeof ( *ext ) + ext_len ) ) {
  1366. /* Parse extension length */
  1367. if ( ( sizeof ( *ext ) > remaining ) ||
  1368. ( ( ext_len = ntohs ( ext->len ) ) >
  1369. ( remaining - sizeof ( *ext ) ) ) ) {
  1370. DBGC ( tls, "TLS %p received underlength "
  1371. "extension\n", tls );
  1372. DBGC_HD ( tls, data, len );
  1373. return -EINVAL_HELLO;
  1374. }
  1375. /* Record known extensions */
  1376. switch ( ext->type ) {
  1377. case htons ( TLS_RENEGOTIATION_INFO ) :
  1378. reneg = ( ( void * ) ext->data );
  1379. if ( ( sizeof ( *reneg ) > ext_len ) ||
  1380. ( reneg->len >
  1381. ( ext_len - sizeof ( *reneg ) ) ) ) {
  1382. DBGC ( tls, "TLS %p received "
  1383. "underlength renegotiation "
  1384. "info\n", tls );
  1385. DBGC_HD ( tls, data, len );
  1386. return -EINVAL_HELLO;
  1387. }
  1388. break;
  1389. }
  1390. }
  1391. }
  1392. /* Check and store protocol version */
  1393. version = ntohs ( hello_a->version );
  1394. if ( version < TLS_VERSION_TLS_1_0 ) {
  1395. DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
  1396. tls, ( version >> 8 ), ( version & 0xff ) );
  1397. return -ENOTSUP_VERSION;
  1398. }
  1399. if ( version > tls->version ) {
  1400. DBGC ( tls, "TLS %p server attempted to illegally upgrade to "
  1401. "protocol version %d.%d\n",
  1402. tls, ( version >> 8 ), ( version & 0xff ) );
  1403. return -EPROTO_VERSION;
  1404. }
  1405. tls->version = version;
  1406. DBGC ( tls, "TLS %p using protocol version %d.%d\n",
  1407. tls, ( version >> 8 ), ( version & 0xff ) );
  1408. /* Use MD5+SHA1 digest algorithm for handshake verification
  1409. * for versions earlier than TLSv1.2.
  1410. */
  1411. if ( tls->version < TLS_VERSION_TLS_1_2 ) {
  1412. tls->handshake_digest = &md5_sha1_algorithm;
  1413. tls->handshake_ctx = tls->handshake_md5_sha1_ctx;
  1414. }
  1415. /* Copy out server random bytes */
  1416. memcpy ( &tls->server_random, &hello_a->random,
  1417. sizeof ( tls->server_random ) );
  1418. /* Select cipher suite */
  1419. if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
  1420. return rc;
  1421. /* Reuse or generate master secret */
  1422. if ( hello_a->session_id_len &&
  1423. ( hello_a->session_id_len == tls->session_id_len ) &&
  1424. ( memcmp ( session_id, tls->session_id,
  1425. tls->session_id_len ) == 0 ) ) {
  1426. /* Session ID match: reuse master secret */
  1427. DBGC ( tls, "TLS %p resuming session ID:\n", tls );
  1428. DBGC_HDA ( tls, 0, tls->session_id, tls->session_id_len );
  1429. } else {
  1430. /* Generate new master secret */
  1431. tls_generate_master_secret ( tls );
  1432. /* Record new session ID, if present */
  1433. if ( hello_a->session_id_len &&
  1434. ( hello_a->session_id_len <= sizeof ( tls->session_id ))){
  1435. tls->session_id_len = hello_a->session_id_len;
  1436. memcpy ( tls->session_id, session_id,
  1437. tls->session_id_len );
  1438. DBGC ( tls, "TLS %p new session ID:\n", tls );
  1439. DBGC_HDA ( tls, 0, tls->session_id,
  1440. tls->session_id_len );
  1441. }
  1442. }
  1443. /* Generate keys */
  1444. if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
  1445. return rc;
  1446. /* Handle secure renegotiation */
  1447. if ( tls->secure_renegotiation ) {
  1448. /* Secure renegotiation is expected; verify data */
  1449. if ( ( reneg == NULL ) ||
  1450. ( reneg->len != sizeof ( tls->verify ) ) ||
  1451. ( memcmp ( reneg->data, &tls->verify,
  1452. sizeof ( tls->verify ) ) != 0 ) ) {
  1453. DBGC ( tls, "TLS %p server failed secure "
  1454. "renegotiation\n", tls );
  1455. return -EPERM_RENEG_VERIFY;
  1456. }
  1457. } else if ( reneg != NULL ) {
  1458. /* Secure renegotiation is being enabled */
  1459. if ( reneg->len != 0 ) {
  1460. DBGC ( tls, "TLS %p server provided non-empty initial "
  1461. "renegotiation\n", tls );
  1462. return -EPERM_RENEG_VERIFY;
  1463. }
  1464. tls->secure_renegotiation = 1;
  1465. }
  1466. return 0;
  1467. }
  1468. /**
  1469. * Receive New Session Ticket handshake record
  1470. *
  1471. * @v tls TLS connection
  1472. * @v data Plaintext handshake record
  1473. * @v len Length of plaintext handshake record
  1474. * @ret rc Return status code
  1475. */
  1476. static int tls_new_session_ticket ( struct tls_connection *tls,
  1477. const void *data, size_t len ) {
  1478. const struct {
  1479. uint32_t lifetime;
  1480. uint16_t len;
  1481. uint8_t ticket[0];
  1482. } __attribute__ (( packed )) *new_session_ticket = data;
  1483. size_t ticket_len;
  1484. /* Parse header */
  1485. if ( sizeof ( *new_session_ticket ) > len ) {
  1486. DBGC ( tls, "TLS %p received underlength New Session Ticket\n",
  1487. tls );
  1488. DBGC_HD ( tls, data, len );
  1489. return -EINVAL_TICKET;
  1490. }
  1491. ticket_len = ntohs ( new_session_ticket->len );
  1492. if ( ticket_len > ( len - sizeof ( *new_session_ticket ) ) ) {
  1493. DBGC ( tls, "TLS %p received overlength New Session Ticket\n",
  1494. tls );
  1495. DBGC_HD ( tls, data, len );
  1496. return -EINVAL_TICKET;
  1497. }
  1498. /* Free any unapplied new session ticket */
  1499. free ( tls->new_session_ticket );
  1500. tls->new_session_ticket = NULL;
  1501. tls->new_session_ticket_len = 0;
  1502. /* Record ticket */
  1503. tls->new_session_ticket = malloc ( ticket_len );
  1504. if ( ! tls->new_session_ticket )
  1505. return -ENOMEM;
  1506. memcpy ( tls->new_session_ticket, new_session_ticket->ticket,
  1507. ticket_len );
  1508. tls->new_session_ticket_len = ticket_len;
  1509. DBGC ( tls, "TLS %p new session ticket:\n", tls );
  1510. DBGC_HDA ( tls, 0, tls->new_session_ticket,
  1511. tls->new_session_ticket_len );
  1512. return 0;
  1513. }
  1514. /**
  1515. * Parse certificate chain
  1516. *
  1517. * @v tls TLS connection
  1518. * @v data Certificate chain
  1519. * @v len Length of certificate chain
  1520. * @ret rc Return status code
  1521. */
  1522. static int tls_parse_chain ( struct tls_connection *tls,
  1523. const void *data, size_t len ) {
  1524. size_t remaining = len;
  1525. int rc;
  1526. /* Free any existing certificate chain */
  1527. x509_chain_put ( tls->chain );
  1528. tls->chain = NULL;
  1529. /* Create certificate chain */
  1530. tls->chain = x509_alloc_chain();
  1531. if ( ! tls->chain ) {
  1532. rc = -ENOMEM_CHAIN;
  1533. goto err_alloc_chain;
  1534. }
  1535. /* Add certificates to chain */
  1536. while ( remaining ) {
  1537. const struct {
  1538. tls24_t length;
  1539. uint8_t data[0];
  1540. } __attribute__ (( packed )) *certificate = data;
  1541. size_t certificate_len;
  1542. size_t record_len;
  1543. struct x509_certificate *cert;
  1544. /* Parse header */
  1545. if ( sizeof ( *certificate ) > remaining ) {
  1546. DBGC ( tls, "TLS %p underlength certificate:\n", tls );
  1547. DBGC_HDA ( tls, 0, data, remaining );
  1548. rc = -EINVAL_CERTIFICATE;
  1549. goto err_underlength;
  1550. }
  1551. certificate_len = tls_uint24 ( &certificate->length );
  1552. if ( certificate_len > ( remaining - sizeof ( *certificate ) )){
  1553. DBGC ( tls, "TLS %p overlength certificate:\n", tls );
  1554. DBGC_HDA ( tls, 0, data, remaining );
  1555. rc = -EINVAL_CERTIFICATE;
  1556. goto err_overlength;
  1557. }
  1558. record_len = ( sizeof ( *certificate ) + certificate_len );
  1559. /* Add certificate to chain */
  1560. if ( ( rc = x509_append_raw ( tls->chain, certificate->data,
  1561. certificate_len ) ) != 0 ) {
  1562. DBGC ( tls, "TLS %p could not append certificate: %s\n",
  1563. tls, strerror ( rc ) );
  1564. DBGC_HDA ( tls, 0, data, remaining );
  1565. goto err_parse;
  1566. }
  1567. cert = x509_last ( tls->chain );
  1568. DBGC ( tls, "TLS %p found certificate %s\n",
  1569. tls, x509_name ( cert ) );
  1570. /* Move to next certificate in list */
  1571. data += record_len;
  1572. remaining -= record_len;
  1573. }
  1574. return 0;
  1575. err_parse:
  1576. err_overlength:
  1577. err_underlength:
  1578. x509_chain_put ( tls->chain );
  1579. tls->chain = NULL;
  1580. err_alloc_chain:
  1581. return rc;
  1582. }
  1583. /**
  1584. * Receive new Certificate handshake record
  1585. *
  1586. * @v tls TLS connection
  1587. * @v data Plaintext handshake record
  1588. * @v len Length of plaintext handshake record
  1589. * @ret rc Return status code
  1590. */
  1591. static int tls_new_certificate ( struct tls_connection *tls,
  1592. const void *data, size_t len ) {
  1593. const struct {
  1594. tls24_t length;
  1595. uint8_t certificates[0];
  1596. } __attribute__ (( packed )) *certificate = data;
  1597. size_t certificates_len;
  1598. int rc;
  1599. /* Parse header */
  1600. if ( sizeof ( *certificate ) > len ) {
  1601. DBGC ( tls, "TLS %p received underlength Server Certificate\n",
  1602. tls );
  1603. DBGC_HD ( tls, data, len );
  1604. return -EINVAL_CERTIFICATES;
  1605. }
  1606. certificates_len = tls_uint24 ( &certificate->length );
  1607. if ( certificates_len > ( len - sizeof ( *certificate ) ) ) {
  1608. DBGC ( tls, "TLS %p received overlength Server Certificate\n",
  1609. tls );
  1610. DBGC_HD ( tls, data, len );
  1611. return -EINVAL_CERTIFICATES;
  1612. }
  1613. /* Parse certificate chain */
  1614. if ( ( rc = tls_parse_chain ( tls, certificate->certificates,
  1615. certificates_len ) ) != 0 )
  1616. return rc;
  1617. return 0;
  1618. }
  1619. /**
  1620. * Receive new Certificate Request handshake record
  1621. *
  1622. * @v tls TLS connection
  1623. * @v data Plaintext handshake record
  1624. * @v len Length of plaintext handshake record
  1625. * @ret rc Return status code
  1626. */
  1627. static int tls_new_certificate_request ( struct tls_connection *tls,
  1628. const void *data __unused,
  1629. size_t len __unused ) {
  1630. /* We can only send a single certificate, so there is no point
  1631. * in parsing the Certificate Request.
  1632. */
  1633. /* Free any existing client certificate */
  1634. x509_put ( tls->cert );
  1635. /* Determine client certificate to be sent */
  1636. tls->cert = certstore_find_key ( &private_key );
  1637. if ( ! tls->cert ) {
  1638. DBGC ( tls, "TLS %p could not find certificate corresponding "
  1639. "to private key\n", tls );
  1640. return -EPERM_CLIENT_CERT;
  1641. }
  1642. x509_get ( tls->cert );
  1643. DBGC ( tls, "TLS %p sending client certificate %s\n",
  1644. tls, x509_name ( tls->cert ) );
  1645. return 0;
  1646. }
  1647. /**
  1648. * Receive new Server Hello Done handshake record
  1649. *
  1650. * @v tls TLS connection
  1651. * @v data Plaintext handshake record
  1652. * @v len Length of plaintext handshake record
  1653. * @ret rc Return status code
  1654. */
  1655. static int tls_new_server_hello_done ( struct tls_connection *tls,
  1656. const void *data, size_t len ) {
  1657. const struct {
  1658. char next[0];
  1659. } __attribute__ (( packed )) *hello_done = data;
  1660. int rc;
  1661. /* Sanity check */
  1662. if ( sizeof ( *hello_done ) != len ) {
  1663. DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
  1664. tls );
  1665. DBGC_HD ( tls, data, len );
  1666. return -EINVAL_HELLO_DONE;
  1667. }
  1668. /* Begin certificate validation */
  1669. if ( ( rc = create_validator ( &tls->validator, tls->chain ) ) != 0 ) {
  1670. DBGC ( tls, "TLS %p could not start certificate validation: "
  1671. "%s\n", tls, strerror ( rc ) );
  1672. return rc;
  1673. }
  1674. pending_get ( &tls->validation );
  1675. return 0;
  1676. }
  1677. /**
  1678. * Receive new Finished handshake record
  1679. *
  1680. * @v tls TLS connection
  1681. * @v data Plaintext handshake record
  1682. * @v len Length of plaintext handshake record
  1683. * @ret rc Return status code
  1684. */
  1685. static int tls_new_finished ( struct tls_connection *tls,
  1686. const void *data, size_t len ) {
  1687. struct tls_session *session = tls->session;
  1688. struct digest_algorithm *digest = tls->handshake_digest;
  1689. const struct {
  1690. uint8_t verify_data[ sizeof ( tls->verify.server ) ];
  1691. char next[0];
  1692. } __attribute__ (( packed )) *finished = data;
  1693. uint8_t digest_out[ digest->digestsize ];
  1694. /* Sanity check */
  1695. if ( sizeof ( *finished ) != len ) {
  1696. DBGC ( tls, "TLS %p received overlength Finished\n", tls );
  1697. DBGC_HD ( tls, data, len );
  1698. return -EINVAL_FINISHED;
  1699. }
  1700. /* Verify data */
  1701. tls_verify_handshake ( tls, digest_out );
  1702. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  1703. tls->verify.server, sizeof ( tls->verify.server ),
  1704. "server finished", digest_out, sizeof ( digest_out ) );
  1705. if ( memcmp ( tls->verify.server, finished->verify_data,
  1706. sizeof ( tls->verify.server ) ) != 0 ) {
  1707. DBGC ( tls, "TLS %p verification failed\n", tls );
  1708. return -EPERM_VERIFY;
  1709. }
  1710. /* Mark server as finished */
  1711. pending_put ( &tls->server_negotiation );
  1712. /* If we are resuming a session (i.e. if the server Finished
  1713. * arrives before the client Finished is sent), then schedule
  1714. * transmission of Change Cipher and Finished.
  1715. */
  1716. if ( is_pending ( &tls->client_negotiation ) ) {
  1717. tls->tx_pending |= ( TLS_TX_CHANGE_CIPHER | TLS_TX_FINISHED );
  1718. tls_tx_resume ( tls );
  1719. }
  1720. /* Record session ID, ticket, and master secret, if applicable */
  1721. if ( tls->session_id_len || tls->new_session_ticket_len ) {
  1722. memcpy ( session->master_secret, tls->master_secret,
  1723. sizeof ( session->master_secret ) );
  1724. }
  1725. if ( tls->session_id_len ) {
  1726. session->id_len = tls->session_id_len;
  1727. memcpy ( session->id, tls->session_id, sizeof ( session->id ) );
  1728. }
  1729. if ( tls->new_session_ticket_len ) {
  1730. free ( session->ticket );
  1731. session->ticket = tls->new_session_ticket;
  1732. session->ticket_len = tls->new_session_ticket_len;
  1733. tls->new_session_ticket = NULL;
  1734. tls->new_session_ticket_len = 0;
  1735. }
  1736. /* Move to end of session's connection list and allow other
  1737. * connections to start making progress.
  1738. */
  1739. list_del ( &tls->list );
  1740. list_add_tail ( &tls->list, &session->conn );
  1741. tls_tx_resume_all ( session );
  1742. /* Send notification of a window change */
  1743. xfer_window_changed ( &tls->plainstream );
  1744. return 0;
  1745. }
  1746. /**
  1747. * Receive new Handshake record
  1748. *
  1749. * @v tls TLS connection
  1750. * @v data Plaintext record
  1751. * @v len Length of plaintext record
  1752. * @ret rc Return status code
  1753. */
  1754. static int tls_new_handshake ( struct tls_connection *tls,
  1755. const void *data, size_t len ) {
  1756. size_t remaining = len;
  1757. int rc;
  1758. while ( remaining ) {
  1759. const struct {
  1760. uint8_t type;
  1761. tls24_t length;
  1762. uint8_t payload[0];
  1763. } __attribute__ (( packed )) *handshake = data;
  1764. const void *payload;
  1765. size_t payload_len;
  1766. size_t record_len;
  1767. /* Parse header */
  1768. if ( sizeof ( *handshake ) > remaining ) {
  1769. DBGC ( tls, "TLS %p received underlength Handshake\n",
  1770. tls );
  1771. DBGC_HD ( tls, data, remaining );
  1772. return -EINVAL_HANDSHAKE;
  1773. }
  1774. payload_len = tls_uint24 ( &handshake->length );
  1775. if ( payload_len > ( remaining - sizeof ( *handshake ) ) ) {
  1776. DBGC ( tls, "TLS %p received overlength Handshake\n",
  1777. tls );
  1778. DBGC_HD ( tls, data, len );
  1779. return -EINVAL_HANDSHAKE;
  1780. }
  1781. payload = &handshake->payload;
  1782. record_len = ( sizeof ( *handshake ) + payload_len );
  1783. /* Handle payload */
  1784. switch ( handshake->type ) {
  1785. case TLS_HELLO_REQUEST:
  1786. rc = tls_new_hello_request ( tls, payload,
  1787. payload_len );
  1788. break;
  1789. case TLS_SERVER_HELLO:
  1790. rc = tls_new_server_hello ( tls, payload, payload_len );
  1791. break;
  1792. case TLS_NEW_SESSION_TICKET:
  1793. rc = tls_new_session_ticket ( tls, payload,
  1794. payload_len );
  1795. break;
  1796. case TLS_CERTIFICATE:
  1797. rc = tls_new_certificate ( tls, payload, payload_len );
  1798. break;
  1799. case TLS_CERTIFICATE_REQUEST:
  1800. rc = tls_new_certificate_request ( tls, payload,
  1801. payload_len );
  1802. break;
  1803. case TLS_SERVER_HELLO_DONE:
  1804. rc = tls_new_server_hello_done ( tls, payload,
  1805. payload_len );
  1806. break;
  1807. case TLS_FINISHED:
  1808. rc = tls_new_finished ( tls, payload, payload_len );
  1809. break;
  1810. default:
  1811. DBGC ( tls, "TLS %p ignoring handshake type %d\n",
  1812. tls, handshake->type );
  1813. rc = 0;
  1814. break;
  1815. }
  1816. /* Add to handshake digest (except for Hello Requests,
  1817. * which are explicitly excluded).
  1818. */
  1819. if ( handshake->type != TLS_HELLO_REQUEST )
  1820. tls_add_handshake ( tls, data, record_len );
  1821. /* Abort on failure */
  1822. if ( rc != 0 )
  1823. return rc;
  1824. /* Move to next handshake record */
  1825. data += record_len;
  1826. remaining -= record_len;
  1827. }
  1828. return 0;
  1829. }
  1830. /**
  1831. * Receive new record
  1832. *
  1833. * @v tls TLS connection
  1834. * @v type Record type
  1835. * @v rx_data List of received data buffers
  1836. * @ret rc Return status code
  1837. */
  1838. static int tls_new_record ( struct tls_connection *tls, unsigned int type,
  1839. struct list_head *rx_data ) {
  1840. struct io_buffer *iobuf;
  1841. int ( * handler ) ( struct tls_connection *tls, const void *data,
  1842. size_t len );
  1843. int rc;
  1844. /* Deliver data records to the plainstream interface */
  1845. if ( type == TLS_TYPE_DATA ) {
  1846. /* Fail unless we are ready to receive data */
  1847. if ( ! tls_ready ( tls ) )
  1848. return -ENOTCONN;
  1849. /* Deliver each I/O buffer in turn */
  1850. while ( ( iobuf = list_first_entry ( rx_data, struct io_buffer,
  1851. list ) ) ) {
  1852. list_del ( &iobuf->list );
  1853. if ( ( rc = xfer_deliver_iob ( &tls->plainstream,
  1854. iobuf ) ) != 0 ) {
  1855. DBGC ( tls, "TLS %p could not deliver data: "
  1856. "%s\n", tls, strerror ( rc ) );
  1857. return rc;
  1858. }
  1859. }
  1860. return 0;
  1861. }
  1862. /* For all other records, merge into a single I/O buffer */
  1863. iobuf = iob_concatenate ( rx_data );
  1864. if ( ! iobuf ) {
  1865. DBGC ( tls, "TLS %p could not concatenate non-data record "
  1866. "type %d\n", tls, type );
  1867. return -ENOMEM_RX_CONCAT;
  1868. }
  1869. /* Determine handler */
  1870. switch ( type ) {
  1871. case TLS_TYPE_CHANGE_CIPHER:
  1872. handler = tls_new_change_cipher;
  1873. break;
  1874. case TLS_TYPE_ALERT:
  1875. handler = tls_new_alert;
  1876. break;
  1877. case TLS_TYPE_HANDSHAKE:
  1878. handler = tls_new_handshake;
  1879. break;
  1880. default:
  1881. /* RFC4346 says that we should just ignore unknown
  1882. * record types.
  1883. */
  1884. handler = NULL;
  1885. DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
  1886. break;
  1887. }
  1888. /* Handle record and free I/O buffer */
  1889. rc = ( handler ? handler ( tls, iobuf->data, iob_len ( iobuf ) ) : 0 );
  1890. free_iob ( iobuf );
  1891. return rc;
  1892. }
  1893. /******************************************************************************
  1894. *
  1895. * Record encryption/decryption
  1896. *
  1897. ******************************************************************************
  1898. */
  1899. /**
  1900. * Initialise HMAC
  1901. *
  1902. * @v cipherspec Cipher specification
  1903. * @v ctx Context
  1904. * @v seq Sequence number
  1905. * @v tlshdr TLS header
  1906. */
  1907. static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
  1908. uint64_t seq, struct tls_header *tlshdr ) {
  1909. struct digest_algorithm *digest = cipherspec->suite->digest;
  1910. hmac_init ( digest, ctx, cipherspec->mac_secret, &digest->digestsize );
  1911. seq = cpu_to_be64 ( seq );
  1912. hmac_update ( digest, ctx, &seq, sizeof ( seq ) );
  1913. hmac_update ( digest, ctx, tlshdr, sizeof ( *tlshdr ) );
  1914. }
  1915. /**
  1916. * Update HMAC
  1917. *
  1918. * @v cipherspec Cipher specification
  1919. * @v ctx Context
  1920. * @v data Data
  1921. * @v len Length of data
  1922. */
  1923. static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
  1924. const void *data, size_t len ) {
  1925. struct digest_algorithm *digest = cipherspec->suite->digest;
  1926. hmac_update ( digest, ctx, data, len );
  1927. }
  1928. /**
  1929. * Finalise HMAC
  1930. *
  1931. * @v cipherspec Cipher specification
  1932. * @v ctx Context
  1933. * @v mac HMAC to fill in
  1934. */
  1935. static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
  1936. void *hmac ) {
  1937. struct digest_algorithm *digest = cipherspec->suite->digest;
  1938. hmac_final ( digest, ctx, cipherspec->mac_secret,
  1939. &digest->digestsize, hmac );
  1940. }
  1941. /**
  1942. * Calculate HMAC
  1943. *
  1944. * @v cipherspec Cipher specification
  1945. * @v seq Sequence number
  1946. * @v tlshdr TLS header
  1947. * @v data Data
  1948. * @v len Length of data
  1949. * @v mac HMAC to fill in
  1950. */
  1951. static void tls_hmac ( struct tls_cipherspec *cipherspec,
  1952. uint64_t seq, struct tls_header *tlshdr,
  1953. const void *data, size_t len, void *hmac ) {
  1954. struct digest_algorithm *digest = cipherspec->suite->digest;
  1955. uint8_t ctx[digest->ctxsize];
  1956. tls_hmac_init ( cipherspec, ctx, seq, tlshdr );
  1957. tls_hmac_update ( cipherspec, ctx, data, len );
  1958. tls_hmac_final ( cipherspec, ctx, hmac );
  1959. }
  1960. /**
  1961. * Allocate and assemble stream-ciphered record from data and MAC portions
  1962. *
  1963. * @v tls TLS connection
  1964. * @ret data Data
  1965. * @ret len Length of data
  1966. * @ret digest MAC digest
  1967. * @ret plaintext_len Length of plaintext record
  1968. * @ret plaintext Allocated plaintext record
  1969. */
  1970. static void * __malloc
  1971. tls_assemble_stream ( struct tls_connection *tls, const void *data, size_t len,
  1972. void *digest, size_t *plaintext_len ) {
  1973. size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
  1974. void *plaintext;
  1975. void *content;
  1976. void *mac;
  1977. /* Calculate stream-ciphered struct length */
  1978. *plaintext_len = ( len + mac_len );
  1979. /* Allocate stream-ciphered struct */
  1980. plaintext = malloc ( *plaintext_len );
  1981. if ( ! plaintext )
  1982. return NULL;
  1983. content = plaintext;
  1984. mac = ( content + len );
  1985. /* Fill in stream-ciphered struct */
  1986. memcpy ( content, data, len );
  1987. memcpy ( mac, digest, mac_len );
  1988. return plaintext;
  1989. }
  1990. /**
  1991. * Allocate and assemble block-ciphered record from data and MAC portions
  1992. *
  1993. * @v tls TLS connection
  1994. * @ret data Data
  1995. * @ret len Length of data
  1996. * @ret digest MAC digest
  1997. * @ret plaintext_len Length of plaintext record
  1998. * @ret plaintext Allocated plaintext record
  1999. */
  2000. static void * tls_assemble_block ( struct tls_connection *tls,
  2001. const void *data, size_t len,
  2002. void *digest, size_t *plaintext_len ) {
  2003. size_t blocksize = tls->tx_cipherspec.suite->cipher->blocksize;
  2004. size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
  2005. size_t iv_len;
  2006. size_t padding_len;
  2007. void *plaintext;
  2008. void *iv;
  2009. void *content;
  2010. void *mac;
  2011. void *padding;
  2012. /* TLSv1.1 and later use an explicit IV */
  2013. iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ? blocksize : 0 );
  2014. /* Calculate block-ciphered struct length */
  2015. padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
  2016. *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
  2017. /* Allocate block-ciphered struct */
  2018. plaintext = malloc ( *plaintext_len );
  2019. if ( ! plaintext )
  2020. return NULL;
  2021. iv = plaintext;
  2022. content = ( iv + iv_len );
  2023. mac = ( content + len );
  2024. padding = ( mac + mac_len );
  2025. /* Fill in block-ciphered struct */
  2026. tls_generate_random ( tls, iv, iv_len );
  2027. memcpy ( content, data, len );
  2028. memcpy ( mac, digest, mac_len );
  2029. memset ( padding, padding_len, ( padding_len + 1 ) );
  2030. return plaintext;
  2031. }
  2032. /**
  2033. * Send plaintext record
  2034. *
  2035. * @v tls TLS connection
  2036. * @v type Record type
  2037. * @v data Plaintext record
  2038. * @v len Length of plaintext record
  2039. * @ret rc Return status code
  2040. */
  2041. static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
  2042. const void *data, size_t len ) {
  2043. struct tls_header plaintext_tlshdr;
  2044. struct tls_header *tlshdr;
  2045. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
  2046. struct cipher_algorithm *cipher = cipherspec->suite->cipher;
  2047. void *plaintext = NULL;
  2048. size_t plaintext_len;
  2049. struct io_buffer *ciphertext = NULL;
  2050. size_t ciphertext_len;
  2051. size_t mac_len = cipherspec->suite->digest->digestsize;
  2052. uint8_t mac[mac_len];
  2053. int rc;
  2054. /* Construct header */
  2055. plaintext_tlshdr.type = type;
  2056. plaintext_tlshdr.version = htons ( tls->version );
  2057. plaintext_tlshdr.length = htons ( len );
  2058. /* Calculate MAC */
  2059. tls_hmac ( cipherspec, tls->tx_seq, &plaintext_tlshdr, data, len, mac );
  2060. /* Allocate and assemble plaintext struct */
  2061. if ( is_stream_cipher ( cipher ) ) {
  2062. plaintext = tls_assemble_stream ( tls, data, len, mac,
  2063. &plaintext_len );
  2064. } else {
  2065. plaintext = tls_assemble_block ( tls, data, len, mac,
  2066. &plaintext_len );
  2067. }
  2068. if ( ! plaintext ) {
  2069. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  2070. "plaintext\n", tls, plaintext_len );
  2071. rc = -ENOMEM_TX_PLAINTEXT;
  2072. goto done;
  2073. }
  2074. DBGC2 ( tls, "Sending plaintext data:\n" );
  2075. DBGC2_HD ( tls, plaintext, plaintext_len );
  2076. /* Allocate ciphertext */
  2077. ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
  2078. ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
  2079. if ( ! ciphertext ) {
  2080. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  2081. "ciphertext\n", tls, ciphertext_len );
  2082. rc = -ENOMEM_TX_CIPHERTEXT;
  2083. goto done;
  2084. }
  2085. /* Assemble ciphertext */
  2086. tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
  2087. tlshdr->type = type;
  2088. tlshdr->version = htons ( tls->version );
  2089. tlshdr->length = htons ( plaintext_len );
  2090. memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
  2091. cipher->ctxsize );
  2092. cipher_encrypt ( cipher, cipherspec->cipher_next_ctx, plaintext,
  2093. iob_put ( ciphertext, plaintext_len ), plaintext_len );
  2094. /* Free plaintext as soon as possible to conserve memory */
  2095. free ( plaintext );
  2096. plaintext = NULL;
  2097. /* Send ciphertext */
  2098. if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
  2099. iob_disown ( ciphertext ) ) ) != 0 ) {
  2100. DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
  2101. tls, strerror ( rc ) );
  2102. goto done;
  2103. }
  2104. /* Update TX state machine to next record */
  2105. tls->tx_seq += 1;
  2106. memcpy ( tls->tx_cipherspec.cipher_ctx,
  2107. tls->tx_cipherspec.cipher_next_ctx, cipher->ctxsize );
  2108. done:
  2109. free ( plaintext );
  2110. free_iob ( ciphertext );
  2111. return rc;
  2112. }
  2113. /**
  2114. * Split stream-ciphered record into data and MAC portions
  2115. *
  2116. * @v tls TLS connection
  2117. * @v rx_data List of received data buffers
  2118. * @v mac MAC to fill in
  2119. * @ret rc Return status code
  2120. */
  2121. static int tls_split_stream ( struct tls_connection *tls,
  2122. struct list_head *rx_data, void **mac ) {
  2123. size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
  2124. struct io_buffer *iobuf;
  2125. /* Extract MAC */
  2126. iobuf = list_last_entry ( rx_data, struct io_buffer, list );
  2127. assert ( iobuf != NULL );
  2128. if ( iob_len ( iobuf ) < mac_len ) {
  2129. DBGC ( tls, "TLS %p received underlength MAC\n", tls );
  2130. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  2131. return -EINVAL_STREAM;
  2132. }
  2133. iob_unput ( iobuf, mac_len );
  2134. *mac = iobuf->tail;
  2135. return 0;
  2136. }
  2137. /**
  2138. * Split block-ciphered record into data and MAC portions
  2139. *
  2140. * @v tls TLS connection
  2141. * @v rx_data List of received data buffers
  2142. * @v mac MAC to fill in
  2143. * @ret rc Return status code
  2144. */
  2145. static int tls_split_block ( struct tls_connection *tls,
  2146. struct list_head *rx_data, void **mac ) {
  2147. size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
  2148. struct io_buffer *iobuf;
  2149. size_t iv_len;
  2150. uint8_t *padding_final;
  2151. uint8_t *padding;
  2152. size_t padding_len;
  2153. /* TLSv1.1 and later use an explicit IV */
  2154. iobuf = list_first_entry ( rx_data, struct io_buffer, list );
  2155. iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ?
  2156. tls->rx_cipherspec.suite->cipher->blocksize : 0 );
  2157. if ( iob_len ( iobuf ) < iv_len ) {
  2158. DBGC ( tls, "TLS %p received underlength IV\n", tls );
  2159. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  2160. return -EINVAL_BLOCK;
  2161. }
  2162. iob_pull ( iobuf, iv_len );
  2163. /* Extract and verify padding */
  2164. iobuf = list_last_entry ( rx_data, struct io_buffer, list );
  2165. padding_final = ( iobuf->tail - 1 );
  2166. padding_len = *padding_final;
  2167. if ( ( padding_len + 1 ) > iob_len ( iobuf ) ) {
  2168. DBGC ( tls, "TLS %p received underlength padding\n", tls );
  2169. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  2170. return -EINVAL_BLOCK;
  2171. }
  2172. iob_unput ( iobuf, ( padding_len + 1 ) );
  2173. for ( padding = iobuf->tail ; padding < padding_final ; padding++ ) {
  2174. if ( *padding != padding_len ) {
  2175. DBGC ( tls, "TLS %p received bad padding\n", tls );
  2176. DBGC_HD ( tls, padding, padding_len );
  2177. return -EINVAL_PADDING;
  2178. }
  2179. }
  2180. /* Extract MAC */
  2181. if ( iob_len ( iobuf ) < mac_len ) {
  2182. DBGC ( tls, "TLS %p received underlength MAC\n", tls );
  2183. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  2184. return -EINVAL_BLOCK;
  2185. }
  2186. iob_unput ( iobuf, mac_len );
  2187. *mac = iobuf->tail;
  2188. return 0;
  2189. }
  2190. /**
  2191. * Receive new ciphertext record
  2192. *
  2193. * @v tls TLS connection
  2194. * @v tlshdr Record header
  2195. * @v rx_data List of received data buffers
  2196. * @ret rc Return status code
  2197. */
  2198. static int tls_new_ciphertext ( struct tls_connection *tls,
  2199. struct tls_header *tlshdr,
  2200. struct list_head *rx_data ) {
  2201. struct tls_header plaintext_tlshdr;
  2202. struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
  2203. struct cipher_algorithm *cipher = cipherspec->suite->cipher;
  2204. struct digest_algorithm *digest = cipherspec->suite->digest;
  2205. uint8_t ctx[digest->ctxsize];
  2206. uint8_t verify_mac[digest->digestsize];
  2207. struct io_buffer *iobuf;
  2208. void *mac;
  2209. size_t len = 0;
  2210. int rc;
  2211. /* Decrypt the received data */
  2212. list_for_each_entry ( iobuf, &tls->rx_data, list ) {
  2213. cipher_decrypt ( cipher, cipherspec->cipher_ctx,
  2214. iobuf->data, iobuf->data, iob_len ( iobuf ) );
  2215. }
  2216. /* Split record into content and MAC */
  2217. if ( is_stream_cipher ( cipher ) ) {
  2218. if ( ( rc = tls_split_stream ( tls, rx_data, &mac ) ) != 0 )
  2219. return rc;
  2220. } else {
  2221. if ( ( rc = tls_split_block ( tls, rx_data, &mac ) ) != 0 )
  2222. return rc;
  2223. }
  2224. /* Calculate total length */
  2225. DBGC2 ( tls, "Received plaintext data:\n" );
  2226. list_for_each_entry ( iobuf, rx_data, list ) {
  2227. DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  2228. len += iob_len ( iobuf );
  2229. }
  2230. /* Verify MAC */
  2231. plaintext_tlshdr.type = tlshdr->type;
  2232. plaintext_tlshdr.version = tlshdr->version;
  2233. plaintext_tlshdr.length = htons ( len );
  2234. tls_hmac_init ( cipherspec, ctx, tls->rx_seq, &plaintext_tlshdr );
  2235. list_for_each_entry ( iobuf, rx_data, list ) {
  2236. tls_hmac_update ( cipherspec, ctx, iobuf->data,
  2237. iob_len ( iobuf ) );
  2238. }
  2239. tls_hmac_final ( cipherspec, ctx, verify_mac );
  2240. if ( memcmp ( mac, verify_mac, sizeof ( verify_mac ) ) != 0 ) {
  2241. DBGC ( tls, "TLS %p failed MAC verification\n", tls );
  2242. return -EINVAL_MAC;
  2243. }
  2244. /* Process plaintext record */
  2245. if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
  2246. return rc;
  2247. return 0;
  2248. }
  2249. /******************************************************************************
  2250. *
  2251. * Plaintext stream operations
  2252. *
  2253. ******************************************************************************
  2254. */
  2255. /**
  2256. * Check flow control window
  2257. *
  2258. * @v tls TLS connection
  2259. * @ret len Length of window
  2260. */
  2261. static size_t tls_plainstream_window ( struct tls_connection *tls ) {
  2262. /* Block window unless we are ready to accept data */
  2263. if ( ! tls_ready ( tls ) )
  2264. return 0;
  2265. return xfer_window ( &tls->cipherstream );
  2266. }
  2267. /**
  2268. * Deliver datagram as raw data
  2269. *
  2270. * @v tls TLS connection
  2271. * @v iobuf I/O buffer
  2272. * @v meta Data transfer metadata
  2273. * @ret rc Return status code
  2274. */
  2275. static int tls_plainstream_deliver ( struct tls_connection *tls,
  2276. struct io_buffer *iobuf,
  2277. struct xfer_metadata *meta __unused ) {
  2278. int rc;
  2279. /* Refuse unless we are ready to accept data */
  2280. if ( ! tls_ready ( tls ) ) {
  2281. rc = -ENOTCONN;
  2282. goto done;
  2283. }
  2284. if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
  2285. iob_len ( iobuf ) ) ) != 0 )
  2286. goto done;
  2287. done:
  2288. free_iob ( iobuf );
  2289. return rc;
  2290. }
  2291. /**
  2292. * Report job progress
  2293. *
  2294. * @v tls TLS connection
  2295. * @v progress Progress report to fill in
  2296. * @ret ongoing_rc Ongoing job status code (if known)
  2297. */
  2298. static int tls_progress ( struct tls_connection *tls,
  2299. struct job_progress *progress ) {
  2300. /* Return cipherstream or validator progress as applicable */
  2301. if ( is_pending ( &tls->validation ) ) {
  2302. return job_progress ( &tls->validator, progress );
  2303. } else {
  2304. return job_progress ( &tls->cipherstream, progress );
  2305. }
  2306. }
  2307. /** TLS plaintext stream interface operations */
  2308. static struct interface_operation tls_plainstream_ops[] = {
  2309. INTF_OP ( xfer_deliver, struct tls_connection *,
  2310. tls_plainstream_deliver ),
  2311. INTF_OP ( xfer_window, struct tls_connection *,
  2312. tls_plainstream_window ),
  2313. INTF_OP ( job_progress, struct tls_connection *, tls_progress ),
  2314. INTF_OP ( intf_close, struct tls_connection *, tls_close ),
  2315. };
  2316. /** TLS plaintext stream interface descriptor */
  2317. static struct interface_descriptor tls_plainstream_desc =
  2318. INTF_DESC_PASSTHRU ( struct tls_connection, plainstream,
  2319. tls_plainstream_ops, cipherstream );
  2320. /******************************************************************************
  2321. *
  2322. * Ciphertext stream operations
  2323. *
  2324. ******************************************************************************
  2325. */
  2326. /**
  2327. * Handle received TLS header
  2328. *
  2329. * @v tls TLS connection
  2330. * @ret rc Returned status code
  2331. */
  2332. static int tls_newdata_process_header ( struct tls_connection *tls ) {
  2333. size_t data_len = ntohs ( tls->rx_header.length );
  2334. size_t remaining = data_len;
  2335. size_t frag_len;
  2336. struct io_buffer *iobuf;
  2337. struct io_buffer *tmp;
  2338. int rc;
  2339. /* Allocate data buffers now that we know the length */
  2340. assert ( list_empty ( &tls->rx_data ) );
  2341. while ( remaining ) {
  2342. /* Calculate fragment length. Ensure that no block is
  2343. * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
  2344. * allocation length if necessary).
  2345. */
  2346. frag_len = remaining;
  2347. if ( frag_len > TLS_RX_BUFSIZE )
  2348. frag_len = TLS_RX_BUFSIZE;
  2349. remaining -= frag_len;
  2350. if ( remaining < TLS_RX_MIN_BUFSIZE ) {
  2351. frag_len += remaining;
  2352. remaining = 0;
  2353. }
  2354. /* Allocate buffer */
  2355. iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
  2356. if ( ! iobuf ) {
  2357. DBGC ( tls, "TLS %p could not allocate %zd of %zd "
  2358. "bytes for receive buffer\n", tls,
  2359. remaining, data_len );
  2360. rc = -ENOMEM_RX_DATA;
  2361. goto err;
  2362. }
  2363. /* Ensure tailroom is exactly what we asked for. This
  2364. * will result in unaligned I/O buffers when the
  2365. * fragment length is unaligned, which can happen only
  2366. * before we switch to using a block cipher.
  2367. */
  2368. iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
  2369. /* Add I/O buffer to list */
  2370. list_add_tail ( &iobuf->list, &tls->rx_data );
  2371. }
  2372. /* Move to data state */
  2373. tls->rx_state = TLS_RX_DATA;
  2374. return 0;
  2375. err:
  2376. list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
  2377. list_del ( &iobuf->list );
  2378. free_iob ( iobuf );
  2379. }
  2380. return rc;
  2381. }
  2382. /**
  2383. * Handle received TLS data payload
  2384. *
  2385. * @v tls TLS connection
  2386. * @ret rc Returned status code
  2387. */
  2388. static int tls_newdata_process_data ( struct tls_connection *tls ) {
  2389. struct io_buffer *iobuf;
  2390. int rc;
  2391. /* Move current buffer to end of list */
  2392. iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
  2393. list_del ( &iobuf->list );
  2394. list_add_tail ( &iobuf->list, &tls->rx_data );
  2395. /* Continue receiving data if any space remains */
  2396. iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
  2397. if ( iob_tailroom ( iobuf ) )
  2398. return 0;
  2399. /* Process record */
  2400. if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
  2401. &tls->rx_data ) ) != 0 )
  2402. return rc;
  2403. /* Increment RX sequence number */
  2404. tls->rx_seq += 1;
  2405. /* Return to header state */
  2406. assert ( list_empty ( &tls->rx_data ) );
  2407. tls->rx_state = TLS_RX_HEADER;
  2408. iob_unput ( &tls->rx_header_iobuf, sizeof ( tls->rx_header ) );
  2409. return 0;
  2410. }
  2411. /**
  2412. * Check flow control window
  2413. *
  2414. * @v tls TLS connection
  2415. * @ret len Length of window
  2416. */
  2417. static size_t tls_cipherstream_window ( struct tls_connection *tls ) {
  2418. /* Open window until we are ready to accept data */
  2419. if ( ! tls_ready ( tls ) )
  2420. return -1UL;
  2421. return xfer_window ( &tls->plainstream );
  2422. }
  2423. /**
  2424. * Receive new ciphertext
  2425. *
  2426. * @v tls TLS connection
  2427. * @v iobuf I/O buffer
  2428. * @v meta Data transfer metadat
  2429. * @ret rc Return status code
  2430. */
  2431. static int tls_cipherstream_deliver ( struct tls_connection *tls,
  2432. struct io_buffer *iobuf,
  2433. struct xfer_metadata *xfer __unused ) {
  2434. size_t frag_len;
  2435. int ( * process ) ( struct tls_connection *tls );
  2436. struct io_buffer *dest;
  2437. int rc;
  2438. while ( iob_len ( iobuf ) ) {
  2439. /* Select buffer according to current state */
  2440. switch ( tls->rx_state ) {
  2441. case TLS_RX_HEADER:
  2442. dest = &tls->rx_header_iobuf;
  2443. process = tls_newdata_process_header;
  2444. break;
  2445. case TLS_RX_DATA:
  2446. dest = list_first_entry ( &tls->rx_data,
  2447. struct io_buffer, list );
  2448. assert ( dest != NULL );
  2449. process = tls_newdata_process_data;
  2450. break;
  2451. default:
  2452. assert ( 0 );
  2453. rc = -EINVAL_RX_STATE;
  2454. goto done;
  2455. }
  2456. /* Copy data portion to buffer */
  2457. frag_len = iob_len ( iobuf );
  2458. if ( frag_len > iob_tailroom ( dest ) )
  2459. frag_len = iob_tailroom ( dest );
  2460. memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
  2461. iob_pull ( iobuf, frag_len );
  2462. /* Process data if buffer is now full */
  2463. if ( iob_tailroom ( dest ) == 0 ) {
  2464. if ( ( rc = process ( tls ) ) != 0 ) {
  2465. tls_close ( tls, rc );
  2466. goto done;
  2467. }
  2468. }
  2469. }
  2470. rc = 0;
  2471. done:
  2472. free_iob ( iobuf );
  2473. return rc;
  2474. }
  2475. /** TLS ciphertext stream interface operations */
  2476. static struct interface_operation tls_cipherstream_ops[] = {
  2477. INTF_OP ( xfer_deliver, struct tls_connection *,
  2478. tls_cipherstream_deliver ),
  2479. INTF_OP ( xfer_window, struct tls_connection *,
  2480. tls_cipherstream_window ),
  2481. INTF_OP ( xfer_window_changed, struct tls_connection *,
  2482. tls_tx_resume ),
  2483. INTF_OP ( intf_close, struct tls_connection *, tls_close ),
  2484. };
  2485. /** TLS ciphertext stream interface descriptor */
  2486. static struct interface_descriptor tls_cipherstream_desc =
  2487. INTF_DESC_PASSTHRU ( struct tls_connection, cipherstream,
  2488. tls_cipherstream_ops, plainstream );
  2489. /******************************************************************************
  2490. *
  2491. * Certificate validator
  2492. *
  2493. ******************************************************************************
  2494. */
  2495. /**
  2496. * Handle certificate validation completion
  2497. *
  2498. * @v tls TLS connection
  2499. * @v rc Reason for completion
  2500. */
  2501. static void tls_validator_done ( struct tls_connection *tls, int rc ) {
  2502. struct tls_session *session = tls->session;
  2503. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
  2504. struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
  2505. struct x509_certificate *cert;
  2506. /* Mark validation as complete */
  2507. pending_put ( &tls->validation );
  2508. /* Close validator interface */
  2509. intf_restart ( &tls->validator, rc );
  2510. /* Check for validation failure */
  2511. if ( rc != 0 ) {
  2512. DBGC ( tls, "TLS %p certificate validation failed: %s\n",
  2513. tls, strerror ( rc ) );
  2514. goto err;
  2515. }
  2516. DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
  2517. /* Extract first certificate */
  2518. cert = x509_first ( tls->chain );
  2519. assert ( cert != NULL );
  2520. /* Verify server name */
  2521. if ( ( rc = x509_check_name ( cert, session->name ) ) != 0 ) {
  2522. DBGC ( tls, "TLS %p server certificate does not match %s: %s\n",
  2523. tls, session->name, strerror ( rc ) );
  2524. goto err;
  2525. }
  2526. /* Initialise public key algorithm */
  2527. if ( ( rc = pubkey_init ( pubkey, cipherspec->pubkey_ctx,
  2528. cert->subject.public_key.raw.data,
  2529. cert->subject.public_key.raw.len ) ) != 0 ) {
  2530. DBGC ( tls, "TLS %p cannot initialise public key: %s\n",
  2531. tls, strerror ( rc ) );
  2532. goto err;
  2533. }
  2534. /* Schedule Client Key Exchange, Change Cipher, and Finished */
  2535. tls->tx_pending |= ( TLS_TX_CLIENT_KEY_EXCHANGE |
  2536. TLS_TX_CHANGE_CIPHER |
  2537. TLS_TX_FINISHED );
  2538. if ( tls->cert ) {
  2539. tls->tx_pending |= ( TLS_TX_CERTIFICATE |
  2540. TLS_TX_CERTIFICATE_VERIFY );
  2541. }
  2542. tls_tx_resume ( tls );
  2543. return;
  2544. err:
  2545. tls_close ( tls, rc );
  2546. return;
  2547. }
  2548. /** TLS certificate validator interface operations */
  2549. static struct interface_operation tls_validator_ops[] = {
  2550. INTF_OP ( intf_close, struct tls_connection *, tls_validator_done ),
  2551. };
  2552. /** TLS certificate validator interface descriptor */
  2553. static struct interface_descriptor tls_validator_desc =
  2554. INTF_DESC ( struct tls_connection, validator, tls_validator_ops );
  2555. /******************************************************************************
  2556. *
  2557. * Controlling process
  2558. *
  2559. ******************************************************************************
  2560. */
  2561. /**
  2562. * TLS TX state machine
  2563. *
  2564. * @v tls TLS connection
  2565. */
  2566. static void tls_tx_step ( struct tls_connection *tls ) {
  2567. struct tls_session *session = tls->session;
  2568. struct tls_connection *conn;
  2569. int rc;
  2570. /* Wait for cipherstream to become ready */
  2571. if ( ! xfer_window ( &tls->cipherstream ) )
  2572. return;
  2573. /* Send first pending transmission */
  2574. if ( tls->tx_pending & TLS_TX_CLIENT_HELLO ) {
  2575. /* Serialise server negotiations within a session, to
  2576. * provide a consistent view of session IDs and
  2577. * session tickets.
  2578. */
  2579. list_for_each_entry ( conn, &session->conn, list ) {
  2580. if ( conn == tls )
  2581. break;
  2582. if ( is_pending ( &conn->server_negotiation ) )
  2583. return;
  2584. }
  2585. /* Record or generate session ID and associated master secret */
  2586. if ( session->id_len ) {
  2587. /* Attempt to resume an existing session */
  2588. memcpy ( tls->session_id, session->id,
  2589. sizeof ( tls->session_id ) );
  2590. tls->session_id_len = session->id_len;
  2591. memcpy ( tls->master_secret, session->master_secret,
  2592. sizeof ( tls->master_secret ) );
  2593. } else {
  2594. /* No existing session: use a random session ID */
  2595. assert ( sizeof ( tls->session_id ) ==
  2596. sizeof ( tls->client_random ) );
  2597. memcpy ( tls->session_id, &tls->client_random,
  2598. sizeof ( tls->session_id ) );
  2599. tls->session_id_len = sizeof ( tls->session_id );
  2600. }
  2601. /* Send Client Hello */
  2602. if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
  2603. DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
  2604. tls, strerror ( rc ) );
  2605. goto err;
  2606. }
  2607. tls->tx_pending &= ~TLS_TX_CLIENT_HELLO;
  2608. } else if ( tls->tx_pending & TLS_TX_CERTIFICATE ) {
  2609. /* Send Certificate */
  2610. if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
  2611. DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
  2612. tls, strerror ( rc ) );
  2613. goto err;
  2614. }
  2615. tls->tx_pending &= ~TLS_TX_CERTIFICATE;
  2616. } else if ( tls->tx_pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
  2617. /* Send Client Key Exchange */
  2618. if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
  2619. DBGC ( tls, "TLS %p could not send Client Key "
  2620. "Exchange: %s\n", tls, strerror ( rc ) );
  2621. goto err;
  2622. }
  2623. tls->tx_pending &= ~TLS_TX_CLIENT_KEY_EXCHANGE;
  2624. } else if ( tls->tx_pending & TLS_TX_CERTIFICATE_VERIFY ) {
  2625. /* Send Certificate Verify */
  2626. if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
  2627. DBGC ( tls, "TLS %p could not send Certificate "
  2628. "Verify: %s\n", tls, strerror ( rc ) );
  2629. goto err;
  2630. }
  2631. tls->tx_pending &= ~TLS_TX_CERTIFICATE_VERIFY;
  2632. } else if ( tls->tx_pending & TLS_TX_CHANGE_CIPHER ) {
  2633. /* Send Change Cipher, and then change the cipher in use */
  2634. if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
  2635. DBGC ( tls, "TLS %p could not send Change Cipher: "
  2636. "%s\n", tls, strerror ( rc ) );
  2637. goto err;
  2638. }
  2639. if ( ( rc = tls_change_cipher ( tls,
  2640. &tls->tx_cipherspec_pending,
  2641. &tls->tx_cipherspec )) != 0 ){
  2642. DBGC ( tls, "TLS %p could not activate TX cipher: "
  2643. "%s\n", tls, strerror ( rc ) );
  2644. goto err;
  2645. }
  2646. tls->tx_seq = 0;
  2647. tls->tx_pending &= ~TLS_TX_CHANGE_CIPHER;
  2648. } else if ( tls->tx_pending & TLS_TX_FINISHED ) {
  2649. /* Send Finished */
  2650. if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
  2651. DBGC ( tls, "TLS %p could not send Finished: %s\n",
  2652. tls, strerror ( rc ) );
  2653. goto err;
  2654. }
  2655. tls->tx_pending &= ~TLS_TX_FINISHED;
  2656. }
  2657. /* Reschedule process if pending transmissions remain,
  2658. * otherwise send notification of a window change.
  2659. */
  2660. if ( tls->tx_pending ) {
  2661. tls_tx_resume ( tls );
  2662. } else {
  2663. xfer_window_changed ( &tls->plainstream );
  2664. }
  2665. return;
  2666. err:
  2667. tls_close ( tls, rc );
  2668. }
  2669. /** TLS TX process descriptor */
  2670. static struct process_descriptor tls_process_desc =
  2671. PROC_DESC_ONCE ( struct tls_connection, process, tls_tx_step );
  2672. /******************************************************************************
  2673. *
  2674. * Session management
  2675. *
  2676. ******************************************************************************
  2677. */
  2678. /**
  2679. * Find or create session for TLS connection
  2680. *
  2681. * @v tls TLS connection
  2682. * @v name Server name
  2683. * @ret rc Return status code
  2684. */
  2685. static int tls_session ( struct tls_connection *tls, const char *name ) {
  2686. struct tls_session *session;
  2687. char *name_copy;
  2688. int rc;
  2689. /* Find existing matching session, if any */
  2690. list_for_each_entry ( session, &tls_sessions, list ) {
  2691. if ( strcmp ( name, session->name ) == 0 ) {
  2692. ref_get ( &session->refcnt );
  2693. tls->session = session;
  2694. DBGC ( tls, "TLS %p joining session %s\n", tls, name );
  2695. return 0;
  2696. }
  2697. }
  2698. /* Create new session */
  2699. session = zalloc ( sizeof ( *session ) + strlen ( name )
  2700. + 1 /* NUL */ );
  2701. if ( ! session ) {
  2702. rc = -ENOMEM;
  2703. goto err_alloc;
  2704. }
  2705. ref_init ( &session->refcnt, free_tls_session );
  2706. name_copy = ( ( ( void * ) session ) + sizeof ( *session ) );
  2707. strcpy ( name_copy, name );
  2708. session->name = name_copy;
  2709. INIT_LIST_HEAD ( &session->conn );
  2710. list_add ( &session->list, &tls_sessions );
  2711. /* Record session */
  2712. tls->session = session;
  2713. DBGC ( tls, "TLS %p created session %s\n", tls, name );
  2714. return 0;
  2715. ref_put ( &session->refcnt );
  2716. err_alloc:
  2717. return rc;
  2718. }
  2719. /******************************************************************************
  2720. *
  2721. * Instantiator
  2722. *
  2723. ******************************************************************************
  2724. */
  2725. int add_tls ( struct interface *xfer, const char *name,
  2726. struct interface **next ) {
  2727. struct tls_connection *tls;
  2728. int rc;
  2729. /* Allocate and initialise TLS structure */
  2730. tls = malloc ( sizeof ( *tls ) );
  2731. if ( ! tls ) {
  2732. rc = -ENOMEM;
  2733. goto err_alloc;
  2734. }
  2735. memset ( tls, 0, sizeof ( *tls ) );
  2736. ref_init ( &tls->refcnt, free_tls );
  2737. INIT_LIST_HEAD ( &tls->list );
  2738. intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
  2739. intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
  2740. intf_init ( &tls->validator, &tls_validator_desc, &tls->refcnt );
  2741. process_init ( &tls->process, &tls_process_desc, &tls->refcnt );
  2742. tls->version = TLS_VERSION_TLS_1_2;
  2743. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  2744. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  2745. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  2746. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  2747. tls->client_random.gmt_unix_time = time ( NULL );
  2748. iob_populate ( &tls->rx_header_iobuf, &tls->rx_header, 0,
  2749. sizeof ( tls->rx_header ) );
  2750. INIT_LIST_HEAD ( &tls->rx_data );
  2751. if ( ( rc = tls_generate_random ( tls, &tls->client_random.random,
  2752. ( sizeof ( tls->client_random.random ) ) ) ) != 0 ) {
  2753. goto err_random;
  2754. }
  2755. tls->pre_master_secret.version = htons ( tls->version );
  2756. if ( ( rc = tls_generate_random ( tls, &tls->pre_master_secret.random,
  2757. ( sizeof ( tls->pre_master_secret.random ) ) ) ) != 0 ) {
  2758. goto err_random;
  2759. }
  2760. if ( ( rc = tls_session ( tls, name ) ) != 0 )
  2761. goto err_session;
  2762. list_add_tail ( &tls->list, &tls->session->conn );
  2763. /* Start negotiation */
  2764. tls_restart ( tls );
  2765. /* Attach to parent interface, mortalise self, and return */
  2766. intf_plug_plug ( &tls->plainstream, xfer );
  2767. *next = &tls->cipherstream;
  2768. ref_put ( &tls->refcnt );
  2769. return 0;
  2770. err_session:
  2771. err_random:
  2772. ref_put ( &tls->refcnt );
  2773. err_alloc:
  2774. return rc;
  2775. }
  2776. /* Drag in objects via add_tls() */
  2777. REQUIRING_SYMBOL ( add_tls );
  2778. /* Drag in crypto configuration */
  2779. REQUIRE_OBJECT ( config_crypto );