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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757
  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. /**
  19. * @file
  20. *
  21. * Transport Layer Security Protocol
  22. */
  23. #include <stdint.h>
  24. #include <stdlib.h>
  25. #include <stdarg.h>
  26. #include <string.h>
  27. #include <errno.h>
  28. #include <byteswap.h>
  29. #include <gpxe/hmac.h>
  30. #include <gpxe/md5.h>
  31. #include <gpxe/sha1.h>
  32. #include <gpxe/aes.h>
  33. #include <gpxe/rsa.h>
  34. #include <gpxe/xfer.h>
  35. #include <gpxe/open.h>
  36. #include <gpxe/filter.h>
  37. #include <gpxe/asn1.h>
  38. #include <gpxe/x509.h>
  39. #include <gpxe/tls.h>
  40. static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
  41. const void *data, size_t len );
  42. static void tls_clear_cipher ( struct tls_session *tls,
  43. struct tls_cipherspec *cipherspec );
  44. /******************************************************************************
  45. *
  46. * Utility functions
  47. *
  48. ******************************************************************************
  49. */
  50. /**
  51. * Extract 24-bit field value
  52. *
  53. * @v field24 24-bit field
  54. * @ret value Field value
  55. *
  56. * TLS uses 24-bit integers in several places, which are awkward to
  57. * parse in C.
  58. */
  59. static unsigned long tls_uint24 ( uint8_t field24[3] ) {
  60. return ( ( field24[0] << 16 ) + ( field24[1] << 8 ) + field24[2] );
  61. }
  62. /******************************************************************************
  63. *
  64. * Cleanup functions
  65. *
  66. ******************************************************************************
  67. */
  68. /**
  69. * Free TLS session
  70. *
  71. * @v refcnt Reference counter
  72. */
  73. static void free_tls ( struct refcnt *refcnt ) {
  74. struct tls_session *tls =
  75. container_of ( refcnt, struct tls_session, refcnt );
  76. /* Free dynamically-allocated resources */
  77. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  78. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  79. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  80. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  81. x509_free_rsa_public_key ( &tls->rsa );
  82. free ( tls->rx_data );
  83. /* Free TLS structure itself */
  84. free ( tls );
  85. }
  86. /**
  87. * Finish with TLS session
  88. *
  89. * @v tls TLS session
  90. * @v rc Status code
  91. */
  92. static void tls_close ( struct tls_session *tls, int rc ) {
  93. /* Remove process */
  94. process_del ( &tls->process );
  95. /* Close ciphertext and plaintext streams */
  96. xfer_nullify ( &tls->cipherstream.xfer );
  97. xfer_close ( &tls->cipherstream.xfer, rc );
  98. xfer_nullify ( &tls->plainstream.xfer );
  99. xfer_close ( &tls->plainstream.xfer, rc );
  100. }
  101. /******************************************************************************
  102. *
  103. * Random number generation
  104. *
  105. ******************************************************************************
  106. */
  107. /**
  108. * Generate random data
  109. *
  110. * @v data Buffer to fill
  111. * @v len Length of buffer
  112. */
  113. static void tls_generate_random ( void *data, size_t len ) {
  114. /* FIXME: Some real random data source would be nice... */
  115. memset ( data, 0x01, len );
  116. }
  117. /**
  118. * Update HMAC with a list of ( data, len ) pairs
  119. *
  120. * @v digest Hash function to use
  121. * @v digest_ctx Digest context
  122. * @v args ( data, len ) pairs of data, terminated by NULL
  123. */
  124. static void tls_hmac_update_va ( struct digest_algorithm *digest,
  125. void *digest_ctx, va_list args ) {
  126. void *data;
  127. size_t len;
  128. while ( ( data = va_arg ( args, void * ) ) ) {
  129. len = va_arg ( args, size_t );
  130. hmac_update ( digest, digest_ctx, data, len );
  131. }
  132. }
  133. /**
  134. * Generate secure pseudo-random data using a single hash function
  135. *
  136. * @v tls TLS session
  137. * @v digest Hash function to use
  138. * @v secret Secret
  139. * @v secret_len Length of secret
  140. * @v out Output buffer
  141. * @v out_len Length of output buffer
  142. * @v seeds ( data, len ) pairs of seed data, terminated by NULL
  143. */
  144. static void tls_p_hash_va ( struct tls_session *tls,
  145. struct digest_algorithm *digest,
  146. void *secret, size_t secret_len,
  147. void *out, size_t out_len,
  148. va_list seeds ) {
  149. uint8_t secret_copy[secret_len];
  150. uint8_t digest_ctx[digest->ctxsize];
  151. uint8_t digest_ctx_partial[digest->ctxsize];
  152. uint8_t a[digest->digestsize];
  153. uint8_t out_tmp[digest->digestsize];
  154. size_t frag_len = digest->digestsize;
  155. va_list tmp;
  156. /* Copy the secret, in case HMAC modifies it */
  157. memcpy ( secret_copy, secret, secret_len );
  158. secret = secret_copy;
  159. DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
  160. DBGC2_HD ( tls, secret, secret_len );
  161. /* Calculate A(1) */
  162. hmac_init ( digest, digest_ctx, secret, &secret_len );
  163. va_copy ( tmp, seeds );
  164. tls_hmac_update_va ( digest, digest_ctx, tmp );
  165. va_end ( tmp );
  166. hmac_final ( digest, digest_ctx, secret, &secret_len, a );
  167. DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
  168. DBGC2_HD ( tls, &a, sizeof ( a ) );
  169. /* Generate as much data as required */
  170. while ( out_len ) {
  171. /* Calculate output portion */
  172. hmac_init ( digest, digest_ctx, secret, &secret_len );
  173. hmac_update ( digest, digest_ctx, a, sizeof ( a ) );
  174. memcpy ( digest_ctx_partial, digest_ctx, digest->ctxsize );
  175. va_copy ( tmp, seeds );
  176. tls_hmac_update_va ( digest, digest_ctx, tmp );
  177. va_end ( tmp );
  178. hmac_final ( digest, digest_ctx,
  179. secret, &secret_len, out_tmp );
  180. /* Copy output */
  181. if ( frag_len > out_len )
  182. frag_len = out_len;
  183. memcpy ( out, out_tmp, frag_len );
  184. DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
  185. DBGC2_HD ( tls, out, frag_len );
  186. /* Calculate A(i) */
  187. hmac_final ( digest, digest_ctx_partial,
  188. secret, &secret_len, a );
  189. DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
  190. DBGC2_HD ( tls, &a, sizeof ( a ) );
  191. out += frag_len;
  192. out_len -= frag_len;
  193. }
  194. }
  195. /**
  196. * Generate secure pseudo-random data
  197. *
  198. * @v tls TLS session
  199. * @v secret Secret
  200. * @v secret_len Length of secret
  201. * @v out Output buffer
  202. * @v out_len Length of output buffer
  203. * @v ... ( data, len ) pairs of seed data, terminated by NULL
  204. */
  205. static void tls_prf ( struct tls_session *tls, void *secret, size_t secret_len,
  206. void *out, size_t out_len, ... ) {
  207. va_list seeds;
  208. va_list tmp;
  209. size_t subsecret_len;
  210. void *md5_secret;
  211. void *sha1_secret;
  212. uint8_t out_md5[out_len];
  213. uint8_t out_sha1[out_len];
  214. unsigned int i;
  215. va_start ( seeds, out_len );
  216. /* Split secret into two, with an overlap of up to one byte */
  217. subsecret_len = ( ( secret_len + 1 ) / 2 );
  218. md5_secret = secret;
  219. sha1_secret = ( secret + secret_len - subsecret_len );
  220. /* Calculate MD5 portion */
  221. va_copy ( tmp, seeds );
  222. tls_p_hash_va ( tls, &md5_algorithm, md5_secret, subsecret_len,
  223. out_md5, out_len, seeds );
  224. va_end ( tmp );
  225. /* Calculate SHA1 portion */
  226. va_copy ( tmp, seeds );
  227. tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret, subsecret_len,
  228. out_sha1, out_len, seeds );
  229. va_end ( tmp );
  230. /* XOR the two portions together into the final output buffer */
  231. for ( i = 0 ; i < out_len ; i++ ) {
  232. *( ( uint8_t * ) out + i ) = ( out_md5[i] ^ out_sha1[i] );
  233. }
  234. va_end ( seeds );
  235. }
  236. /**
  237. * Generate secure pseudo-random data
  238. *
  239. * @v secret Secret
  240. * @v secret_len Length of secret
  241. * @v out Output buffer
  242. * @v out_len Length of output buffer
  243. * @v label String literal label
  244. * @v ... ( data, len ) pairs of seed data
  245. */
  246. #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
  247. tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
  248. label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
  249. /******************************************************************************
  250. *
  251. * Secret management
  252. *
  253. ******************************************************************************
  254. */
  255. /**
  256. * Generate master secret
  257. *
  258. * @v tls TLS session
  259. *
  260. * The pre-master secret and the client and server random values must
  261. * already be known.
  262. */
  263. static void tls_generate_master_secret ( struct tls_session *tls ) {
  264. DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
  265. DBGC_HD ( tls, &tls->pre_master_secret,
  266. sizeof ( tls->pre_master_secret ) );
  267. DBGC ( tls, "TLS %p client random bytes:\n", tls );
  268. DBGC_HD ( tls, &tls->client_random, sizeof ( tls->client_random ) );
  269. DBGC ( tls, "TLS %p server random bytes:\n", tls );
  270. DBGC_HD ( tls, &tls->server_random, sizeof ( tls->server_random ) );
  271. tls_prf_label ( tls, &tls->pre_master_secret,
  272. sizeof ( tls->pre_master_secret ),
  273. &tls->master_secret, sizeof ( tls->master_secret ),
  274. "master secret",
  275. &tls->client_random, sizeof ( tls->client_random ),
  276. &tls->server_random, sizeof ( tls->server_random ) );
  277. DBGC ( tls, "TLS %p generated master secret:\n", tls );
  278. DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
  279. }
  280. /**
  281. * Generate key material
  282. *
  283. * @v tls TLS session
  284. *
  285. * The master secret must already be known.
  286. */
  287. static int tls_generate_keys ( struct tls_session *tls ) {
  288. struct tls_cipherspec *tx_cipherspec = &tls->tx_cipherspec_pending;
  289. struct tls_cipherspec *rx_cipherspec = &tls->rx_cipherspec_pending;
  290. size_t hash_size = tx_cipherspec->digest->digestsize;
  291. size_t key_size = tx_cipherspec->key_len;
  292. size_t iv_size = tx_cipherspec->cipher->blocksize;
  293. size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
  294. uint8_t key_block[total];
  295. uint8_t *key;
  296. int rc;
  297. /* Generate key block */
  298. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  299. key_block, sizeof ( key_block ), "key expansion",
  300. &tls->server_random, sizeof ( tls->server_random ),
  301. &tls->client_random, sizeof ( tls->client_random ) );
  302. /* Split key block into portions */
  303. key = key_block;
  304. /* TX MAC secret */
  305. memcpy ( tx_cipherspec->mac_secret, key, hash_size );
  306. DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
  307. DBGC_HD ( tls, key, hash_size );
  308. key += hash_size;
  309. /* RX MAC secret */
  310. memcpy ( rx_cipherspec->mac_secret, key, hash_size );
  311. DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
  312. DBGC_HD ( tls, key, hash_size );
  313. key += hash_size;
  314. /* TX key */
  315. if ( ( rc = cipher_setkey ( tx_cipherspec->cipher,
  316. tx_cipherspec->cipher_ctx,
  317. key, key_size ) ) != 0 ) {
  318. DBGC ( tls, "TLS %p could not set TX key: %s\n",
  319. tls, strerror ( rc ) );
  320. return rc;
  321. }
  322. DBGC ( tls, "TLS %p TX key:\n", tls );
  323. DBGC_HD ( tls, key, key_size );
  324. key += key_size;
  325. /* RX key */
  326. if ( ( rc = cipher_setkey ( rx_cipherspec->cipher,
  327. rx_cipherspec->cipher_ctx,
  328. key, key_size ) ) != 0 ) {
  329. DBGC ( tls, "TLS %p could not set TX key: %s\n",
  330. tls, strerror ( rc ) );
  331. return rc;
  332. }
  333. DBGC ( tls, "TLS %p RX key:\n", tls );
  334. DBGC_HD ( tls, key, key_size );
  335. key += key_size;
  336. /* TX initialisation vector */
  337. cipher_setiv ( tx_cipherspec->cipher, tx_cipherspec->cipher_ctx, key );
  338. DBGC ( tls, "TLS %p TX IV:\n", tls );
  339. DBGC_HD ( tls, key, iv_size );
  340. key += iv_size;
  341. /* RX initialisation vector */
  342. cipher_setiv ( rx_cipherspec->cipher, rx_cipherspec->cipher_ctx, key );
  343. DBGC ( tls, "TLS %p RX IV:\n", tls );
  344. DBGC_HD ( tls, key, iv_size );
  345. key += iv_size;
  346. assert ( ( key_block + total ) == key );
  347. return 0;
  348. }
  349. /******************************************************************************
  350. *
  351. * Cipher suite management
  352. *
  353. ******************************************************************************
  354. */
  355. /**
  356. * Clear cipher suite
  357. *
  358. * @v cipherspec TLS cipher specification
  359. */
  360. static void tls_clear_cipher ( struct tls_session *tls __unused,
  361. struct tls_cipherspec *cipherspec ) {
  362. free ( cipherspec->dynamic );
  363. memset ( cipherspec, 0, sizeof ( cipherspec ) );
  364. cipherspec->pubkey = &pubkey_null;
  365. cipherspec->cipher = &cipher_null;
  366. cipherspec->digest = &digest_null;
  367. }
  368. /**
  369. * Set cipher suite
  370. *
  371. * @v tls TLS session
  372. * @v cipherspec TLS cipher specification
  373. * @v pubkey Public-key encryption elgorithm
  374. * @v cipher Bulk encryption cipher algorithm
  375. * @v digest MAC digest algorithm
  376. * @v key_len Key length
  377. * @ret rc Return status code
  378. */
  379. static int tls_set_cipher ( struct tls_session *tls,
  380. struct tls_cipherspec *cipherspec,
  381. struct pubkey_algorithm *pubkey,
  382. struct cipher_algorithm *cipher,
  383. struct digest_algorithm *digest,
  384. size_t key_len ) {
  385. size_t total;
  386. void *dynamic;
  387. /* Clear out old cipher contents, if any */
  388. tls_clear_cipher ( tls, cipherspec );
  389. /* Allocate dynamic storage */
  390. total = ( pubkey->ctxsize + 2 * cipher->ctxsize + digest->digestsize );
  391. dynamic = malloc ( total );
  392. if ( ! dynamic ) {
  393. DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
  394. "context\n", tls, total );
  395. return -ENOMEM;
  396. }
  397. memset ( dynamic, 0, total );
  398. /* Assign storage */
  399. cipherspec->dynamic = dynamic;
  400. cipherspec->pubkey_ctx = dynamic; dynamic += pubkey->ctxsize;
  401. cipherspec->cipher_ctx = dynamic; dynamic += cipher->ctxsize;
  402. cipherspec->cipher_next_ctx = dynamic; dynamic += cipher->ctxsize;
  403. cipherspec->mac_secret = dynamic; dynamic += digest->digestsize;
  404. assert ( ( cipherspec->dynamic + total ) == dynamic );
  405. /* Store parameters */
  406. cipherspec->pubkey = pubkey;
  407. cipherspec->cipher = cipher;
  408. cipherspec->digest = digest;
  409. cipherspec->key_len = key_len;
  410. return 0;
  411. }
  412. /**
  413. * Select next cipher suite
  414. *
  415. * @v tls TLS session
  416. * @v cipher_suite Cipher suite specification
  417. * @ret rc Return status code
  418. */
  419. static int tls_select_cipher ( struct tls_session *tls,
  420. unsigned int cipher_suite ) {
  421. struct pubkey_algorithm *pubkey = &pubkey_null;
  422. struct cipher_algorithm *cipher = &cipher_null;
  423. struct digest_algorithm *digest = &digest_null;
  424. unsigned int key_len = 0;
  425. int rc;
  426. switch ( cipher_suite ) {
  427. case htons ( TLS_RSA_WITH_AES_128_CBC_SHA ):
  428. key_len = ( 128 / 8 );
  429. cipher = &aes_cbc_algorithm;
  430. digest = &sha1_algorithm;
  431. break;
  432. case htons ( TLS_RSA_WITH_AES_256_CBC_SHA ):
  433. key_len = ( 256 / 8 );
  434. cipher = &aes_cbc_algorithm;
  435. digest = &sha1_algorithm;
  436. break;
  437. default:
  438. DBGC ( tls, "TLS %p does not support cipher %04x\n",
  439. tls, ntohs ( cipher_suite ) );
  440. return -ENOTSUP;
  441. }
  442. /* Set ciphers */
  443. if ( ( rc = tls_set_cipher ( tls, &tls->tx_cipherspec_pending, pubkey,
  444. cipher, digest, key_len ) ) != 0 )
  445. return rc;
  446. if ( ( rc = tls_set_cipher ( tls, &tls->rx_cipherspec_pending, pubkey,
  447. cipher, digest, key_len ) ) != 0 )
  448. return rc;
  449. DBGC ( tls, "TLS %p selected %s-%s-%d-%s\n", tls,
  450. pubkey->name, cipher->name, ( key_len * 8 ), digest->name );
  451. return 0;
  452. }
  453. /**
  454. * Activate next cipher suite
  455. *
  456. * @v tls TLS session
  457. * @v pending Pending cipher specification
  458. * @v active Active cipher specification to replace
  459. * @ret rc Return status code
  460. */
  461. static int tls_change_cipher ( struct tls_session *tls,
  462. struct tls_cipherspec *pending,
  463. struct tls_cipherspec *active ) {
  464. /* Sanity check */
  465. if ( /* FIXME (when pubkey is not hard-coded to RSA):
  466. * ( pending->pubkey == &pubkey_null ) || */
  467. ( pending->cipher == &cipher_null ) ||
  468. ( pending->digest == &digest_null ) ) {
  469. DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
  470. return -ENOTSUP;
  471. }
  472. tls_clear_cipher ( tls, active );
  473. memswap ( active, pending, sizeof ( *active ) );
  474. return 0;
  475. }
  476. /******************************************************************************
  477. *
  478. * Handshake verification
  479. *
  480. ******************************************************************************
  481. */
  482. /**
  483. * Add handshake record to verification hash
  484. *
  485. * @v tls TLS session
  486. * @v data Handshake record
  487. * @v len Length of handshake record
  488. */
  489. static void tls_add_handshake ( struct tls_session *tls,
  490. const void *data, size_t len ) {
  491. digest_update ( &md5_algorithm, tls->handshake_md5_ctx, data, len );
  492. digest_update ( &sha1_algorithm, tls->handshake_sha1_ctx, data, len );
  493. }
  494. /**
  495. * Calculate handshake verification hash
  496. *
  497. * @v tls TLS session
  498. * @v out Output buffer
  499. *
  500. * Calculates the MD5+SHA1 digest over all handshake messages seen so
  501. * far.
  502. */
  503. static void tls_verify_handshake ( struct tls_session *tls, void *out ) {
  504. struct digest_algorithm *md5 = &md5_algorithm;
  505. struct digest_algorithm *sha1 = &sha1_algorithm;
  506. uint8_t md5_ctx[md5->ctxsize];
  507. uint8_t sha1_ctx[sha1->ctxsize];
  508. void *md5_digest = out;
  509. void *sha1_digest = ( out + md5->digestsize );
  510. memcpy ( md5_ctx, tls->handshake_md5_ctx, sizeof ( md5_ctx ) );
  511. memcpy ( sha1_ctx, tls->handshake_sha1_ctx, sizeof ( sha1_ctx ) );
  512. digest_final ( md5, md5_ctx, md5_digest );
  513. digest_final ( sha1, sha1_ctx, sha1_digest );
  514. }
  515. /******************************************************************************
  516. *
  517. * Record handling
  518. *
  519. ******************************************************************************
  520. */
  521. /**
  522. * Transmit Handshake record
  523. *
  524. * @v tls TLS session
  525. * @v data Plaintext record
  526. * @v len Length of plaintext record
  527. * @ret rc Return status code
  528. */
  529. static int tls_send_handshake ( struct tls_session *tls,
  530. void *data, size_t len ) {
  531. /* Add to handshake digest */
  532. tls_add_handshake ( tls, data, len );
  533. /* Send record */
  534. return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
  535. }
  536. /**
  537. * Transmit Client Hello record
  538. *
  539. * @v tls TLS session
  540. * @ret rc Return status code
  541. */
  542. static int tls_send_client_hello ( struct tls_session *tls ) {
  543. struct {
  544. uint32_t type_length;
  545. uint16_t version;
  546. uint8_t random[32];
  547. uint8_t session_id_len;
  548. uint16_t cipher_suite_len;
  549. uint16_t cipher_suites[2];
  550. uint8_t compression_methods_len;
  551. uint8_t compression_methods[1];
  552. } __attribute__ (( packed )) hello;
  553. memset ( &hello, 0, sizeof ( hello ) );
  554. hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
  555. htonl ( sizeof ( hello ) -
  556. sizeof ( hello.type_length ) ) );
  557. hello.version = htons ( TLS_VERSION_TLS_1_0 );
  558. memcpy ( &hello.random, &tls->client_random, sizeof ( hello.random ) );
  559. hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
  560. hello.cipher_suites[0] = htons ( TLS_RSA_WITH_AES_128_CBC_SHA );
  561. hello.cipher_suites[1] = htons ( TLS_RSA_WITH_AES_256_CBC_SHA );
  562. hello.compression_methods_len = sizeof ( hello.compression_methods );
  563. return tls_send_handshake ( tls, &hello, sizeof ( hello ) );
  564. }
  565. /**
  566. * Transmit Client Key Exchange record
  567. *
  568. * @v tls TLS session
  569. * @ret rc Return status code
  570. */
  571. static int tls_send_client_key_exchange ( struct tls_session *tls ) {
  572. /* FIXME: Hack alert */
  573. RSA_CTX *rsa_ctx;
  574. RSA_pub_key_new ( &rsa_ctx, tls->rsa.modulus, tls->rsa.modulus_len,
  575. tls->rsa.exponent, tls->rsa.exponent_len );
  576. struct {
  577. uint32_t type_length;
  578. uint16_t encrypted_pre_master_secret_len;
  579. uint8_t encrypted_pre_master_secret[rsa_ctx->num_octets];
  580. } __attribute__ (( packed )) key_xchg;
  581. memset ( &key_xchg, 0, sizeof ( key_xchg ) );
  582. key_xchg.type_length = ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE ) |
  583. htonl ( sizeof ( key_xchg ) -
  584. sizeof ( key_xchg.type_length ) ) );
  585. key_xchg.encrypted_pre_master_secret_len
  586. = htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) );
  587. /* FIXME: Hack alert */
  588. DBGC ( tls, "RSA encrypting plaintext, modulus, exponent:\n" );
  589. DBGC_HD ( tls, &tls->pre_master_secret,
  590. sizeof ( tls->pre_master_secret ) );
  591. DBGC_HD ( tls, tls->rsa.modulus, tls->rsa.modulus_len );
  592. DBGC_HD ( tls, tls->rsa.exponent, tls->rsa.exponent_len );
  593. RSA_encrypt ( rsa_ctx, ( const uint8_t * ) &tls->pre_master_secret,
  594. sizeof ( tls->pre_master_secret ),
  595. key_xchg.encrypted_pre_master_secret, 0 );
  596. DBGC ( tls, "RSA encrypt done. Ciphertext:\n" );
  597. DBGC_HD ( tls, &key_xchg.encrypted_pre_master_secret,
  598. sizeof ( key_xchg.encrypted_pre_master_secret ) );
  599. RSA_free ( rsa_ctx );
  600. return tls_send_handshake ( tls, &key_xchg, sizeof ( key_xchg ) );
  601. }
  602. /**
  603. * Transmit Change Cipher record
  604. *
  605. * @v tls TLS session
  606. * @ret rc Return status code
  607. */
  608. static int tls_send_change_cipher ( struct tls_session *tls ) {
  609. static const uint8_t change_cipher[1] = { 1 };
  610. return tls_send_plaintext ( tls, TLS_TYPE_CHANGE_CIPHER,
  611. change_cipher, sizeof ( change_cipher ) );
  612. }
  613. /**
  614. * Transmit Finished record
  615. *
  616. * @v tls TLS session
  617. * @ret rc Return status code
  618. */
  619. static int tls_send_finished ( struct tls_session *tls ) {
  620. struct {
  621. uint32_t type_length;
  622. uint8_t verify_data[12];
  623. } __attribute__ (( packed )) finished;
  624. uint8_t digest[MD5_DIGEST_SIZE + SHA1_DIGEST_SIZE];
  625. memset ( &finished, 0, sizeof ( finished ) );
  626. finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
  627. htonl ( sizeof ( finished ) -
  628. sizeof ( finished.type_length ) ) );
  629. tls_verify_handshake ( tls, digest );
  630. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  631. finished.verify_data, sizeof ( finished.verify_data ),
  632. "client finished", digest, sizeof ( digest ) );
  633. return tls_send_handshake ( tls, &finished, sizeof ( finished ) );
  634. }
  635. /**
  636. * Receive new Change Cipher record
  637. *
  638. * @v tls TLS session
  639. * @v data Plaintext record
  640. * @v len Length of plaintext record
  641. * @ret rc Return status code
  642. */
  643. static int tls_new_change_cipher ( struct tls_session *tls,
  644. void *data, size_t len ) {
  645. int rc;
  646. if ( ( len != 1 ) || ( *( ( uint8_t * ) data ) != 1 ) ) {
  647. DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
  648. DBGC_HD ( tls, data, len );
  649. return -EINVAL;
  650. }
  651. if ( ( rc = tls_change_cipher ( tls, &tls->rx_cipherspec_pending,
  652. &tls->rx_cipherspec ) ) != 0 ) {
  653. DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
  654. tls, strerror ( rc ) );
  655. return rc;
  656. }
  657. tls->rx_seq = ~( ( uint64_t ) 0 );
  658. return 0;
  659. }
  660. /**
  661. * Receive new Alert record
  662. *
  663. * @v tls TLS session
  664. * @v data Plaintext record
  665. * @v len Length of plaintext record
  666. * @ret rc Return status code
  667. */
  668. static int tls_new_alert ( struct tls_session *tls, void *data, size_t len ) {
  669. struct {
  670. uint8_t level;
  671. uint8_t description;
  672. char next[0];
  673. } __attribute__ (( packed )) *alert = data;
  674. void *end = alert->next;
  675. /* Sanity check */
  676. if ( end != ( data + len ) ) {
  677. DBGC ( tls, "TLS %p received overlength Alert\n", tls );
  678. DBGC_HD ( tls, data, len );
  679. return -EINVAL;
  680. }
  681. switch ( alert->level ) {
  682. case TLS_ALERT_WARNING:
  683. DBGC ( tls, "TLS %p received warning alert %d\n",
  684. tls, alert->description );
  685. return 0;
  686. case TLS_ALERT_FATAL:
  687. DBGC ( tls, "TLS %p received fatal alert %d\n",
  688. tls, alert->description );
  689. return -EPERM;
  690. default:
  691. DBGC ( tls, "TLS %p received unknown alert level %d"
  692. "(alert %d)\n", tls, alert->level, alert->description );
  693. return -EIO;
  694. }
  695. }
  696. /**
  697. * Receive new Server Hello handshake record
  698. *
  699. * @v tls TLS session
  700. * @v data Plaintext handshake record
  701. * @v len Length of plaintext handshake record
  702. * @ret rc Return status code
  703. */
  704. static int tls_new_server_hello ( struct tls_session *tls,
  705. void *data, size_t len ) {
  706. struct {
  707. uint16_t version;
  708. uint8_t random[32];
  709. uint8_t session_id_len;
  710. char next[0];
  711. } __attribute__ (( packed )) *hello_a = data;
  712. struct {
  713. uint8_t session_id[hello_a->session_id_len];
  714. uint16_t cipher_suite;
  715. uint8_t compression_method;
  716. char next[0];
  717. } __attribute__ (( packed )) *hello_b = ( void * ) &hello_a->next;
  718. void *end = hello_b->next;
  719. int rc;
  720. /* Sanity check */
  721. if ( end != ( data + len ) ) {
  722. DBGC ( tls, "TLS %p received overlength Server Hello\n", tls );
  723. DBGC_HD ( tls, data, len );
  724. return -EINVAL;
  725. }
  726. /* Check protocol version */
  727. if ( ntohs ( hello_a->version ) < TLS_VERSION_TLS_1_0 ) {
  728. DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
  729. tls, ( ntohs ( hello_a->version ) >> 8 ),
  730. ( ntohs ( hello_a->version ) & 0xff ) );
  731. return -ENOTSUP;
  732. }
  733. /* Copy out server random bytes */
  734. memcpy ( &tls->server_random, &hello_a->random,
  735. sizeof ( tls->server_random ) );
  736. /* Select cipher suite */
  737. if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
  738. return rc;
  739. /* Generate secrets */
  740. tls_generate_master_secret ( tls );
  741. if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
  742. return rc;
  743. return 0;
  744. }
  745. /**
  746. * Receive new Certificate handshake record
  747. *
  748. * @v tls TLS session
  749. * @v data Plaintext handshake record
  750. * @v len Length of plaintext handshake record
  751. * @ret rc Return status code
  752. */
  753. static int tls_new_certificate ( struct tls_session *tls,
  754. void *data, size_t len ) {
  755. struct {
  756. uint8_t length[3];
  757. uint8_t certificates[0];
  758. } __attribute__ (( packed )) *certificate = data;
  759. struct {
  760. uint8_t length[3];
  761. uint8_t certificate[0];
  762. } __attribute__ (( packed )) *element =
  763. ( ( void * ) certificate->certificates );
  764. size_t elements_len = tls_uint24 ( certificate->length );
  765. void *end = ( certificate->certificates + elements_len );
  766. struct asn1_cursor cursor;
  767. int rc;
  768. /* Sanity check */
  769. if ( end != ( data + len ) ) {
  770. DBGC ( tls, "TLS %p received overlength Server Certificate\n",
  771. tls );
  772. DBGC_HD ( tls, data, len );
  773. return -EINVAL;
  774. }
  775. /* Traverse certificate chain */
  776. do {
  777. cursor.data = element->certificate;
  778. cursor.len = tls_uint24 ( element->length );
  779. if ( ( cursor.data + cursor.len ) > end ) {
  780. DBGC ( tls, "TLS %p received corrupt Server "
  781. "Certificate\n", tls );
  782. DBGC_HD ( tls, data, len );
  783. return -EINVAL;
  784. }
  785. // HACK
  786. if ( ( rc = x509_rsa_public_key ( &cursor,
  787. &tls->rsa ) ) != 0 ) {
  788. DBGC ( tls, "TLS %p cannot determine RSA public key: "
  789. "%s\n", tls, strerror ( rc ) );
  790. return rc;
  791. }
  792. return 0;
  793. element = ( cursor.data + cursor.len );
  794. } while ( element != end );
  795. return -EINVAL;
  796. }
  797. /**
  798. * Receive new Server Hello Done handshake record
  799. *
  800. * @v tls TLS session
  801. * @v data Plaintext handshake record
  802. * @v len Length of plaintext handshake record
  803. * @ret rc Return status code
  804. */
  805. static int tls_new_server_hello_done ( struct tls_session *tls,
  806. void *data, size_t len ) {
  807. struct {
  808. char next[0];
  809. } __attribute__ (( packed )) *hello_done = data;
  810. void *end = hello_done->next;
  811. /* Sanity check */
  812. if ( end != ( data + len ) ) {
  813. DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
  814. tls );
  815. DBGC_HD ( tls, data, len );
  816. return -EINVAL;
  817. }
  818. /* Check that we are ready to send the Client Key Exchange */
  819. if ( tls->tx_state != TLS_TX_NONE ) {
  820. DBGC ( tls, "TLS %p received Server Hello Done while in "
  821. "TX state %d\n", tls, tls->tx_state );
  822. return -EIO;
  823. }
  824. /* Start sending the Client Key Exchange */
  825. tls->tx_state = TLS_TX_CLIENT_KEY_EXCHANGE;
  826. return 0;
  827. }
  828. /**
  829. * Receive new Finished handshake record
  830. *
  831. * @v tls TLS session
  832. * @v data Plaintext handshake record
  833. * @v len Length of plaintext handshake record
  834. * @ret rc Return status code
  835. */
  836. static int tls_new_finished ( struct tls_session *tls,
  837. void *data, size_t len ) {
  838. /* FIXME: Handle this properly */
  839. tls->tx_state = TLS_TX_DATA;
  840. ( void ) data;
  841. ( void ) len;
  842. return 0;
  843. }
  844. /**
  845. * Receive new Handshake record
  846. *
  847. * @v tls TLS session
  848. * @v data Plaintext record
  849. * @v len Length of plaintext record
  850. * @ret rc Return status code
  851. */
  852. static int tls_new_handshake ( struct tls_session *tls,
  853. void *data, size_t len ) {
  854. struct {
  855. uint8_t type;
  856. uint8_t length[3];
  857. uint8_t payload[0];
  858. } __attribute__ (( packed )) *handshake = data;
  859. void *payload = &handshake->payload;
  860. size_t payload_len = tls_uint24 ( handshake->length );
  861. void *end = ( payload + payload_len );
  862. int rc;
  863. /* Sanity check */
  864. if ( end != ( data + len ) ) {
  865. DBGC ( tls, "TLS %p received overlength Handshake\n", tls );
  866. DBGC_HD ( tls, data, len );
  867. return -EINVAL;
  868. }
  869. switch ( handshake->type ) {
  870. case TLS_SERVER_HELLO:
  871. rc = tls_new_server_hello ( tls, payload, payload_len );
  872. break;
  873. case TLS_CERTIFICATE:
  874. rc = tls_new_certificate ( tls, payload, payload_len );
  875. break;
  876. case TLS_SERVER_HELLO_DONE:
  877. rc = tls_new_server_hello_done ( tls, payload, payload_len );
  878. break;
  879. case TLS_FINISHED:
  880. rc = tls_new_finished ( tls, payload, payload_len );
  881. break;
  882. default:
  883. DBGC ( tls, "TLS %p ignoring handshake type %d\n",
  884. tls, handshake->type );
  885. rc = 0;
  886. break;
  887. }
  888. /* Add to handshake digest (except for Hello Requests, which
  889. * are explicitly excluded).
  890. */
  891. if ( handshake->type != TLS_HELLO_REQUEST )
  892. tls_add_handshake ( tls, data, len );
  893. return rc;
  894. }
  895. /**
  896. * Receive new record
  897. *
  898. * @v tls TLS session
  899. * @v type Record type
  900. * @v data Plaintext record
  901. * @v len Length of plaintext record
  902. * @ret rc Return status code
  903. */
  904. static int tls_new_record ( struct tls_session *tls,
  905. unsigned int type, void *data, size_t len ) {
  906. switch ( type ) {
  907. case TLS_TYPE_CHANGE_CIPHER:
  908. return tls_new_change_cipher ( tls, data, len );
  909. case TLS_TYPE_ALERT:
  910. return tls_new_alert ( tls, data, len );
  911. case TLS_TYPE_HANDSHAKE:
  912. return tls_new_handshake ( tls, data, len );
  913. case TLS_TYPE_DATA:
  914. return xfer_deliver_raw ( &tls->plainstream.xfer, data, len );
  915. default:
  916. /* RFC4346 says that we should just ignore unknown
  917. * record types.
  918. */
  919. DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
  920. return 0;
  921. }
  922. }
  923. /******************************************************************************
  924. *
  925. * Record encryption/decryption
  926. *
  927. ******************************************************************************
  928. */
  929. /**
  930. * Calculate HMAC
  931. *
  932. * @v tls TLS session
  933. * @v cipherspec Cipher specification
  934. * @v seq Sequence number
  935. * @v tlshdr TLS header
  936. * @v data Data
  937. * @v len Length of data
  938. * @v mac HMAC to fill in
  939. */
  940. static void tls_hmac ( struct tls_session *tls __unused,
  941. struct tls_cipherspec *cipherspec,
  942. uint64_t seq, struct tls_header *tlshdr,
  943. const void *data, size_t len, void *hmac ) {
  944. struct digest_algorithm *digest = cipherspec->digest;
  945. uint8_t digest_ctx[digest->ctxsize];
  946. hmac_init ( digest, digest_ctx, cipherspec->mac_secret,
  947. &digest->digestsize );
  948. seq = cpu_to_be64 ( seq );
  949. hmac_update ( digest, digest_ctx, &seq, sizeof ( seq ) );
  950. hmac_update ( digest, digest_ctx, tlshdr, sizeof ( *tlshdr ) );
  951. hmac_update ( digest, digest_ctx, data, len );
  952. hmac_final ( digest, digest_ctx, cipherspec->mac_secret,
  953. &digest->digestsize, hmac );
  954. }
  955. /**
  956. * Allocate and assemble stream-ciphered record from data and MAC portions
  957. *
  958. * @v tls TLS session
  959. * @ret data Data
  960. * @ret len Length of data
  961. * @ret digest MAC digest
  962. * @ret plaintext_len Length of plaintext record
  963. * @ret plaintext Allocated plaintext record
  964. */
  965. static void * __malloc tls_assemble_stream ( struct tls_session *tls,
  966. const void *data, size_t len,
  967. void *digest, size_t *plaintext_len ) {
  968. size_t mac_len = tls->tx_cipherspec.digest->digestsize;
  969. void *plaintext;
  970. void *content;
  971. void *mac;
  972. /* Calculate stream-ciphered struct length */
  973. *plaintext_len = ( len + mac_len );
  974. /* Allocate stream-ciphered struct */
  975. plaintext = malloc ( *plaintext_len );
  976. if ( ! plaintext )
  977. return NULL;
  978. content = plaintext;
  979. mac = ( content + len );
  980. /* Fill in stream-ciphered struct */
  981. memcpy ( content, data, len );
  982. memcpy ( mac, digest, mac_len );
  983. return plaintext;
  984. }
  985. /**
  986. * Allocate and assemble block-ciphered record from data and MAC portions
  987. *
  988. * @v tls TLS session
  989. * @ret data Data
  990. * @ret len Length of data
  991. * @ret digest MAC digest
  992. * @ret plaintext_len Length of plaintext record
  993. * @ret plaintext Allocated plaintext record
  994. */
  995. static void * tls_assemble_block ( struct tls_session *tls,
  996. const void *data, size_t len,
  997. void *digest, size_t *plaintext_len ) {
  998. size_t blocksize = tls->tx_cipherspec.cipher->blocksize;
  999. size_t iv_len = blocksize;
  1000. size_t mac_len = tls->tx_cipherspec.digest->digestsize;
  1001. size_t padding_len;
  1002. void *plaintext;
  1003. void *iv;
  1004. void *content;
  1005. void *mac;
  1006. void *padding;
  1007. /* FIXME: TLSv1.1 has an explicit IV */
  1008. iv_len = 0;
  1009. /* Calculate block-ciphered struct length */
  1010. padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
  1011. *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
  1012. /* Allocate block-ciphered struct */
  1013. plaintext = malloc ( *plaintext_len );
  1014. if ( ! plaintext )
  1015. return NULL;
  1016. iv = plaintext;
  1017. content = ( iv + iv_len );
  1018. mac = ( content + len );
  1019. padding = ( mac + mac_len );
  1020. /* Fill in block-ciphered struct */
  1021. memset ( iv, 0, iv_len );
  1022. memcpy ( content, data, len );
  1023. memcpy ( mac, digest, mac_len );
  1024. memset ( padding, padding_len, ( padding_len + 1 ) );
  1025. return plaintext;
  1026. }
  1027. /**
  1028. * Send plaintext record
  1029. *
  1030. * @v tls TLS session
  1031. * @v type Record type
  1032. * @v data Plaintext record
  1033. * @v len Length of plaintext record
  1034. * @ret rc Return status code
  1035. */
  1036. static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
  1037. const void *data, size_t len ) {
  1038. struct tls_header plaintext_tlshdr;
  1039. struct tls_header *tlshdr;
  1040. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
  1041. void *plaintext = NULL;
  1042. size_t plaintext_len;
  1043. struct io_buffer *ciphertext = NULL;
  1044. size_t ciphertext_len;
  1045. size_t mac_len = cipherspec->digest->digestsize;
  1046. uint8_t mac[mac_len];
  1047. int rc;
  1048. /* Construct header */
  1049. plaintext_tlshdr.type = type;
  1050. plaintext_tlshdr.version = htons ( TLS_VERSION_TLS_1_0 );
  1051. plaintext_tlshdr.length = htons ( len );
  1052. /* Calculate MAC */
  1053. tls_hmac ( tls, cipherspec, tls->tx_seq, &plaintext_tlshdr,
  1054. data, len, mac );
  1055. /* Allocate and assemble plaintext struct */
  1056. if ( is_stream_cipher ( cipherspec->cipher ) ) {
  1057. plaintext = tls_assemble_stream ( tls, data, len, mac,
  1058. &plaintext_len );
  1059. } else {
  1060. plaintext = tls_assemble_block ( tls, data, len, mac,
  1061. &plaintext_len );
  1062. }
  1063. if ( ! plaintext ) {
  1064. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1065. "plaintext\n", tls, plaintext_len );
  1066. rc = -ENOMEM;
  1067. goto done;
  1068. }
  1069. DBGC2 ( tls, "Sending plaintext data:\n" );
  1070. DBGC2_HD ( tls, plaintext, plaintext_len );
  1071. /* Allocate ciphertext */
  1072. ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
  1073. ciphertext = xfer_alloc_iob ( &tls->cipherstream.xfer,
  1074. ciphertext_len );
  1075. if ( ! ciphertext ) {
  1076. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1077. "ciphertext\n", tls, ciphertext_len );
  1078. rc = -ENOMEM;
  1079. goto done;
  1080. }
  1081. /* Assemble ciphertext */
  1082. tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
  1083. tlshdr->type = type;
  1084. tlshdr->version = htons ( TLS_VERSION_TLS_1_0 );
  1085. tlshdr->length = htons ( plaintext_len );
  1086. memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
  1087. cipherspec->cipher->ctxsize );
  1088. cipher_encrypt ( cipherspec->cipher, cipherspec->cipher_next_ctx,
  1089. plaintext, iob_put ( ciphertext, plaintext_len ),
  1090. plaintext_len );
  1091. /* Free plaintext as soon as possible to conserve memory */
  1092. free ( plaintext );
  1093. plaintext = NULL;
  1094. /* Send ciphertext */
  1095. rc = xfer_deliver_iob ( &tls->cipherstream.xfer, ciphertext );
  1096. ciphertext = NULL;
  1097. if ( rc != 0 ) {
  1098. DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
  1099. tls, strerror ( rc ) );
  1100. goto done;
  1101. }
  1102. /* Update TX state machine to next record */
  1103. tls->tx_seq += 1;
  1104. memcpy ( tls->tx_cipherspec.cipher_ctx,
  1105. tls->tx_cipherspec.cipher_next_ctx,
  1106. tls->tx_cipherspec.cipher->ctxsize );
  1107. done:
  1108. free ( plaintext );
  1109. free_iob ( ciphertext );
  1110. return rc;
  1111. }
  1112. /**
  1113. * Split stream-ciphered record into data and MAC portions
  1114. *
  1115. * @v tls TLS session
  1116. * @v plaintext Plaintext record
  1117. * @v plaintext_len Length of record
  1118. * @ret data Data
  1119. * @ret len Length of data
  1120. * @ret digest MAC digest
  1121. * @ret rc Return status code
  1122. */
  1123. static int tls_split_stream ( struct tls_session *tls,
  1124. void *plaintext, size_t plaintext_len,
  1125. void **data, size_t *len, void **digest ) {
  1126. void *content;
  1127. size_t content_len;
  1128. void *mac;
  1129. size_t mac_len;
  1130. /* Decompose stream-ciphered data */
  1131. mac_len = tls->rx_cipherspec.digest->digestsize;
  1132. if ( plaintext_len < mac_len ) {
  1133. DBGC ( tls, "TLS %p received underlength record\n", tls );
  1134. DBGC_HD ( tls, plaintext, plaintext_len );
  1135. return -EINVAL;
  1136. }
  1137. content_len = ( plaintext_len - mac_len );
  1138. content = plaintext;
  1139. mac = ( content + content_len );
  1140. /* Fill in return values */
  1141. *data = content;
  1142. *len = content_len;
  1143. *digest = mac;
  1144. return 0;
  1145. }
  1146. /**
  1147. * Split block-ciphered record into data and MAC portions
  1148. *
  1149. * @v tls TLS session
  1150. * @v plaintext Plaintext record
  1151. * @v plaintext_len Length of record
  1152. * @ret data Data
  1153. * @ret len Length of data
  1154. * @ret digest MAC digest
  1155. * @ret rc Return status code
  1156. */
  1157. static int tls_split_block ( struct tls_session *tls,
  1158. void *plaintext, size_t plaintext_len,
  1159. void **data, size_t *len,
  1160. void **digest ) {
  1161. void *iv;
  1162. size_t iv_len;
  1163. void *content;
  1164. size_t content_len;
  1165. void *mac;
  1166. size_t mac_len;
  1167. void *padding;
  1168. size_t padding_len;
  1169. unsigned int i;
  1170. /* Decompose block-ciphered data */
  1171. if ( plaintext_len < 1 ) {
  1172. DBGC ( tls, "TLS %p received underlength record\n", tls );
  1173. DBGC_HD ( tls, plaintext, plaintext_len );
  1174. return -EINVAL;
  1175. }
  1176. iv_len = tls->rx_cipherspec.cipher->blocksize;
  1177. /* FIXME: TLSv1.1 uses an explicit IV */
  1178. iv_len = 0;
  1179. mac_len = tls->rx_cipherspec.digest->digestsize;
  1180. padding_len = *( ( uint8_t * ) ( plaintext + plaintext_len - 1 ) );
  1181. if ( plaintext_len < ( iv_len + mac_len + padding_len + 1 ) ) {
  1182. DBGC ( tls, "TLS %p received underlength record\n", tls );
  1183. DBGC_HD ( tls, plaintext, plaintext_len );
  1184. return -EINVAL;
  1185. }
  1186. content_len = ( plaintext_len - iv_len - mac_len - padding_len - 1 );
  1187. iv = plaintext;
  1188. content = ( iv + iv_len );
  1189. mac = ( content + content_len );
  1190. padding = ( mac + mac_len );
  1191. /* Verify padding bytes */
  1192. for ( i = 0 ; i < padding_len ; i++ ) {
  1193. if ( *( ( uint8_t * ) ( padding + i ) ) != padding_len ) {
  1194. DBGC ( tls, "TLS %p received bad padding\n", tls );
  1195. DBGC_HD ( tls, plaintext, plaintext_len );
  1196. return -EINVAL;
  1197. }
  1198. }
  1199. /* Fill in return values */
  1200. *data = content;
  1201. *len = content_len;
  1202. *digest = mac;
  1203. return 0;
  1204. }
  1205. /**
  1206. * Receive new ciphertext record
  1207. *
  1208. * @v tls TLS session
  1209. * @v tlshdr Record header
  1210. * @v ciphertext Ciphertext record
  1211. * @ret rc Return status code
  1212. */
  1213. static int tls_new_ciphertext ( struct tls_session *tls,
  1214. struct tls_header *tlshdr, void *ciphertext ) {
  1215. struct tls_header plaintext_tlshdr;
  1216. struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
  1217. size_t record_len = ntohs ( tlshdr->length );
  1218. void *plaintext = NULL;
  1219. void *data;
  1220. size_t len;
  1221. void *mac;
  1222. size_t mac_len = cipherspec->digest->digestsize;
  1223. uint8_t verify_mac[mac_len];
  1224. int rc;
  1225. /* Allocate buffer for plaintext */
  1226. plaintext = malloc ( record_len );
  1227. if ( ! plaintext ) {
  1228. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1229. "decryption buffer\n", tls, record_len );
  1230. rc = -ENOMEM;
  1231. goto done;
  1232. }
  1233. /* Decrypt the record */
  1234. cipher_decrypt ( cipherspec->cipher, cipherspec->cipher_ctx,
  1235. ciphertext, plaintext, record_len );
  1236. /* Split record into content and MAC */
  1237. if ( is_stream_cipher ( cipherspec->cipher ) ) {
  1238. if ( ( rc = tls_split_stream ( tls, plaintext, record_len,
  1239. &data, &len, &mac ) ) != 0 )
  1240. goto done;
  1241. } else {
  1242. if ( ( rc = tls_split_block ( tls, plaintext, record_len,
  1243. &data, &len, &mac ) ) != 0 )
  1244. goto done;
  1245. }
  1246. /* Verify MAC */
  1247. plaintext_tlshdr.type = tlshdr->type;
  1248. plaintext_tlshdr.version = tlshdr->version;
  1249. plaintext_tlshdr.length = htons ( len );
  1250. tls_hmac ( tls, cipherspec, tls->rx_seq, &plaintext_tlshdr,
  1251. data, len, verify_mac);
  1252. if ( memcmp ( mac, verify_mac, mac_len ) != 0 ) {
  1253. DBGC ( tls, "TLS %p failed MAC verification\n", tls );
  1254. DBGC_HD ( tls, plaintext, record_len );
  1255. goto done;
  1256. }
  1257. DBGC2 ( tls, "Received plaintext data:\n" );
  1258. DBGC2_HD ( tls, data, len );
  1259. /* Process plaintext record */
  1260. if ( ( rc = tls_new_record ( tls, tlshdr->type, data, len ) ) != 0 )
  1261. goto done;
  1262. rc = 0;
  1263. done:
  1264. free ( plaintext );
  1265. return rc;
  1266. }
  1267. /******************************************************************************
  1268. *
  1269. * Plaintext stream operations
  1270. *
  1271. ******************************************************************************
  1272. */
  1273. /**
  1274. * Close interface
  1275. *
  1276. * @v xfer Plainstream data transfer interface
  1277. * @v rc Reason for close
  1278. */
  1279. static void tls_plainstream_close ( struct xfer_interface *xfer, int rc ) {
  1280. struct tls_session *tls =
  1281. container_of ( xfer, struct tls_session, plainstream.xfer );
  1282. tls_close ( tls, rc );
  1283. }
  1284. /**
  1285. * Check flow control window
  1286. *
  1287. * @v xfer Plainstream data transfer interface
  1288. * @ret len Length of window
  1289. */
  1290. static size_t tls_plainstream_window ( struct xfer_interface *xfer ) {
  1291. struct tls_session *tls =
  1292. container_of ( xfer, struct tls_session, plainstream.xfer );
  1293. /* Block window unless we are ready to accept data */
  1294. if ( tls->tx_state != TLS_TX_DATA )
  1295. return 0;
  1296. return filter_window ( xfer );
  1297. }
  1298. /**
  1299. * Deliver datagram as raw data
  1300. *
  1301. * @v xfer Plainstream data transfer interface
  1302. * @v data Data buffer
  1303. * @v len Length of data buffer
  1304. * @ret rc Return status code
  1305. */
  1306. static int tls_plainstream_deliver_raw ( struct xfer_interface *xfer,
  1307. const void *data, size_t len ) {
  1308. struct tls_session *tls =
  1309. container_of ( xfer, struct tls_session, plainstream.xfer );
  1310. /* Refuse unless we are ready to accept data */
  1311. if ( tls->tx_state != TLS_TX_DATA )
  1312. return -ENOTCONN;
  1313. return tls_send_plaintext ( tls, TLS_TYPE_DATA, data, len );
  1314. }
  1315. /** TLS plaintext stream operations */
  1316. static struct xfer_interface_operations tls_plainstream_operations = {
  1317. .close = tls_plainstream_close,
  1318. .vredirect = ignore_xfer_vredirect,
  1319. .window = tls_plainstream_window,
  1320. .alloc_iob = default_xfer_alloc_iob,
  1321. .deliver_iob = xfer_deliver_as_raw,
  1322. .deliver_raw = tls_plainstream_deliver_raw,
  1323. };
  1324. /******************************************************************************
  1325. *
  1326. * Ciphertext stream operations
  1327. *
  1328. ******************************************************************************
  1329. */
  1330. /**
  1331. * Close interface
  1332. *
  1333. * @v xfer Plainstream data transfer interface
  1334. * @v rc Reason for close
  1335. */
  1336. static void tls_cipherstream_close ( struct xfer_interface *xfer, int rc ) {
  1337. struct tls_session *tls =
  1338. container_of ( xfer, struct tls_session, cipherstream.xfer );
  1339. tls_close ( tls, rc );
  1340. }
  1341. /**
  1342. * Handle received TLS header
  1343. *
  1344. * @v tls TLS session
  1345. * @ret rc Returned status code
  1346. */
  1347. static int tls_newdata_process_header ( struct tls_session *tls ) {
  1348. size_t data_len = ntohs ( tls->rx_header.length );
  1349. /* Allocate data buffer now that we know the length */
  1350. assert ( tls->rx_data == NULL );
  1351. tls->rx_data = malloc ( data_len );
  1352. if ( ! tls->rx_data ) {
  1353. DBGC ( tls, "TLS %p could not allocate %zd bytes "
  1354. "for receive buffer\n", tls, data_len );
  1355. return -ENOMEM;
  1356. }
  1357. /* Move to data state */
  1358. tls->rx_state = TLS_RX_DATA;
  1359. return 0;
  1360. }
  1361. /**
  1362. * Handle received TLS data payload
  1363. *
  1364. * @v tls TLS session
  1365. * @ret rc Returned status code
  1366. */
  1367. static int tls_newdata_process_data ( struct tls_session *tls ) {
  1368. int rc;
  1369. /* Process record */
  1370. if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
  1371. tls->rx_data ) ) != 0 )
  1372. return rc;
  1373. /* Increment RX sequence number */
  1374. tls->rx_seq += 1;
  1375. /* Free data buffer */
  1376. free ( tls->rx_data );
  1377. tls->rx_data = NULL;
  1378. /* Return to header state */
  1379. tls->rx_state = TLS_RX_HEADER;
  1380. return 0;
  1381. }
  1382. /**
  1383. * Receive new ciphertext
  1384. *
  1385. * @v app Stream application
  1386. * @v data Data received
  1387. * @v len Length of received data
  1388. * @ret rc Return status code
  1389. */
  1390. static int tls_cipherstream_deliver_raw ( struct xfer_interface *xfer,
  1391. const void *data, size_t len ) {
  1392. struct tls_session *tls =
  1393. container_of ( xfer, struct tls_session, cipherstream.xfer );
  1394. size_t frag_len;
  1395. void *buf;
  1396. size_t buf_len;
  1397. int ( * process ) ( struct tls_session *tls );
  1398. int rc;
  1399. while ( len ) {
  1400. /* Select buffer according to current state */
  1401. switch ( tls->rx_state ) {
  1402. case TLS_RX_HEADER:
  1403. buf = &tls->rx_header;
  1404. buf_len = sizeof ( tls->rx_header );
  1405. process = tls_newdata_process_header;
  1406. break;
  1407. case TLS_RX_DATA:
  1408. buf = tls->rx_data;
  1409. buf_len = ntohs ( tls->rx_header.length );
  1410. process = tls_newdata_process_data;
  1411. break;
  1412. default:
  1413. assert ( 0 );
  1414. return -EINVAL;
  1415. }
  1416. /* Copy data portion to buffer */
  1417. frag_len = ( buf_len - tls->rx_rcvd );
  1418. if ( frag_len > len )
  1419. frag_len = len;
  1420. memcpy ( ( buf + tls->rx_rcvd ), data, frag_len );
  1421. tls->rx_rcvd += frag_len;
  1422. data += frag_len;
  1423. len -= frag_len;
  1424. /* Process data if buffer is now full */
  1425. if ( tls->rx_rcvd == buf_len ) {
  1426. if ( ( rc = process ( tls ) ) != 0 ) {
  1427. tls_close ( tls, rc );
  1428. return rc;
  1429. }
  1430. tls->rx_rcvd = 0;
  1431. }
  1432. }
  1433. return 0;
  1434. }
  1435. /** TLS ciphertext stream operations */
  1436. static struct xfer_interface_operations tls_cipherstream_operations = {
  1437. .close = tls_cipherstream_close,
  1438. .vredirect = xfer_vopen,
  1439. .window = filter_window,
  1440. .alloc_iob = default_xfer_alloc_iob,
  1441. .deliver_iob = xfer_deliver_as_raw,
  1442. .deliver_raw = tls_cipherstream_deliver_raw,
  1443. };
  1444. /******************************************************************************
  1445. *
  1446. * Controlling process
  1447. *
  1448. ******************************************************************************
  1449. */
  1450. /**
  1451. * TLS TX state machine
  1452. *
  1453. * @v process TLS process
  1454. */
  1455. static void tls_step ( struct process *process ) {
  1456. struct tls_session *tls =
  1457. container_of ( process, struct tls_session, process );
  1458. int rc;
  1459. /* Wait for cipherstream to become ready */
  1460. if ( ! xfer_window ( &tls->cipherstream.xfer ) )
  1461. return;
  1462. switch ( tls->tx_state ) {
  1463. case TLS_TX_NONE:
  1464. /* Nothing to do */
  1465. break;
  1466. case TLS_TX_CLIENT_HELLO:
  1467. /* Send Client Hello */
  1468. if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
  1469. DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
  1470. tls, strerror ( rc ) );
  1471. goto err;
  1472. }
  1473. tls->tx_state = TLS_TX_NONE;
  1474. break;
  1475. case TLS_TX_CLIENT_KEY_EXCHANGE:
  1476. /* Send Client Key Exchange */
  1477. if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
  1478. DBGC ( tls, "TLS %p could send Client Key Exchange: "
  1479. "%s\n", tls, strerror ( rc ) );
  1480. goto err;
  1481. }
  1482. tls->tx_state = TLS_TX_CHANGE_CIPHER;
  1483. break;
  1484. case TLS_TX_CHANGE_CIPHER:
  1485. /* Send Change Cipher, and then change the cipher in use */
  1486. if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
  1487. DBGC ( tls, "TLS %p could not send Change Cipher: "
  1488. "%s\n", tls, strerror ( rc ) );
  1489. goto err;
  1490. }
  1491. if ( ( rc = tls_change_cipher ( tls,
  1492. &tls->tx_cipherspec_pending,
  1493. &tls->tx_cipherspec )) != 0 ){
  1494. DBGC ( tls, "TLS %p could not activate TX cipher: "
  1495. "%s\n", tls, strerror ( rc ) );
  1496. goto err;
  1497. }
  1498. tls->tx_seq = 0;
  1499. tls->tx_state = TLS_TX_FINISHED;
  1500. break;
  1501. case TLS_TX_FINISHED:
  1502. /* Send Finished */
  1503. if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
  1504. DBGC ( tls, "TLS %p could not send Finished: %s\n",
  1505. tls, strerror ( rc ) );
  1506. goto err;
  1507. }
  1508. tls->tx_state = TLS_TX_NONE;
  1509. break;
  1510. case TLS_TX_DATA:
  1511. /* Nothing to do */
  1512. break;
  1513. default:
  1514. assert ( 0 );
  1515. }
  1516. return;
  1517. err:
  1518. tls_close ( tls, rc );
  1519. }
  1520. /******************************************************************************
  1521. *
  1522. * Instantiator
  1523. *
  1524. ******************************************************************************
  1525. */
  1526. int add_tls ( struct xfer_interface *xfer, struct xfer_interface **next ) {
  1527. struct tls_session *tls;
  1528. /* Allocate and initialise TLS structure */
  1529. tls = malloc ( sizeof ( *tls ) );
  1530. if ( ! tls )
  1531. return -ENOMEM;
  1532. memset ( tls, 0, sizeof ( *tls ) );
  1533. tls->refcnt.free = free_tls;
  1534. filter_init ( &tls->plainstream, &tls_plainstream_operations,
  1535. &tls->cipherstream, &tls_cipherstream_operations,
  1536. &tls->refcnt );
  1537. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  1538. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  1539. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  1540. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  1541. tls->client_random.gmt_unix_time = 0;
  1542. tls_generate_random ( &tls->client_random.random,
  1543. ( sizeof ( tls->client_random.random ) ) );
  1544. tls->pre_master_secret.version = htons ( TLS_VERSION_TLS_1_0 );
  1545. tls_generate_random ( &tls->pre_master_secret.random,
  1546. ( sizeof ( tls->pre_master_secret.random ) ) );
  1547. digest_init ( &md5_algorithm, tls->handshake_md5_ctx );
  1548. digest_init ( &sha1_algorithm, tls->handshake_sha1_ctx );
  1549. tls->tx_state = TLS_TX_CLIENT_HELLO;
  1550. process_init ( &tls->process, tls_step, &tls->refcnt );
  1551. /* Attach to parent interface, mortalise self, and return */
  1552. xfer_plug_plug ( &tls->plainstream.xfer, xfer );
  1553. *next = &tls->cipherstream.xfer;
  1554. ref_put ( &tls->refcnt );
  1555. return 0;
  1556. }