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 63KB

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