Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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