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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653
  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. free_iob ( iobuf );
  1566. return -EINVAL_NON_DATA;
  1567. }
  1568. /* Determine handler */
  1569. switch ( type ) {
  1570. case TLS_TYPE_CHANGE_CIPHER:
  1571. handler = tls_new_change_cipher;
  1572. break;
  1573. case TLS_TYPE_ALERT:
  1574. handler = tls_new_alert;
  1575. break;
  1576. case TLS_TYPE_HANDSHAKE:
  1577. handler = tls_new_handshake;
  1578. break;
  1579. default:
  1580. /* RFC4346 says that we should just ignore unknown
  1581. * record types.
  1582. */
  1583. handler = NULL;
  1584. DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
  1585. break;
  1586. }
  1587. /* Handle record and free I/O buffer */
  1588. rc = ( handler ? handler ( tls, iobuf->data, iob_len ( iobuf ) ) : 0 );
  1589. free_iob ( iobuf );
  1590. return rc;
  1591. }
  1592. /******************************************************************************
  1593. *
  1594. * Record encryption/decryption
  1595. *
  1596. ******************************************************************************
  1597. */
  1598. /**
  1599. * Initialise HMAC
  1600. *
  1601. * @v cipherspec Cipher specification
  1602. * @v ctx Context
  1603. * @v seq Sequence number
  1604. * @v tlshdr TLS header
  1605. */
  1606. static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
  1607. uint64_t seq, struct tls_header *tlshdr ) {
  1608. struct digest_algorithm *digest = cipherspec->suite->digest;
  1609. hmac_init ( digest, ctx, cipherspec->mac_secret, &digest->digestsize );
  1610. seq = cpu_to_be64 ( seq );
  1611. hmac_update ( digest, ctx, &seq, sizeof ( seq ) );
  1612. hmac_update ( digest, ctx, tlshdr, sizeof ( *tlshdr ) );
  1613. }
  1614. /**
  1615. * Update HMAC
  1616. *
  1617. * @v cipherspec Cipher specification
  1618. * @v ctx Context
  1619. * @v data Data
  1620. * @v len Length of data
  1621. */
  1622. static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
  1623. const void *data, size_t len ) {
  1624. struct digest_algorithm *digest = cipherspec->suite->digest;
  1625. hmac_update ( digest, ctx, data, len );
  1626. }
  1627. /**
  1628. * Finalise HMAC
  1629. *
  1630. * @v cipherspec Cipher specification
  1631. * @v ctx Context
  1632. * @v mac HMAC to fill in
  1633. */
  1634. static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
  1635. void *hmac ) {
  1636. struct digest_algorithm *digest = cipherspec->suite->digest;
  1637. hmac_final ( digest, ctx, cipherspec->mac_secret,
  1638. &digest->digestsize, hmac );
  1639. }
  1640. /**
  1641. * Calculate HMAC
  1642. *
  1643. * @v cipherspec Cipher specification
  1644. * @v seq Sequence number
  1645. * @v tlshdr TLS header
  1646. * @v data Data
  1647. * @v len Length of data
  1648. * @v mac HMAC to fill in
  1649. */
  1650. static void tls_hmac ( struct tls_cipherspec *cipherspec,
  1651. uint64_t seq, struct tls_header *tlshdr,
  1652. const void *data, size_t len, void *hmac ) {
  1653. struct digest_algorithm *digest = cipherspec->suite->digest;
  1654. uint8_t ctx[digest->ctxsize];
  1655. tls_hmac_init ( cipherspec, ctx, seq, tlshdr );
  1656. tls_hmac_update ( cipherspec, ctx, data, len );
  1657. tls_hmac_final ( cipherspec, ctx, hmac );
  1658. }
  1659. /**
  1660. * Allocate and assemble stream-ciphered record from data and MAC portions
  1661. *
  1662. * @v tls TLS session
  1663. * @ret data Data
  1664. * @ret len Length of data
  1665. * @ret digest MAC digest
  1666. * @ret plaintext_len Length of plaintext record
  1667. * @ret plaintext Allocated plaintext record
  1668. */
  1669. static void * __malloc tls_assemble_stream ( struct tls_session *tls,
  1670. const void *data, size_t len,
  1671. void *digest, size_t *plaintext_len ) {
  1672. size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
  1673. void *plaintext;
  1674. void *content;
  1675. void *mac;
  1676. /* Calculate stream-ciphered struct length */
  1677. *plaintext_len = ( len + mac_len );
  1678. /* Allocate stream-ciphered struct */
  1679. plaintext = malloc ( *plaintext_len );
  1680. if ( ! plaintext )
  1681. return NULL;
  1682. content = plaintext;
  1683. mac = ( content + len );
  1684. /* Fill in stream-ciphered struct */
  1685. memcpy ( content, data, len );
  1686. memcpy ( mac, digest, mac_len );
  1687. return plaintext;
  1688. }
  1689. /**
  1690. * Allocate and assemble block-ciphered record from data and MAC portions
  1691. *
  1692. * @v tls TLS session
  1693. * @ret data Data
  1694. * @ret len Length of data
  1695. * @ret digest MAC digest
  1696. * @ret plaintext_len Length of plaintext record
  1697. * @ret plaintext Allocated plaintext record
  1698. */
  1699. static void * tls_assemble_block ( struct tls_session *tls,
  1700. const void *data, size_t len,
  1701. void *digest, size_t *plaintext_len ) {
  1702. size_t blocksize = tls->tx_cipherspec.suite->cipher->blocksize;
  1703. size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
  1704. size_t iv_len;
  1705. size_t padding_len;
  1706. void *plaintext;
  1707. void *iv;
  1708. void *content;
  1709. void *mac;
  1710. void *padding;
  1711. /* TLSv1.1 and later use an explicit IV */
  1712. iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ? blocksize : 0 );
  1713. /* Calculate block-ciphered struct length */
  1714. padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
  1715. *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
  1716. /* Allocate block-ciphered struct */
  1717. plaintext = malloc ( *plaintext_len );
  1718. if ( ! plaintext )
  1719. return NULL;
  1720. iv = plaintext;
  1721. content = ( iv + iv_len );
  1722. mac = ( content + len );
  1723. padding = ( mac + mac_len );
  1724. /* Fill in block-ciphered struct */
  1725. tls_generate_random ( tls, iv, iv_len );
  1726. memcpy ( content, data, len );
  1727. memcpy ( mac, digest, mac_len );
  1728. memset ( padding, padding_len, ( padding_len + 1 ) );
  1729. return plaintext;
  1730. }
  1731. /**
  1732. * Send plaintext record
  1733. *
  1734. * @v tls TLS session
  1735. * @v type Record type
  1736. * @v data Plaintext record
  1737. * @v len Length of plaintext record
  1738. * @ret rc Return status code
  1739. */
  1740. static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
  1741. const void *data, size_t len ) {
  1742. struct tls_header plaintext_tlshdr;
  1743. struct tls_header *tlshdr;
  1744. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
  1745. struct cipher_algorithm *cipher = cipherspec->suite->cipher;
  1746. void *plaintext = NULL;
  1747. size_t plaintext_len;
  1748. struct io_buffer *ciphertext = NULL;
  1749. size_t ciphertext_len;
  1750. size_t mac_len = cipherspec->suite->digest->digestsize;
  1751. uint8_t mac[mac_len];
  1752. int rc;
  1753. /* Construct header */
  1754. plaintext_tlshdr.type = type;
  1755. plaintext_tlshdr.version = htons ( tls->version );
  1756. plaintext_tlshdr.length = htons ( len );
  1757. /* Calculate MAC */
  1758. tls_hmac ( cipherspec, tls->tx_seq, &plaintext_tlshdr, data, len, mac );
  1759. /* Allocate and assemble plaintext struct */
  1760. if ( is_stream_cipher ( cipher ) ) {
  1761. plaintext = tls_assemble_stream ( tls, data, len, mac,
  1762. &plaintext_len );
  1763. } else {
  1764. plaintext = tls_assemble_block ( tls, data, len, mac,
  1765. &plaintext_len );
  1766. }
  1767. if ( ! plaintext ) {
  1768. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1769. "plaintext\n", tls, plaintext_len );
  1770. rc = -ENOMEM_TX_PLAINTEXT;
  1771. goto done;
  1772. }
  1773. DBGC2 ( tls, "Sending plaintext data:\n" );
  1774. DBGC2_HD ( tls, plaintext, plaintext_len );
  1775. /* Allocate ciphertext */
  1776. ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
  1777. ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
  1778. if ( ! ciphertext ) {
  1779. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1780. "ciphertext\n", tls, ciphertext_len );
  1781. rc = -ENOMEM_TX_CIPHERTEXT;
  1782. goto done;
  1783. }
  1784. /* Assemble ciphertext */
  1785. tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
  1786. tlshdr->type = type;
  1787. tlshdr->version = htons ( tls->version );
  1788. tlshdr->length = htons ( plaintext_len );
  1789. memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
  1790. cipher->ctxsize );
  1791. cipher_encrypt ( cipher, cipherspec->cipher_next_ctx, plaintext,
  1792. iob_put ( ciphertext, plaintext_len ), plaintext_len );
  1793. /* Free plaintext as soon as possible to conserve memory */
  1794. free ( plaintext );
  1795. plaintext = NULL;
  1796. /* Send ciphertext */
  1797. if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
  1798. iob_disown ( ciphertext ) ) ) != 0 ) {
  1799. DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
  1800. tls, strerror ( rc ) );
  1801. goto done;
  1802. }
  1803. /* Update TX state machine to next record */
  1804. tls->tx_seq += 1;
  1805. memcpy ( tls->tx_cipherspec.cipher_ctx,
  1806. tls->tx_cipherspec.cipher_next_ctx, cipher->ctxsize );
  1807. done:
  1808. free ( plaintext );
  1809. free_iob ( ciphertext );
  1810. return rc;
  1811. }
  1812. /**
  1813. * Split stream-ciphered record into data and MAC portions
  1814. *
  1815. * @v tls TLS session
  1816. * @v rx_data List of received data buffers
  1817. * @v mac MAC to fill in
  1818. * @ret rc Return status code
  1819. */
  1820. static int tls_split_stream ( struct tls_session *tls,
  1821. struct list_head *rx_data, void **mac ) {
  1822. size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
  1823. struct io_buffer *iobuf;
  1824. /* Extract MAC */
  1825. iobuf = list_last_entry ( rx_data, struct io_buffer, list );
  1826. assert ( iobuf != NULL );
  1827. if ( iob_len ( iobuf ) < mac_len ) {
  1828. DBGC ( tls, "TLS %p received underlength MAC\n", tls );
  1829. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  1830. return -EINVAL_STREAM;
  1831. }
  1832. iob_unput ( iobuf, mac_len );
  1833. *mac = iobuf->tail;
  1834. return 0;
  1835. }
  1836. /**
  1837. * Split block-ciphered record into data and MAC portions
  1838. *
  1839. * @v tls TLS session
  1840. * @v rx_data List of received data buffers
  1841. * @v mac MAC to fill in
  1842. * @ret rc Return status code
  1843. */
  1844. static int tls_split_block ( struct tls_session *tls,
  1845. struct list_head *rx_data, void **mac ) {
  1846. size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
  1847. struct io_buffer *iobuf;
  1848. size_t iv_len;
  1849. uint8_t *padding_final;
  1850. uint8_t *padding;
  1851. size_t padding_len;
  1852. /* TLSv1.1 and later use an explicit IV */
  1853. iobuf = list_first_entry ( rx_data, struct io_buffer, list );
  1854. iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ?
  1855. tls->rx_cipherspec.suite->cipher->blocksize : 0 );
  1856. if ( iob_len ( iobuf ) < iv_len ) {
  1857. DBGC ( tls, "TLS %p received underlength IV\n", tls );
  1858. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  1859. return -EINVAL_BLOCK;
  1860. }
  1861. iob_pull ( iobuf, iv_len );
  1862. /* Extract and verify padding */
  1863. iobuf = list_last_entry ( rx_data, struct io_buffer, list );
  1864. padding_final = ( iobuf->tail - 1 );
  1865. padding_len = *padding_final;
  1866. if ( ( padding_len + 1 ) > iob_len ( iobuf ) ) {
  1867. DBGC ( tls, "TLS %p received underlength padding\n", tls );
  1868. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  1869. return -EINVAL_BLOCK;
  1870. }
  1871. iob_unput ( iobuf, ( padding_len + 1 ) );
  1872. for ( padding = iobuf->tail ; padding < padding_final ; padding++ ) {
  1873. if ( *padding != padding_len ) {
  1874. DBGC ( tls, "TLS %p received bad padding\n", tls );
  1875. DBGC_HD ( tls, padding, padding_len );
  1876. return -EINVAL_PADDING;
  1877. }
  1878. }
  1879. /* Extract MAC */
  1880. if ( iob_len ( iobuf ) < mac_len ) {
  1881. DBGC ( tls, "TLS %p received underlength MAC\n", tls );
  1882. DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  1883. return -EINVAL_BLOCK;
  1884. }
  1885. iob_unput ( iobuf, mac_len );
  1886. *mac = iobuf->tail;
  1887. return 0;
  1888. }
  1889. /**
  1890. * Receive new ciphertext record
  1891. *
  1892. * @v tls TLS session
  1893. * @v tlshdr Record header
  1894. * @v rx_data List of received data buffers
  1895. * @ret rc Return status code
  1896. */
  1897. static int tls_new_ciphertext ( struct tls_session *tls,
  1898. struct tls_header *tlshdr,
  1899. struct list_head *rx_data ) {
  1900. struct tls_header plaintext_tlshdr;
  1901. struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
  1902. struct cipher_algorithm *cipher = cipherspec->suite->cipher;
  1903. struct digest_algorithm *digest = cipherspec->suite->digest;
  1904. uint8_t ctx[digest->ctxsize];
  1905. uint8_t verify_mac[digest->digestsize];
  1906. struct io_buffer *iobuf;
  1907. void *mac;
  1908. size_t len = 0;
  1909. int rc;
  1910. /* Decrypt the received data */
  1911. list_for_each_entry ( iobuf, &tls->rx_data, list ) {
  1912. cipher_decrypt ( cipher, cipherspec->cipher_ctx,
  1913. iobuf->data, iobuf->data, iob_len ( iobuf ) );
  1914. }
  1915. /* Split record into content and MAC */
  1916. if ( is_stream_cipher ( cipher ) ) {
  1917. if ( ( rc = tls_split_stream ( tls, rx_data, &mac ) ) != 0 )
  1918. return rc;
  1919. } else {
  1920. if ( ( rc = tls_split_block ( tls, rx_data, &mac ) ) != 0 )
  1921. return rc;
  1922. }
  1923. /* Calculate total length */
  1924. DBGC2 ( tls, "Received plaintext data:\n" );
  1925. list_for_each_entry ( iobuf, rx_data, list ) {
  1926. DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
  1927. len += iob_len ( iobuf );
  1928. }
  1929. /* Verify MAC */
  1930. plaintext_tlshdr.type = tlshdr->type;
  1931. plaintext_tlshdr.version = tlshdr->version;
  1932. plaintext_tlshdr.length = htons ( len );
  1933. tls_hmac_init ( cipherspec, ctx, tls->rx_seq, &plaintext_tlshdr );
  1934. list_for_each_entry ( iobuf, rx_data, list ) {
  1935. tls_hmac_update ( cipherspec, ctx, iobuf->data,
  1936. iob_len ( iobuf ) );
  1937. }
  1938. tls_hmac_final ( cipherspec, ctx, verify_mac );
  1939. if ( memcmp ( mac, verify_mac, sizeof ( verify_mac ) ) != 0 ) {
  1940. DBGC ( tls, "TLS %p failed MAC verification\n", tls );
  1941. return -EINVAL_MAC;
  1942. }
  1943. /* Process plaintext record */
  1944. if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
  1945. return rc;
  1946. return 0;
  1947. }
  1948. /******************************************************************************
  1949. *
  1950. * Plaintext stream operations
  1951. *
  1952. ******************************************************************************
  1953. */
  1954. /**
  1955. * Check flow control window
  1956. *
  1957. * @v tls TLS session
  1958. * @ret len Length of window
  1959. */
  1960. static size_t tls_plainstream_window ( struct tls_session *tls ) {
  1961. /* Block window unless we are ready to accept data */
  1962. if ( ! tls_ready ( tls ) )
  1963. return 0;
  1964. return xfer_window ( &tls->cipherstream );
  1965. }
  1966. /**
  1967. * Deliver datagram as raw data
  1968. *
  1969. * @v tls TLS session
  1970. * @v iobuf I/O buffer
  1971. * @v meta Data transfer metadata
  1972. * @ret rc Return status code
  1973. */
  1974. static int tls_plainstream_deliver ( struct tls_session *tls,
  1975. struct io_buffer *iobuf,
  1976. struct xfer_metadata *meta __unused ) {
  1977. int rc;
  1978. /* Refuse unless we are ready to accept data */
  1979. if ( ! tls_ready ( tls ) ) {
  1980. rc = -ENOTCONN;
  1981. goto done;
  1982. }
  1983. if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
  1984. iob_len ( iobuf ) ) ) != 0 )
  1985. goto done;
  1986. done:
  1987. free_iob ( iobuf );
  1988. return rc;
  1989. }
  1990. /** TLS plaintext stream interface operations */
  1991. static struct interface_operation tls_plainstream_ops[] = {
  1992. INTF_OP ( xfer_deliver, struct tls_session *, tls_plainstream_deliver ),
  1993. INTF_OP ( xfer_window, struct tls_session *, tls_plainstream_window ),
  1994. INTF_OP ( intf_close, struct tls_session *, tls_close ),
  1995. };
  1996. /** TLS plaintext stream interface descriptor */
  1997. static struct interface_descriptor tls_plainstream_desc =
  1998. INTF_DESC_PASSTHRU ( struct tls_session, plainstream,
  1999. tls_plainstream_ops, cipherstream );
  2000. /******************************************************************************
  2001. *
  2002. * Ciphertext stream operations
  2003. *
  2004. ******************************************************************************
  2005. */
  2006. /**
  2007. * Handle received TLS header
  2008. *
  2009. * @v tls TLS session
  2010. * @ret rc Returned status code
  2011. */
  2012. static int tls_newdata_process_header ( struct tls_session *tls ) {
  2013. size_t data_len = ntohs ( tls->rx_header.length );
  2014. size_t remaining = data_len;
  2015. size_t frag_len;
  2016. struct io_buffer *iobuf;
  2017. struct io_buffer *tmp;
  2018. int rc;
  2019. /* Allocate data buffers now that we know the length */
  2020. assert ( list_empty ( &tls->rx_data ) );
  2021. while ( remaining ) {
  2022. /* Calculate fragment length. Ensure that no block is
  2023. * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
  2024. * allocation length if necessary).
  2025. */
  2026. frag_len = remaining;
  2027. if ( frag_len > TLS_RX_BUFSIZE )
  2028. frag_len = TLS_RX_BUFSIZE;
  2029. remaining -= frag_len;
  2030. if ( remaining < TLS_RX_MIN_BUFSIZE ) {
  2031. frag_len += remaining;
  2032. remaining = 0;
  2033. }
  2034. /* Allocate buffer */
  2035. iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
  2036. if ( ! iobuf ) {
  2037. DBGC ( tls, "TLS %p could not allocate %zd of %zd "
  2038. "bytes for receive buffer\n", tls,
  2039. remaining, data_len );
  2040. rc = -ENOMEM_RX_DATA;
  2041. goto err;
  2042. }
  2043. /* Ensure tailroom is exactly what we asked for. This
  2044. * will result in unaligned I/O buffers when the
  2045. * fragment length is unaligned, which can happen only
  2046. * before we switch to using a block cipher.
  2047. */
  2048. iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
  2049. /* Add I/O buffer to list */
  2050. list_add_tail ( &iobuf->list, &tls->rx_data );
  2051. }
  2052. /* Move to data state */
  2053. tls->rx_state = TLS_RX_DATA;
  2054. return 0;
  2055. err:
  2056. list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
  2057. list_del ( &iobuf->list );
  2058. free_iob ( iobuf );
  2059. }
  2060. return rc;
  2061. }
  2062. /**
  2063. * Handle received TLS data payload
  2064. *
  2065. * @v tls TLS session
  2066. * @ret rc Returned status code
  2067. */
  2068. static int tls_newdata_process_data ( struct tls_session *tls ) {
  2069. struct io_buffer *iobuf;
  2070. int rc;
  2071. /* Move current buffer to end of list */
  2072. iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
  2073. list_del ( &iobuf->list );
  2074. list_add_tail ( &iobuf->list, &tls->rx_data );
  2075. /* Continue receiving data if any space remains */
  2076. iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
  2077. if ( iob_tailroom ( iobuf ) )
  2078. return 0;
  2079. /* Process record */
  2080. if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
  2081. &tls->rx_data ) ) != 0 )
  2082. return rc;
  2083. /* Increment RX sequence number */
  2084. tls->rx_seq += 1;
  2085. /* Return to header state */
  2086. assert ( list_empty ( &tls->rx_data ) );
  2087. tls->rx_state = TLS_RX_HEADER;
  2088. iob_unput ( &tls->rx_header_iobuf, sizeof ( tls->rx_header ) );
  2089. return 0;
  2090. }
  2091. /**
  2092. * Receive new ciphertext
  2093. *
  2094. * @v tls TLS session
  2095. * @v iobuf I/O buffer
  2096. * @v meta Data transfer metadat
  2097. * @ret rc Return status code
  2098. */
  2099. static int tls_cipherstream_deliver ( struct tls_session *tls,
  2100. struct io_buffer *iobuf,
  2101. struct xfer_metadata *xfer __unused ) {
  2102. size_t frag_len;
  2103. int ( * process ) ( struct tls_session *tls );
  2104. struct io_buffer *dest;
  2105. int rc;
  2106. while ( iob_len ( iobuf ) ) {
  2107. /* Select buffer according to current state */
  2108. switch ( tls->rx_state ) {
  2109. case TLS_RX_HEADER:
  2110. dest = &tls->rx_header_iobuf;
  2111. process = tls_newdata_process_header;
  2112. break;
  2113. case TLS_RX_DATA:
  2114. dest = list_first_entry ( &tls->rx_data,
  2115. struct io_buffer, list );
  2116. assert ( dest != NULL );
  2117. process = tls_newdata_process_data;
  2118. break;
  2119. default:
  2120. assert ( 0 );
  2121. rc = -EINVAL_RX_STATE;
  2122. goto done;
  2123. }
  2124. /* Copy data portion to buffer */
  2125. frag_len = iob_len ( iobuf );
  2126. if ( frag_len > iob_tailroom ( dest ) )
  2127. frag_len = iob_tailroom ( dest );
  2128. memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
  2129. iob_pull ( iobuf, frag_len );
  2130. /* Process data if buffer is now full */
  2131. if ( iob_tailroom ( dest ) == 0 ) {
  2132. if ( ( rc = process ( tls ) ) != 0 ) {
  2133. tls_close ( tls, rc );
  2134. goto done;
  2135. }
  2136. }
  2137. }
  2138. rc = 0;
  2139. done:
  2140. free_iob ( iobuf );
  2141. return rc;
  2142. }
  2143. /** TLS ciphertext stream interface operations */
  2144. static struct interface_operation tls_cipherstream_ops[] = {
  2145. INTF_OP ( xfer_deliver, struct tls_session *,
  2146. tls_cipherstream_deliver ),
  2147. INTF_OP ( xfer_window_changed, struct tls_session *, tls_tx_resume ),
  2148. INTF_OP ( intf_close, struct tls_session *, tls_close ),
  2149. };
  2150. /** TLS ciphertext stream interface descriptor */
  2151. static struct interface_descriptor tls_cipherstream_desc =
  2152. INTF_DESC_PASSTHRU ( struct tls_session, cipherstream,
  2153. tls_cipherstream_ops, plainstream );
  2154. /******************************************************************************
  2155. *
  2156. * Certificate validator
  2157. *
  2158. ******************************************************************************
  2159. */
  2160. /**
  2161. * Handle certificate validation completion
  2162. *
  2163. * @v tls TLS session
  2164. * @v rc Reason for completion
  2165. */
  2166. static void tls_validator_done ( struct tls_session *tls, int rc ) {
  2167. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
  2168. struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
  2169. struct x509_certificate *cert;
  2170. /* Close validator interface */
  2171. intf_restart ( &tls->validator, rc );
  2172. /* Check for validation failure */
  2173. if ( rc != 0 ) {
  2174. DBGC ( tls, "TLS %p certificate validation failed: %s\n",
  2175. tls, strerror ( rc ) );
  2176. goto err;
  2177. }
  2178. DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
  2179. /* Extract first certificate */
  2180. cert = x509_first ( tls->chain );
  2181. assert ( cert != NULL );
  2182. /* Verify server name */
  2183. if ( ( cert->subject.name == NULL ) ||
  2184. ( strcmp ( cert->subject.name, tls->name ) != 0 ) ) {
  2185. DBGC ( tls, "TLS %p server name incorrect (expected %s, got "
  2186. "%s)\n", tls, tls->name, cert->subject.name );
  2187. rc = -EACCES_WRONG_NAME;
  2188. goto err;
  2189. }
  2190. /* Initialise public key algorithm */
  2191. if ( ( rc = pubkey_init ( pubkey, cipherspec->pubkey_ctx,
  2192. cert->subject.public_key.raw.data,
  2193. cert->subject.public_key.raw.len ) ) != 0 ) {
  2194. DBGC ( tls, "TLS %p cannot initialise public key: %s\n",
  2195. tls, strerror ( rc ) );
  2196. goto err;
  2197. }
  2198. /* Schedule Client Key Exchange, Change Cipher, and Finished */
  2199. tls->tx_pending |= ( TLS_TX_CLIENT_KEY_EXCHANGE |
  2200. TLS_TX_CHANGE_CIPHER |
  2201. TLS_TX_FINISHED );
  2202. tls_tx_resume ( tls );
  2203. return;
  2204. err:
  2205. tls_close ( tls, rc );
  2206. return;
  2207. }
  2208. /** TLS certificate validator interface operations */
  2209. static struct interface_operation tls_validator_ops[] = {
  2210. INTF_OP ( intf_close, struct tls_session *, tls_validator_done ),
  2211. };
  2212. /** TLS certificate validator interface descriptor */
  2213. static struct interface_descriptor tls_validator_desc =
  2214. INTF_DESC ( struct tls_session, validator, tls_validator_ops );
  2215. /******************************************************************************
  2216. *
  2217. * Controlling process
  2218. *
  2219. ******************************************************************************
  2220. */
  2221. /**
  2222. * TLS TX state machine
  2223. *
  2224. * @v tls TLS session
  2225. */
  2226. static void tls_tx_step ( struct tls_session *tls ) {
  2227. int rc;
  2228. /* Wait for cipherstream to become ready */
  2229. if ( ! xfer_window ( &tls->cipherstream ) )
  2230. return;
  2231. /* Send first pending transmission */
  2232. if ( tls->tx_pending & TLS_TX_CLIENT_HELLO ) {
  2233. /* Send Client Hello */
  2234. if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
  2235. DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
  2236. tls, strerror ( rc ) );
  2237. goto err;
  2238. }
  2239. tls->tx_pending &= ~TLS_TX_CLIENT_HELLO;
  2240. } else if ( tls->tx_pending & TLS_TX_CERTIFICATE ) {
  2241. /* Send Certificate */
  2242. if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
  2243. DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
  2244. tls, strerror ( rc ) );
  2245. goto err;
  2246. }
  2247. tls->tx_pending &= ~TLS_TX_CERTIFICATE;
  2248. } else if ( tls->tx_pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
  2249. /* Send Client Key Exchange */
  2250. if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
  2251. DBGC ( tls, "TLS %p could not send Client Key "
  2252. "Exchange: %s\n", tls, strerror ( rc ) );
  2253. goto err;
  2254. }
  2255. tls->tx_pending &= ~TLS_TX_CLIENT_KEY_EXCHANGE;
  2256. } else if ( tls->tx_pending & TLS_TX_CERTIFICATE_VERIFY ) {
  2257. /* Send Certificate Verify */
  2258. if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
  2259. DBGC ( tls, "TLS %p could not send Certificate "
  2260. "Verify: %s\n", tls, strerror ( rc ) );
  2261. goto err;
  2262. }
  2263. tls->tx_pending &= ~TLS_TX_CERTIFICATE_VERIFY;
  2264. } else if ( tls->tx_pending & TLS_TX_CHANGE_CIPHER ) {
  2265. /* Send Change Cipher, and then change the cipher in use */
  2266. if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
  2267. DBGC ( tls, "TLS %p could not send Change Cipher: "
  2268. "%s\n", tls, strerror ( rc ) );
  2269. goto err;
  2270. }
  2271. if ( ( rc = tls_change_cipher ( tls,
  2272. &tls->tx_cipherspec_pending,
  2273. &tls->tx_cipherspec )) != 0 ){
  2274. DBGC ( tls, "TLS %p could not activate TX cipher: "
  2275. "%s\n", tls, strerror ( rc ) );
  2276. goto err;
  2277. }
  2278. tls->tx_seq = 0;
  2279. tls->tx_pending &= ~TLS_TX_CHANGE_CIPHER;
  2280. } else if ( tls->tx_pending & TLS_TX_FINISHED ) {
  2281. /* Send Finished */
  2282. if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
  2283. DBGC ( tls, "TLS %p could not send Finished: %s\n",
  2284. tls, strerror ( rc ) );
  2285. goto err;
  2286. }
  2287. tls->tx_pending &= ~TLS_TX_FINISHED;
  2288. }
  2289. /* Reschedule process if pending transmissions remain */
  2290. if ( tls->tx_pending )
  2291. tls_tx_resume ( tls );
  2292. return;
  2293. err:
  2294. tls_close ( tls, rc );
  2295. }
  2296. /** TLS TX process descriptor */
  2297. static struct process_descriptor tls_process_desc =
  2298. PROC_DESC_ONCE ( struct tls_session, process, tls_tx_step );
  2299. /******************************************************************************
  2300. *
  2301. * Instantiator
  2302. *
  2303. ******************************************************************************
  2304. */
  2305. int add_tls ( struct interface *xfer, const char *name,
  2306. struct interface **next ) {
  2307. struct tls_session *tls;
  2308. int rc;
  2309. /* Allocate and initialise TLS structure */
  2310. tls = malloc ( sizeof ( *tls ) );
  2311. if ( ! tls ) {
  2312. rc = -ENOMEM;
  2313. goto err_alloc;
  2314. }
  2315. memset ( tls, 0, sizeof ( *tls ) );
  2316. ref_init ( &tls->refcnt, free_tls );
  2317. tls->name = name;
  2318. intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
  2319. intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
  2320. intf_init ( &tls->validator, &tls_validator_desc, &tls->refcnt );
  2321. process_init ( &tls->process, &tls_process_desc, &tls->refcnt );
  2322. tls->version = TLS_VERSION_TLS_1_2;
  2323. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  2324. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  2325. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  2326. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  2327. tls->client_random.gmt_unix_time = time ( NULL );
  2328. if ( ( rc = tls_generate_random ( tls, &tls->client_random.random,
  2329. ( sizeof ( tls->client_random.random ) ) ) ) != 0 ) {
  2330. goto err_random;
  2331. }
  2332. tls->pre_master_secret.version = htons ( tls->version );
  2333. if ( ( rc = tls_generate_random ( tls, &tls->pre_master_secret.random,
  2334. ( sizeof ( tls->pre_master_secret.random ) ) ) ) != 0 ) {
  2335. goto err_random;
  2336. }
  2337. digest_init ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx );
  2338. digest_init ( &sha256_algorithm, tls->handshake_sha256_ctx );
  2339. tls->handshake_digest = &sha256_algorithm;
  2340. tls->handshake_ctx = tls->handshake_sha256_ctx;
  2341. tls->tx_pending = TLS_TX_CLIENT_HELLO;
  2342. iob_populate ( &tls->rx_header_iobuf, &tls->rx_header, 0,
  2343. sizeof ( tls->rx_header ) );
  2344. INIT_LIST_HEAD ( &tls->rx_data );
  2345. /* Add pending operations for server and client Finished messages */
  2346. pending_get ( &tls->client_negotiation );
  2347. pending_get ( &tls->server_negotiation );
  2348. /* Attach to parent interface, mortalise self, and return */
  2349. intf_plug_plug ( &tls->plainstream, xfer );
  2350. *next = &tls->cipherstream;
  2351. ref_put ( &tls->refcnt );
  2352. return 0;
  2353. err_random:
  2354. ref_put ( &tls->refcnt );
  2355. err_alloc:
  2356. return rc;
  2357. }