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

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