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

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