Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

tls.c 71KB

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