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 85KB

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