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

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