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

tls.c 74KB

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