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

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