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

tls.c 89KB

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