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

tls.c 75KB

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